76 Commits

Author SHA1 Message Date
mnovak 7322bbd856 [docs] Roadmap: Phase 3 status and handover 2026-11-08 12:57:24 +01:00
mnovak 0213021bb1 [control] Fix round 4: a device change during an engine switch is never skipped silently (devices_problem until the serving engine is told), and every switch ends by telling the engine that serves, also after going back 2026-11-08 12:48:57 +01:00
mnovak c45dafa2a3 [tests] Tests first, fix round 4: a revocation during a switch to Caddy, and during a failed switch away from Caddy, is in force when the switch ends (red) 2026-11-08 12:40:24 +01:00
mnovak 4d87537a76 [control] Fix round 3: revocations never wait for an apply (files and edge at once; under Caddy the reload is left to the end of a running trial), confirmed before the deadline is claimed, the guard marks a trial expired only after a verified load and retries, caddy-revert clears a stale deadline when Pingora serves 2026-11-08 12:28:35 +01:00
mnovak 09b8313a04 [tests] Tests first, fix round 3: a revocation during a watch is in force at once (Pingora) or when the apply ends (Caddy), a device revoked under Caddy is refused, caddy-revert with Pingora serving clears a stale deadline (red) 2026-11-08 12:21:36 +01:00
mnovak 057abbc954 [web] Design re-check: the engine chip closes its popover, Show details on every pause, popover grammar, share links off while Caddy serves, renewal copy 2026-11-08 12:04:14 +01:00
mnovak 457aea86ca [repo] NixOS and docs: ianitor-caddy-guard with caddy-fallback, caddy-revert after every control stop, admin socket only for control, Caddy trial deadline in the engine-switch VM test, trusted proxies stay off beside Caddy 2026-11-08 12:04:14 +01:00
mnovak 23a283ece9 [control] Fix round 2: Caddy rereads its files on every load and the served certificate is checked, Caddy trials get a deadline outside control (caddy-guard, caddy-revert), the watch under Caddy judges upstreams as edge does, a reload of Caddy during the watch is noticed and device changes wait for the apply, stricter root key scan, IPv4-mapped trusted proxies 2026-11-08 12:04:13 +01:00
mnovak ba3a060b2e [tests] Tests first, fix round 2: same caddy.json reload rereads certificates, forward-auth hosts kept under Caddy as under edge, crash mid-trial under Caddy, Caddy reloaded during the watch, watching crash point, caddy-revert after a crash, TLS 1.2 device after a bad ALPN (red) 2026-11-08 11:48:10 +01:00
mnovak 503916492d [web] Design review: last row's menu not clipped, Hostname focused after loading, popover closes on Esc and outside click, phone engine chip in the top bar, paused and needs-attention copy with Restore in the panel, change bar offers and countdown, focus after share and kept, fingerprint check when signing by hand, draft kept through sign-in 2026-11-08 11:21:44 +01:00
mnovak b24ffdf9db [control] Design review: Caddy differences per host in fallback_ready, active apply kind, hosts and watch end, capped device end date, CSR fingerprint for signing by hand, crash points exit without SIGABRT 2026-11-08 11:21:43 +01:00
mnovak 3bf5fa0e1a [control] QC minors: device install links open a page and download on POST (never listed), approve and install failures show on the request and the CLI waits, PBKDF2 floor, private pki dirs or an error, trusted_proxies for a proxy in front, a placeholder keeps the device allow list from being empty (Caddy refuses that) 2026-11-08 11:02:50 +01:00
mnovak bc336d1188 [repo] NixOS and docs: Caddy admin socket for changes under Caddy, polkit start/stop only, edge never stops restarting, openssl in the VM tests, beside-Caddy without secrets in argv, pinned Ianitor rev, X-Served-By trial marker 2026-11-08 10:49:42 +01:00
mnovak e84eb1ba74 [control] Fix round 1: changes apply while Caddy serves (admin socket, watch through Caddy), revocations that fail are errors and catch up, proof only on the forward-auth UI host, root keys found by content, intermediates checked before install, stale SNI cleared before each handshake 2026-11-08 10:49:31 +01:00
mnovak 0749119f19 [tests] Tests first, fix round 1: proof only on the forward-auth UI host, revocations that cannot be written, root key files by content, intermediates that cannot issue, stale SNI after a failed or resumed handshake, edge re-reads the allow list, changes apply while Caddy serves, Hostname focus (red) 2026-11-08 10:26:31 +01:00
mnovak e2a777882c [control] Root-key refusal test: a control that does not refuse is killed after 20 s instead of hanging the suite 2026-11-08 00:10:26 +01:00
mnovak b85c38f615 [repo] VM tests: no clash with the driver's log name (the drivers of all four build) 2026-11-08 00:06:37 +01:00
mnovak ca9bf3fdd4 [repo] NixOS: flake with the release build (test hooks off) and the web UI, services.ianitor module (edge, control, caddy-fallback, engine-select, per-boot UI proof, polkit for exactly two units), four VM tests, deploy/test-access.sh 2026-11-08 00:04:13 +01:00
mnovak a61dfd854f [web] Decisions applied: openssl signing by hand with the .ext file, Sign out link, renew soon 30 days before a device certificate ends 2026-11-07 23:48:44 +01:00
mnovak 9933f55242 [control] Mark's UI decisions: Remote-Name shown with the proof, [ui] logout_url for Sign out, openssl signing files for the manual intermediate step, engine.not_ready, server sentences for the eight generic codes 2026-11-07 23:48:43 +01:00
mnovak 3e326e85a0 [web] The web UI: hosts, add/edit with apply progress, undo, history and restore, share links, engine switch, certificates and device installs, signing by hand, settings and tokens; smoke test counts every §4 flow's clicks 2026-11-07 23:44:27 +01:00
mnovak aed5fbfcff [control] Overview for the UI: who is looking (viewer) and the underlying pause reason, so the UI offers the right action 2026-11-07 23:44:25 +01:00
mnovak f9dd2247f8 [control] Dev mode: a throw-away Domi root signs the first intermediate at start, so tls = "domi" works for any name; --ui-dir serves a built UI 2026-11-07 23:24:45 +01:00
mnovak 6237e721d6 [control] Test hooks: IANITOR_TEST_CRASH_AT and IANITOR_TEST_FAIL_WRITE only with the default test-hooks feature; a --no-default-features build has neither 2026-11-07 23:23:51 +01:00
mnovak 12886a1d31 [control] Engine switch: POST /engine through a Units abstraction (systemctl via polkit, a fake in tests); engine file first, back to the old engine if the new one does not serve; changes and share links wait while Caddy serves 2026-11-07 23:22:59 +01:00
mnovak c18ae154ad [control] Domi CA and UI sign-in: intermediate renewal by CSR with manual offline signing, domi host certificates, device requests approved by code, one-time PKCS#12 installs, revocation; Remote-User trusted only with edge's per-boot proof 2026-11-07 23:21:49 +01:00
mnovak 211b851c3e [control] Tests first: Domi CA flows through the API (offline-signed intermediate, domi host chains, device approval by code, one-time install, revocation, no root key) and UI sign-in that refuses a forged Remote-User (red) 2026-11-07 23:11:05 +01:00
mnovak a5190acc3b [edge] Device certificates as Caddy does them: no certificate on a device host fails the handshake, a Host other than the SNI name is 421; diff corpus gains six device cases 2026-11-07 22:55:37 +01:00
mnovak 3d8f524d00 [edge] Device certificates: mTLS on hosts with device_certs only (asked per SNI), chain to the Domi CA bundle and the allow list in the handshake, checked again per request; 403 without one 2026-11-07 22:49:32 +01:00
mnovak 4054427b62 [edge] Tests first: a Domi device cert is accepted for mTLS, a self-signed one with the same subject, an unlisted one and none are not (red) 2026-11-07 22:46:08 +01:00
mnovak 18da3f5d5a [core] Device certificates: device_certs host field; edge config v3 and Caddy client_authentication with a CA bundle and an allow list, 403 without a certificate 2026-11-07 22:46:07 +01:00
mnovak dc23bfe842 [core] Domi CA: offline root (10 y, pathLen 1), intermediate from a CSR (1 y, pathLen 0), server (90 d) and device (1 y) leaves, encrypted keys, match codes 2026-11-07 22:41:29 +01:00
mnovak cde0c3ea3b [core] Tests first: the Domi CA chains to the root, a leaf cannot sign, expired and wrong-name certs are rejected (red) 2026-11-07 22:40:56 +01:00
mnovak 7cb5715580 [docs] Custos ticket: the CSR-signing operation with match-code approval that Custos does not have yet 2026-11-07 22:40:38 +01:00
mnovak cb04bff74e [repo] Merge: Mark's decisions on the open points (PR #4) 2026-11-07 22:18:05 +01:00
mnovak 24009414de [docs] Decisions: runtime engine switch, share-link password and deny list, accepted 4th clicks, murex palette, LE staging in phase 3 2026-11-07 22:17:52 +01:00
mnovak 1adfa05640 [repo] Merge: Phase 2 control plane (PR #3) 2026-11-07 20:03:28 +01:00
mnovak 83a857ad80 [docs] Roadmap: final Phase 2 test counts and the open diff flake 2026-11-07 20:02:51 +01:00
mnovak afc3477b5c [control] Atomic writes: a temporary name unique per write (pid, counter, random), so two writers of one file never collide; same for edge's epoch floor 2026-11-07 19:57:06 +01:00
mnovak 7863202e3a [core] Share paths: invisible characters (default-ignorable code points, combining marks) do not hide a dot-only segment 2026-11-07 19:57:06 +01:00
mnovak 443d7457d2 [docs] Roadmap: Phase 2 status and handover 2026-11-07 19:48:29 +01:00
mnovak 432ae0f803 [tests] Ports and Caddy: test ports come from outside the ephemeral range, and a Caddy start that does not come up is retried 2026-11-07 19:45:18 +01:00
mnovak 83b7b3b7d6 [edge] Epoch floor: an unreadable or corrupt floor refuses share links instead of resetting to 0; directory fsync'ed after the write 2026-11-07 19:41:53 +01:00
mnovak cbb3e41ca7 [core] Share paths: judge dot segments on the NFKC form, so look-alike dots and spaces inside names pass; refuse slash look-alikes and broken escapes like %+f 2026-11-07 19:40:49 +01:00
mnovak 17f26f94a3 [control] Files retry: only in the apply worker under the lock, reloads edge to what it writes, drops only the journal of the apply that caused the pause; swallowed aborts and pauses logged; CLI owner check before creating the state dir 2026-11-07 19:39:49 +01:00
mnovak e28b084a19 [control] Tests first: a request during a Restore's watch never writes the unverified head or drops its journal (red) 2026-11-07 19:37:04 +01:00
mnovak 421800ec18 [core] Format: rustfmt on the URL redaction tests 2026-11-07 19:22:40 +01:00
mnovak 85edfa7128 [repo] Hook self-test: keep its source files next to the work dir by absolute path and remove them first, so a run leaves nothing behind 2026-11-07 19:22:32 +01:00
mnovak 60fb4b63ee [edge] Share fixes: revocation epoch floor kept in edge's own state across restarts, every share=ish1. parameter stripped (also encoded) 2026-11-07 19:22:03 +01:00
mnovak 7d3af00720 [control] Share and token fixes: settle the epoch before minting, mint in its own task so a dropped client frees its key, token checks off the async threads, CLI refuses to run as another user than the state dir's owner 2026-11-07 19:20:05 +01:00
mnovak 43918943da [core] Share paths and errors: decode once and refuse invalid UTF-8 and any NFKC look-alike of path structure, dots before any escape; hide everything before the last @ of a URL 2026-11-07 19:18:17 +01:00
mnovak dd10557b87 [control] Pause fixes: Restore waits until an unsaved pause is on disk, unwritable config files pause with a way out, a failed promote at start starts paused, a revert that cannot see edge is not reverted 2026-11-07 19:17:16 +01:00
mnovak 339882ec96 [control] Tests first: a Restore never drops an unsaved pause, a revert that cannot see edge is not called reverted (red) 2026-11-07 19:14:29 +01:00
mnovak 00f8dffc6a [tests] Ports: never hand out the same free port twice in one process, so parallel tests cannot reach each other's servers 2026-11-07 19:05:13 +01:00
mnovak 99b2a3a1a5 [docs] API: what errors may repeat, Idempotency-Key in progress and limits, where a minted URL is held 2026-11-07 18:57:54 +01:00
mnovak f382fe2f76 [control] API fixes: atomic Idempotency-Key reservation, no echo of odd field names or path parameters, askpass answers only password prompts, file protocol not forced, token test split on the known prefix, serialisation test without second-resolution times 2026-11-07 18:57:54 +01:00
mnovak 54574702ea [core] Format: rustfmt on the path and redaction changes 2026-11-07 18:57:53 +01:00
mnovak 2b66729f1b [core] Share paths and errors: refuse overlong UTF-8, %u, look-alike dots and slashes and trimmed dot segments; never repeat URL credentials in an error 2026-11-07 18:53:42 +01:00
mnovak 4448527b16 [control] Store and recovery fixes: cross-process token lock, revert keeps its journal until done, epoch and deny list never roll back, journal errors propagate, lost confirm reloads edge, trial hash checked 2026-11-07 18:51:58 +01:00
mnovak b9e14c6aee [control] Tests first: CLI token races, unsaved pause keeps the journal, lost share records never lower the epoch or shrink the deny list (red) 2026-11-07 18:47:00 +01:00
mnovak 98dad246d3 [edge] Share fixes: per-network password limit and no eviction, revocation epoch never goes down, stray share tokens stripped on every host, admin socket bound in a private directory 2026-11-07 18:44:55 +01:00
mnovak fee35830d1 [edge] Tests first: junk ids cannot flush the password throttle, a lower revocation epoch is refused (red) 2026-11-07 18:42:03 +01:00
mnovak c5380c65a6 [control] Recovery: record the outcome before clearing the journal; a failed revert pauses changes until a Restore, and a restart never loads the unverified head 2026-11-07 18:26:03 +01:00
mnovak 7cc92ec42d [docs] API: curl examples end to end on loopback, §8.4 reload answer with load numbers, UI contract deviations 2026-11-07 18:23:42 +01:00
mnovak 2c06efead1 [control] Dev mode: throw-away CA and certificates for three dev hosts; push step skipped without a remote 2026-11-07 18:23:41 +01:00
mnovak 56982fc6b7 [diff] Apply sequence: control applies six steps, Ianitor and Caddy answer the corpus identically after each 2026-11-07 18:18:07 +01:00
mnovak aa0f66b5ac [control] Phase 2 control plane: routes repo via git, journaled apply with trial/watch/revert, undo and restore, push with retry, share links, API tokens, REST API with OpenAPI, --dev 2026-11-07 18:17:06 +01:00
mnovak 56209cc595 [control] Tests first: health-check revert, crash at every apply stage, serialised applies, undo/restore, push, share links, token rejection and leaks, hostile bodies (red) 2026-11-07 18:16:51 +01:00
mnovak 74d1bc02da [edge] Options: credentials directory override, so tests can run several edges in one process 2026-11-07 18:16:14 +01:00
mnovak 6ce1fe9d2b [edge] Reload and share links: in-process config swap with self-reverting trials, admin socket with health and certificate status, share-link cookies, visitor pages and throttle 2026-11-07 17:49:53 +01:00
mnovak c0ed9c65c5 [edge] Tests first: reload under load, refused and trial configs, admin status, share-link visits and prefix escapes (red) 2026-11-07 17:47:43 +01:00
mnovak 7c81945771 [core] Time: RFC 3339 and long dates from Unix seconds 2026-11-07 17:47:42 +01:00
mnovak 94ba18d38b [core] Share links and repo layout: HMAC tokens with epoch, prefix check, exact hosts/<hostname>.toml, error codes; edge config v2 2026-11-07 17:32:44 +01:00
mnovak 73a9f3da45 [core] Tests first: share tokens, prefix escapes, repo layout, exact host path, error codes (red) 2026-11-07 17:32:09 +01:00
mnovak 027bf3a553 [docs] UI API: the designer's contract for Phase 3 2026-11-07 17:22:53 +01:00
mnovak db43af24a6 [core] Phase 1: merge core/phase-1 (PR #2) 2026-11-07 16:46:56 +01:00
150 changed files with 37659 additions and 362 deletions
+5 -2
View File
@@ -65,8 +65,11 @@ expect_staged() {
B='-----BEGIN' B='-----BEGIN'
E='-----END' E='-----END'
mkdir -p "$WORK/../ianitor-hook-src.$$" && SRC="$WORK/../ianitor-hook-src.$$" # An absolute path next to $WORK (not "$WORK/..", which no longer resolves once $WORK is gone),
trap 'rm -rf "$WORK" "$SRC"' EXIT INT TERM # removed first.
SRC="$(dirname "$WORK")/ianitor-hook-src.$$"
mkdir -p "$SRC" || exit 2
trap 'rm -rf "$SRC" "$WORK"' EXIT INT TERM
printf '%s RSA PRIVATE KEY-----\nMIIBOgIBAAJBAK\n%s RSA PRIVATE KEY-----\n' "$B" "$E" > "$SRC/pem" printf '%s RSA PRIVATE KEY-----\nMIIBOgIBAAJBAK\n%s RSA PRIVATE KEY-----\n' "$B" "$E" > "$SRC/pem"
head -c 6291456 /dev/zero | tr '\000' 'a' > "$SRC/six-mb" head -c 6291456 /dev/zero | tr '\000' 'a' > "$SRC/six-mb"
+2 -2
View File
@@ -8,7 +8,7 @@ crates/core config model, schema, compilers (Pingora runtime + Caddy JSON),
crates/edge Pingora data plane. Reads compiled config, serves traffic. Never decides policy. crates/edge Pingora data plane. Reads compiled config, serves traffic. Never decides policy.
crates/control API, git routes repo, apply/rollback, share links, PKI flows. Loopback only. Never serves public traffic. crates/control API, git routes repo, apply/rollback, share links, PKI flows. Loopback only. Never serves public traffic.
apps/web Svelte 5 (runes, TypeScript strict). A client of the API; no logic. apps/web Svelte 5 (runes, TypeScript strict). A client of the API; no logic.
packages/ui shared dark Domi theme. packages/ui shared dark Domi theme, murex palette.
tests/diff same requests against Ianitor and Caddy, responses compared. tests/diff same requests against Ianitor and Caddy, responses compared.
tests/support shared test fixtures (test CA, upstreams, mock Authelia, clients); test-only. tests/support shared test fixtures (test CA, upstreams, mock Authelia, clients); test-only.
tests/fuzz cargo-fuzz targets. tests/fuzz cargo-fuzz targets.
@@ -37,7 +37,7 @@ One-time per clone: git config core.hooksPath .githooks (self-test: bash .gith
- Workflow: branch → Gitea PR via API → short adversarial self-review in the PR body → merge --no-ff → push → verify hashes. - Workflow: branch → Gitea PR via API → short adversarial self-review in the PR body → merge --no-ff → push → verify hashes.
- Server changes: prepare the Nix change and show the command; Mark runs nixos-rebuild himself. deploy/test-access.sh must pass. - Server changes: prepare the Nix change and show the command; Mark runs nixos-rebuild himself. deploy/test-access.sh must pass.
- When reporting done, say which build is deployed and whether it changed visibly. - When reporting done, say which build is deployed and whether it changed visibly.
- UI: dark Domi theme, every action ≤ 3 clicks, plain English; Latin only in the brand name. - UI: dark Domi theme, murex palette; every action ≤ 3 clicks, plain English; Latin only in the brand name.
## Session end ## Session end
Update the Status table and the Handover section at the bottom of docs/ROADMAP.md. No separate handover file. Update the Status table and the Handover section at the bottom of docs/ROADMAP.md. No separate handover file.
Generated
+664 -6
View File
@@ -2,6 +2,41 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 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]] [[package]]
name = "ahash" name = "ahash"
version = "0.8.12" version = "0.8.12"
@@ -219,6 +254,56 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"bytes",
"form_urlencoded",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-util",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"serde_core",
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tower",
"tower-layer",
"tower-service",
]
[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"sync_wrapper",
"tower-layer",
"tower-service",
]
[[package]] [[package]]
name = "base64" name = "base64"
version = "0.22.1" version = "0.22.1"
@@ -231,6 +316,12 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]] [[package]]
name = "bit-vec" name = "bit-vec"
version = "0.9.1" version = "0.9.1"
@@ -252,7 +343,7 @@ version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [ dependencies = [
"digest", "digest 0.10.7",
] ]
[[package]] [[package]]
@@ -264,6 +355,24 @@ dependencies = [
"generic-array", "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]] [[package]]
name = "brotli" name = "brotli"
version = "3.5.0" version = "3.5.0"
@@ -302,6 +411,15 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cbc"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
dependencies = [
"cipher",
]
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.11.1" version = "1.11.1"
@@ -326,6 +444,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" 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]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.45" version = "0.4.45"
@@ -335,6 +464,17 @@ dependencies = [
"num-traits", "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]] [[package]]
name = "clap" name = "clap"
version = "4.6.7" version = "4.6.7"
@@ -384,6 +524,24 @@ dependencies = [
"cc", "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]] [[package]]
name = "colorchoice" name = "colorchoice"
version = "1.0.5" version = "1.0.5"
@@ -409,6 +567,12 @@ dependencies = [
"crossbeam-utils", "crossbeam-utils",
] ]
[[package]]
name = "const-oid"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]] [[package]]
name = "const-random" name = "const-random"
version = "0.1.18" version = "0.1.18"
@@ -455,6 +619,12 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.2.17" version = "0.2.17"
@@ -464,6 +634,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "crc32fast" name = "crc32fast"
version = "1.5.4" version = "1.5.4"
@@ -504,6 +683,33 @@ dependencies = [
"typenum", "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]] [[package]]
name = "daemonix" name = "daemonix"
version = "0.1.0" version = "0.1.0"
@@ -541,6 +747,19 @@ version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" 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]] [[package]]
name = "der-parser" name = "der-parser"
version = "9.0.0" version = "9.0.0"
@@ -569,6 +788,17 @@ dependencies = [
"rusticata-macros", "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]] [[package]]
name = "deranged" name = "deranged"
version = "0.5.9" version = "0.5.9"
@@ -586,17 +816,38 @@ dependencies = [
"syn 1.0.109", "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]] [[package]]
name = "digest" name = "digest"
version = "0.10.7" version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [ dependencies = [
"block-buffer", "block-buffer 0.10.4",
"crypto-common", "crypto-common 0.1.7",
"subtle", "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]] [[package]]
name = "displaydoc" name = "displaydoc"
version = "0.2.7" version = "0.2.7"
@@ -656,6 +907,12 @@ version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
[[package]]
name = "flagset"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
[[package]] [[package]]
name = "flate2" name = "flate2"
version = "1.1.11" version = "1.1.11"
@@ -829,6 +1086,16 @@ dependencies = [
"cfg-if", "cfg-if",
"libc", "libc",
"r-efi 6.0.0", "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]] [[package]]
@@ -897,6 +1164,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" 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]] [[package]]
name = "http" name = "http"
version = "1.5.0" version = "1.5.0"
@@ -942,6 +1218,15 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" 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]] [[package]]
name = "hyper" name = "hyper"
version = "1.12.0" version = "1.12.0"
@@ -1005,25 +1290,58 @@ dependencies = [
[[package]] [[package]]
name = "ianitor-control" name = "ianitor-control"
version = "0.1.0" version = "0.1.0"
dependencies = [
"axum",
"base64 0.22.1",
"bytes",
"http",
"ianitor-core",
"ianitor-edge",
"ianitor-testkit",
"log",
"p12-keystore",
"qrcode",
"ring",
"rpassword",
"rustls",
"rustls-pki-types",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tokio-rustls",
"toml",
"utoipa",
]
[[package]] [[package]]
name = "ianitor-core" name = "ianitor-core"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"base64 0.22.1",
"rcgen",
"ring",
"rustls-pki-types",
"rustls-webpki",
"serde", "serde",
"serde_json", "serde_json",
"thiserror 2.0.21", "thiserror 2.0.21",
"time",
"toml", "toml",
"unicode-normalization",
"url", "url",
"x509-parser 0.18.1",
] ]
[[package]] [[package]]
name = "ianitor-diff" name = "ianitor-diff"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"ianitor-control",
"ianitor-core", "ianitor-core",
"ianitor-edge", "ianitor-edge",
"ianitor-testkit", "ianitor-testkit",
"rcgen",
"rustls", "rustls",
"serde_json", "serde_json",
"tokio", "tokio",
@@ -1036,12 +1354,18 @@ dependencies = [
"arc-swap", "arc-swap",
"async-trait", "async-trait",
"bytes", "bytes",
"form_urlencoded",
"http", "http",
"http-body-util",
"hyper",
"hyper-util",
"ianitor-core", "ianitor-core",
"ianitor-testkit", "ianitor-testkit",
"instant-acme", "instant-acme",
"log", "log",
"pingora", "pingora",
"rcgen",
"ring",
"rustls", "rustls",
"rustls-pki-types", "rustls-pki-types",
"serde", "serde",
@@ -1192,6 +1516,18 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [ dependencies = [
"equivalent", "equivalent",
"hashbrown 0.17.1", "hashbrown 0.17.1",
"serde",
"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]] [[package]]
@@ -1343,6 +1679,12 @@ dependencies = [
"hashbrown 0.17.1", "hashbrown 0.17.1",
] ]
[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]] [[package]]
name = "memchr" name = "memchr"
version = "2.8.3" version = "2.8.3"
@@ -1358,6 +1700,12 @@ dependencies = [
"autocfg", "autocfg",
] ]
[[package]]
name = "mime"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"
[[package]] [[package]]
name = "minimal-lexical" name = "minimal-lexical"
version = "0.2.1" version = "0.2.1"
@@ -1514,6 +1862,29 @@ dependencies = [
"syn 2.0.119", "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]] [[package]]
name = "parking" name = "parking"
version = "2.2.1" version = "2.2.1"
@@ -1543,6 +1914,16 @@ dependencies = [
"windows-link", "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]] [[package]]
name = "pem" name = "pem"
version = "4.0.0" version = "4.0.0"
@@ -1553,6 +1934,15 @@ dependencies = [
"serde_core", "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]] [[package]]
name = "percent-encoding" name = "percent-encoding"
version = "2.3.2" version = "2.3.2"
@@ -1843,12 +2233,64 @@ dependencies = [
"tokio", "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]] [[package]]
name = "pkg-config" name = "pkg-config"
version = "0.3.34" version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" 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]] [[package]]
name = "potential_utf" name = "potential_utf"
version = "0.1.6" version = "0.1.6"
@@ -1895,6 +2337,12 @@ dependencies = [
"yansi", "yansi",
] ]
[[package]]
name = "qrcode"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.47" version = "1.0.47"
@@ -1937,6 +2385,17 @@ dependencies = [
"rand_core 0.9.5", "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]] [[package]]
name = "rand_chacha" name = "rand_chacha"
version = "0.3.1" version = "0.3.1"
@@ -1975,6 +2434,21 @@ dependencies = [
"getrandom 0.3.4", "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]] [[package]]
name = "rcgen" name = "rcgen"
version = "0.14.10" version = "0.14.10"
@@ -2060,6 +2534,27 @@ dependencies = [
"serde", "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]] [[package]]
name = "rust_decimal" name = "rust_decimal"
version = "1.43.0" version = "1.43.0"
@@ -2196,6 +2691,16 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" 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]] [[package]]
name = "same-file" name = "same-file"
version = "1.0.6" version = "1.0.6"
@@ -2220,6 +2725,18 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" 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]] [[package]]
name = "security-framework" name = "security-framework"
version = "2.11.1" version = "2.11.1"
@@ -2311,6 +2828,17 @@ dependencies = [
"zmij", "zmij",
] ]
[[package]]
name = "serde_path_to_error"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
dependencies = [
"itoa",
"serde",
"serde_core",
]
[[package]] [[package]]
name = "serde_spanned" name = "serde_spanned"
version = "1.1.3" version = "1.1.3"
@@ -2320,6 +2848,18 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]] [[package]]
name = "serde_yaml" name = "serde_yaml"
version = "0.9.34+deprecated" version = "0.9.34+deprecated"
@@ -2351,8 +2891,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"cpufeatures", "cpufeatures 0.2.17",
"digest", "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]] [[package]]
@@ -2409,6 +2971,16 @@ dependencies = [
"windows-sys 0.61.2", "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]] [[package]]
name = "stable_deref_trait" name = "stable_deref_trait"
version = "1.2.1" version = "1.2.1"
@@ -2488,6 +3060,12 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
[[package]] [[package]]
name = "synstructure" name = "synstructure"
version = "0.13.2" version = "0.13.2"
@@ -2608,6 +3186,12 @@ dependencies = [
"zerovec", "zerovec",
] ]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.54.1" version = "1.54.1"
@@ -2733,6 +3317,27 @@ version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
"sync_wrapper",
"tokio",
"tower-layer",
"tower-service",
]
[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
[[package]] [[package]]
name = "tower-service" name = "tower-service"
version = "0.3.3" version = "0.3.3"
@@ -2776,7 +3381,7 @@ dependencies = [
"httparse", "httparse",
"log", "log",
"rand 0.9.5", "rand 0.9.5",
"sha1", "sha1 0.10.7",
"thiserror 2.0.21", "thiserror 2.0.21",
] ]
@@ -2798,6 +3403,25 @@ version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
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]] [[package]]
name = "unsafe-libyaml" name = "unsafe-libyaml"
version = "0.2.11" version = "0.2.11"
@@ -2843,6 +3467,29 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"
[[package]]
name = "utoipa"
version = "5.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bde15df68e80b16c7d16b9616e80770ad158988daa56a27dccd1e55558b0160"
dependencies = [
"indexmap 2.14.2",
"serde",
"serde_json",
"utoipa-gen",
]
[[package]]
name = "utoipa-gen"
version = "5.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba0b99ee52df3028635d93840c797102da61f8a7bb3cf751032455895b52ef8"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "version_check" name = "version_check"
version = "0.9.5" version = "0.9.5"
@@ -3016,6 +3663,17 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" 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]] [[package]]
name = "x509-parser" name = "x509-parser"
version = "0.16.0" version = "0.16.0"
+3 -1
View File
@@ -5,7 +5,7 @@ members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.1.0"
edition = "2024" edition = "2024"
rust-version = "1.88" rust-version = "1.89"
license = "MPL-2.0" license = "MPL-2.0"
publish = false publish = false
@@ -18,6 +18,8 @@ serde_json = "1.0.145"
toml = "1.2.1" toml = "1.2.1"
thiserror = "2.0.17" thiserror = "2.0.17"
url = "2.5.7" url = "2.5.7"
ring = "0.17.14"
base64 = "0.22.1"
tokio = { version = "1.48", features = ["full"] } tokio = { version = "1.48", features = ["full"] }
bytes = "1.10" bytes = "1.10"
http = "1.3" http = "1.3"
+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", "name": "web",
"version": "0.0.0", "version": "0.1.0",
"private": true, "private": true,
"license": "MPL-2.0", "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": { "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,
},
});
+39 -1
View File
@@ -1,15 +1,53 @@
[package] [package]
name = "ianitor-control" name = "ianitor-control"
description = "Ianitor Domi control plane (API, routes repo, apply/rollback). Placeholder until phase 2." description = "Ianitor Domi control plane: routes repo, apply with automatic rollback, share links, API tokens, REST API on loopback."
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
license.workspace = true license.workspace = true
publish.workspace = true publish.workspace = true
[lib]
name = "ianitor_control"
path = "src/lib.rs"
[[bin]] [[bin]]
name = "ianitor-control" name = "ianitor-control"
path = "src/main.rs" 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
serde.workspace = true
serde_json.workspace = true
toml.workspace = true
thiserror.workspace = true
log.workspace = true
ring.workspace = true
base64.workspace = true
http.workspace = true
bytes.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
[lints] [lints]
workspace = true workspace = true
File diff suppressed because it is too large Load Diff
+641
View File
@@ -0,0 +1,641 @@
// 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 REST + JSON API on loopback (`/api/v1`), with its OpenAPI document generated from the
//! handlers (utoipa).
//!
//! Every request: the `Host` header must name this server (against DNS rebinding); a browser
//! write without `X-Ianitor-UI: 1` is refused (CSRF); a valid `Authorization: Bearer` API
//! token is required (nothing else identifies the caller: control trusts no `Remote-*`
//! header); 120 requests a minute per token. Bodies are at most 64 KiB, JSON, with no
//! unknown fields. Errors are one typed envelope with a plain-English message. Logs show
//! method, route template, status and time only.
// An error answer is built once per failed request; boxing it buys nothing.
#![allow(clippy::result_large_err)]
pub mod handlers;
pub mod pki;
pub mod ui;
pub mod views;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use axum::Router;
use axum::body::{Body as AxumBody, Bytes};
use axum::extract::{DefaultBodyLimit, FromRequest, MatchedPath, Request, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
use serde::de::DeserializeOwned;
use utoipa::OpenApi;
pub use views::health_state;
use crate::engine::{Control, Fail};
use crate::messages::{self, Params, message};
use crate::tokens::Refusal;
use crate::util::{hex, now, random, rfc3339, sha256_hex};
use views::{ErrorBody, ErrorEnvelope};
pub const MAX_BODY: usize = 64 * 1024;
const RATE_PER_MINUTE: u32 = 120;
/// Who is calling: the API token's id and name.
#[derive(Debug, Clone)]
pub struct Actor {
pub token_id: String,
pub name: String,
}
pub enum Stored {
/// The first request with this key is still being handled.
Pending,
Apply(String),
Json(u16, serde_json::Value),
}
/// Most Idempotency-Keys held at once (each for 24 h).
const MAX_IDEM_KEYS: usize = 2000;
pub struct AppState {
pub ctl: Arc<Control>,
idem: Mutex<HashMap<String, (String, Stored, u64)>>,
rate: Mutex<HashMap<String, (u64, u32)>>,
}
impl AppState {
pub fn new(ctl: Arc<Control>) -> Arc<AppState> {
Arc::new(AppState {
ctl,
idem: Mutex::new(HashMap::new()),
rate: Mutex::new(HashMap::new()),
})
}
/// Count one request against `bucket`; `Err(seconds to wait)` over the limit.
pub fn limit(&self, bucket: &str, per_window: u32, window: u64) -> Result<(), u64> {
let Ok(mut m) = self.rate.lock() else {
return Ok(());
};
let t = now();
let slot = t / window;
if m.len() > 10_000 {
m.retain(|_, (s, _)| *s + 1 >= slot);
}
let e = m.entry(bucket.to_owned()).or_insert((slot, 0));
if e.0 != slot {
*e = (slot, 0);
}
if e.1 >= per_window {
return Err((slot + 1) * window - t);
}
e.1 += 1;
Ok(())
}
/// Start a request with an Idempotency-Key, atomically: `Ok(Some)` replays an earlier
/// answer, `Ok(None)` reserves the key (finish with [`AppState::idem_finish`]), `Err` when
/// the key was used for another request, is still in progress, or no key can be held.
pub fn idem_begin(&self, key: &str, fingerprint: &str) -> Result<Option<Stored>, ApiError> {
let mut m = self
.idem
.lock()
.map_err(|_| ApiError::internal("idempotency store"))?;
let t = now();
match m.get(key) {
Some((fp, _, at)) if t.saturating_sub(*at) < 86_400 && fp != fingerprint => {
return Err(ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"request.idempotency",
Params::new(),
));
}
Some((_, Stored::Pending, at)) if t.saturating_sub(*at) < 86_400 => {
return Err(ApiError::new(
StatusCode::CONFLICT,
"request.in_progress",
Params::new(),
)
.retry(1));
}
Some((_, Stored::Apply(id), at)) if t.saturating_sub(*at) < 86_400 => {
return Ok(Some(Stored::Apply(id.clone())));
}
Some((_, Stored::Json(s, v), at)) if t.saturating_sub(*at) < 86_400 => {
return Ok(Some(Stored::Json(*s, v.clone())));
}
_ => {}
}
if m.len() >= MAX_IDEM_KEYS {
m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400);
}
if m.len() >= MAX_IDEM_KEYS {
return Err(ApiError::new(
StatusCode::TOO_MANY_REQUESTS,
"rate.limited",
Params::new(),
)
.retry(60));
}
m.insert(key.to_owned(), (fingerprint.to_owned(), Stored::Pending, t));
Ok(None)
}
/// Finish a reserved key: remember the answer, or (on `None`, a refusal) free the key.
pub fn idem_finish(&self, key: &str, fingerprint: &str, s: Option<Stored>) {
if let Ok(mut m) = self.idem.lock() {
match s {
Some(s) => {
m.insert(key.to_owned(), (fingerprint.to_owned(), s, now()));
}
None => {
m.remove(key);
}
}
}
}
}
// ---------------------------------------------------------------- errors
#[derive(Debug)]
pub struct ApiError {
pub status: StatusCode,
pub body: ErrorBody,
pub errors: Vec<ErrorBody>,
}
impl ApiError {
pub fn new(status: StatusCode, code: &str, params: Params) -> ApiError {
ApiError {
status,
body: ErrorBody {
code: code.into(),
message: message(code, &params),
field: params.get("field").cloned(),
params,
retry_after_s: None,
detail: None,
},
errors: Vec::new(),
}
}
pub fn internal(detail: impl Into<String>) -> ApiError {
let mut e = ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", Params::new());
e.body.detail = Some(detail.into());
e
}
pub fn retry(mut self, secs: u64) -> ApiError {
self.body.retry_after_s = Some(secs);
self.body.params.insert("seconds".into(), secs.to_string());
self.body.message = message(&self.body.code, &self.body.params);
self
}
}
impl From<Fail> for ApiError {
fn from(f: Fail) -> ApiError {
ApiError {
status: StatusCode::from_u16(f.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
body: ErrorBody::from(&f.reason),
errors: f.errors.iter().map(ErrorBody::from).collect(),
}
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let retry = self.body.retry_after_s;
let env = ErrorEnvelope {
error: self.body,
errors: self.errors,
request_id: String::new(),
};
let mut r = (self.status, axum::Json(env)).into_response();
if let Some(s) = retry
&& let Ok(v) = HeaderValue::from_str(&s.to_string())
{
r.headers_mut().insert(header::RETRY_AFTER, v);
}
r
}
}
// ---------------------------------------------------------------- JSON bodies
/// A JSON request body: at most 64 KiB, no unknown fields, errors that never echo values.
pub struct Body<T> {
pub value: T,
pub raw: Bytes,
}
impl<T: DeserializeOwned, S: Send + Sync> FromRequest<S> for Body<T> {
type Rejection = ApiError;
async fn from_request(req: Request, state: &S) -> Result<Self, ApiError> {
let json_type = req
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("application/json"));
let raw = Bytes::from_request(req, state).await.map_err(|_| {
ApiError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"request.too_large",
Params::new(),
)
})?;
let text: &[u8] = if raw.is_empty() { b"{}" } else { &raw };
if !raw.is_empty() && !json_type {
return Err(ApiError::new(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"request.body",
messages::params([("problem", "send it as application/json.".into())]),
));
}
match serde_json::from_slice::<T>(text) {
Ok(value) => Ok(Body { value, raw }),
Err(e) => Err(body_error(&e)),
}
}
}
fn body_error(e: &serde_json::Error) -> ApiError {
let m = e.to_string();
let quoted = |prefix: &str| -> Option<String> {
let rest = m.split(prefix).nth(1)?;
Some(rest.split('`').next()?.to_owned())
};
if let Some(f) = quoted("unknown field `") {
// The name is the sender's: repeat it only if it is a plain field name.
let plain = !f.is_empty()
&& f.len() <= 64
&& f.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_');
let shown = if plain {
f
} else {
"(a field name)".to_owned()
};
let mut err = ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"request.body_unknown_field",
messages::params([("field", shown.clone())]),
);
err.body.field = plain.then_some(shown);
return err;
}
if let Some(f) = quoted("missing field `") {
return ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"request.body",
messages::params([
("problem", format!("the field \"{f}\" is missing.")),
("field", f),
]),
);
}
// Other serde messages can quote the value sent; say only where the problem is.
let what = match e.classify() {
serde_json::error::Category::Syntax | serde_json::error::Category::Eof => "it is not JSON",
_ => "a value has the wrong type or form",
};
ApiError::new(
StatusCode::BAD_REQUEST,
"request.body",
messages::params([(
"problem",
format!("{what} (line {}, column {}).", e.line(), e.column()),
)]),
)
}
// ---------------------------------------------------------------- middleware
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;
};
let port = ctl.cfg.listen.port();
let ok = [
ctl.cfg.listen.to_string(),
format!("localhost:{port}"),
format!("127.0.0.1:{port}"),
format!("[::1]:{port}"),
];
// 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
.iter()
.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();
let method = req.method().clone();
let route = req
.extensions()
.get::<MatchedPath>()
.map(|p| p.as_str().to_owned())
.unwrap_or_else(|| "(no route)".into());
let resp = async {
if !host_allowed(&st.ctl, req.headers()) {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"request.host",
Params::new(),
));
}
let browser = req.headers().contains_key(header::ORIGIN)
|| req.headers().contains_key("sec-fetch-site");
let write = !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS");
let ui = req
.headers()
.get("x-ianitor-ui")
.is_some_and(|v| v.as_bytes() == b"1");
if browser && write && !ui {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"request.csrf",
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)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
// The token store takes a file lock: off the async threads.
let ctl = st.ctl.clone();
let checked = tokio::task::spawn_blocking(move || ctl.tokens.check(auth.as_deref()))
.await
.unwrap_or(Err(Refusal::Unknown));
let tok = checked.map_err(|r| {
let (code, params) = match r {
Refusal::Missing => ("token.missing", Params::new()),
Refusal::Unknown => ("token.unknown", Params::new()),
Refusal::Expired(t) => (
"token.expired",
messages::params([("date", ianitor_core::time::long_date(t))]),
),
Refusal::Revoked(t) => (
"token.revoked",
messages::params([("date", ianitor_core::time::long_date(t))]),
),
};
ApiError::new(StatusCode::UNAUTHORIZED, code, params)
})?;
st.limit(&format!("token:{}", tok.id), 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: tok.id,
name: tok.name,
});
Ok(next.run(req).await)
}
.await;
let resp = resp.unwrap_or_else(IntoResponse::into_response);
log::info!(target: "ianitor::api", "{method} {route} {} {} ms", resp.status().as_u16(), started.elapsed().as_millis());
resp
}
/// Adds `server_time` to every JSON object answer and `request_id` to error envelopes.
async fn finish(req: Request, next: Next) -> Response {
let request_id = random::<8>().map(|b| hex(&b)).unwrap_or_default();
let resp = next.run(req).await;
let json = resp
.headers()
.get(header::CONTENT_TYPE)
.is_some_and(|v| v.as_bytes().starts_with(b"application/json"));
let (mut parts, body) = resp.into_parts();
if let Ok(v) = HeaderValue::from_str(&request_id) {
parts.headers.insert("x-request-id", v);
}
if !json {
return Response::from_parts(parts, body);
}
let Ok(bytes) = axum::body::to_bytes(body, 16 << 20).await else {
return Response::from_parts(parts, AxumBody::empty());
};
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.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())
}
_ => bytes.to_vec(),
};
parts.headers.remove(header::CONTENT_LENGTH);
Response::from_parts(parts, AxumBody::from(out))
}
async fn not_found() -> ApiError {
ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
}
async fn method_not_allowed() -> ApiError {
ApiError::new(
StatusCode::METHOD_NOT_ALLOWED,
"request.method",
Params::new(),
)
}
pub fn fingerprint(method: &str, path: &str, raw: &[u8]) -> String {
sha256_hex(format!("{method} {path} {}", sha256_hex(raw)).as_bytes())
}
pub fn router(st: Arc<AppState>) -> Router {
use handlers as h;
let api = Router::new()
.route("/api/v1/overview", get(h::overview))
.route("/api/v1/hosts", get(h::list_hosts).post(h::create_host))
.route("/api/v1/hosts/validate", post(h::validate_host))
.route(
"/api/v1/hosts/{hostname}",
get(h::get_host)
.put(h::update_host)
.patch(h::patch_host)
.delete(h::delete_host),
)
.route(
"/api/v1/hosts/{hostname}/share-links",
post(h::mint_share_link),
)
.route(
"/api/v1/hosts/{hostname}/certificate/retry",
post(h::retry_certificate),
)
.route("/api/v1/applies", get(h::list_applies))
.route(
"/api/v1/applies/{id}",
get(h::get_apply).delete(h::cancel_apply),
)
.route("/api/v1/history", get(h::history))
.route("/api/v1/history/{change_id}", get(h::history_entry))
.route(
"/api/v1/history/{change_id}/restore-preview",
get(h::restore_preview),
)
.route("/api/v1/undo", get(h::get_undo).post(h::undo))
.route("/api/v1/restore", post(h::restore))
.route("/api/v1/repo/push", post(h::push_now))
.route("/api/v1/settings", get(h::settings))
.route("/api/v1/tokens", get(h::list_tokens).post(h::create_token))
.route(
"/api/v1/tokens/{id}",
delete(h::revoke_token).patch(h::rename_token),
)
.route("/api/v1/share-links", get(h::list_share_links))
.route(
"/api/v1/share-links/stop-all",
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.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.
pub fn openapi_json() -> String {
handlers::ApiDoc::openapi()
.to_pretty_json()
.unwrap_or_else(|_| "{}".into())
}
+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
}
+841
View File
@@ -0,0 +1,841 @@
// 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/.
//! Response shapes (docs/ui-api.md §1, §2), built from control's state. Times are RFC 3339
//! UTC; every JSON object answer also gets `server_time` from the API layer.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::edgelink::{EdgeStatus, HostStatus};
use crate::engine::Control;
use crate::hostspec::HostSpec;
use crate::messages::{self, message};
use crate::records::{ApplyRecord, FieldError, Reason, Step, WatchHost};
use crate::util::{now, rfc3339};
fn t(x: Option<u64>) -> Option<String> {
x.map(rfc3339)
}
fn short(id: &Option<String>) -> Option<String> {
id.as_ref().map(|c| c.chars().take(7).collect())
}
/// One error, as the UI shows it (docs/ui-api.md §0).
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ErrorBody {
/// Stable code, e.g. `host.upstream.no_port`.
pub code: String,
/// Plain English, shown as is.
pub message: String,
/// The form field, e.g. `upstreams[0]`.
pub field: Option<String>,
pub params: BTreeMap<String, String>,
pub retry_after_s: Option<u64>,
/// Technical detail, behind "Show details". Never a secret.
pub detail: Option<String>,
}
impl From<&FieldError> for ErrorBody {
fn from(e: &FieldError) -> Self {
ErrorBody {
code: e.code.clone(),
message: e.message.clone(),
field: e.field.clone(),
params: e.params.clone(),
retry_after_s: None,
detail: e.detail.clone(),
}
}
}
impl From<&Reason> for ErrorBody {
fn from(r: &Reason) -> Self {
ErrorBody {
code: r.code.clone(),
message: r.message.clone(),
field: r.field.clone(),
params: r.params.clone(),
retry_after_s: None,
detail: r.detail.clone(),
}
}
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ErrorEnvelope {
pub error: ErrorBody,
pub errors: Vec<ErrorBody>,
pub request_id: String,
}
// ---------------------------------------------------------------- applies
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct WaitingFor {
pub apply_id: String,
pub summary: String,
pub seconds_left: Option<u64>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct QueueView {
pub position: usize,
pub waiting_for: Option<WaitingFor>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct WatchView {
pub ends_at: String,
pub seconds_left: u64,
pub hosts: Vec<WatchHost>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct PushView {
/// `pushed`, `pending` or `failed`.
pub state: String,
pub at: Option<String>,
pub error_code: Option<String>,
pub next_try_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ApplyView {
pub id: String,
pub change_id: String,
/// `add`, `edit`, `remove`, `undo`, `restore` or `share_links`.
pub kind: String,
pub summary: String,
pub hosts: Vec<String>,
/// `queued`, `validating`, `applying`, `watching`, `kept`, `reverted`, `failed` or
/// `needs_attention`.
pub state: String,
pub created_at: String,
pub started_at: Option<String>,
pub finished_at: Option<String>,
pub steps: Vec<Step>,
pub queue: Option<QueueView>,
pub watch: Option<WatchView>,
pub reason: Option<Reason>,
pub errors: Vec<ErrorBody>,
pub commit_short: Option<String>,
pub commit: Option<String>,
pub push: Option<PushView>,
pub undo_of: Option<String>,
pub restore_of: Option<String>,
pub effect: Option<String>,
pub attempted_host: Option<HostSpec>,
pub actor: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ApplyAccepted {
pub apply: ApplyView,
}
pub fn apply_view(c: &Control, r: &ApplyRecord) -> ApplyView {
let n = now();
let queue = (r.state == "queued").then(|| {
let position = c.queue_position(&r.id).unwrap_or(1);
let running = c.records().into_iter().rev().find(|x| x.is_running());
QueueView {
position,
waiting_for: running.map(|x| WaitingFor {
apply_id: x.id.clone(),
summary: x.summary.clone(),
seconds_left: x.watch.as_ref().map(|w| w.ends.saturating_sub(n)),
}),
}
});
let push = (r.state == "kept" && r.commit.is_some()).then(|| {
let p = c.push_state();
let step = r
.steps
.iter()
.find(|s| s.key == "push")
.map(|s| s.state.as_str())
.unwrap_or("pending");
PushView {
state: match step {
"done" => "pushed",
"failed" => "failed",
_ if c.cfg.routes.remote.is_none() => "pending",
_ if p.error_code.is_some() => "failed",
_ => "pending",
}
.into(),
at: t(p.last_push_at),
error_code: p.error_code.clone(),
next_try_at: t(p.next_try_at),
}
});
ApplyView {
id: r.id.clone(),
change_id: r.id.clone(),
kind: r.kind.clone(),
summary: r.summary.clone(),
hosts: r.hosts.clone(),
state: r.state.clone(),
created_at: rfc3339(r.created),
started_at: t(r.started),
finished_at: t(r.finished),
steps: r.steps.clone(),
queue,
watch: r.watch.as_ref().map(|w| WatchView {
ends_at: rfc3339(w.ends),
seconds_left: if r.state == "watching" {
w.ends.saturating_sub(n)
} else {
0
},
hosts: w.hosts.clone(),
}),
reason: r.reason.clone(),
errors: r.errors.iter().map(ErrorBody::from).collect(),
commit_short: short(&r.commit),
commit: r.commit.clone(),
push,
undo_of: r.undo_of.clone(),
restore_of: r.restore_of.clone(),
effect: r.effect.clone(),
attempted_host: r.attempted_host.clone(),
actor: r.actor.clone(),
}
}
// ---------------------------------------------------------------- health
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Failure {
pub kind: String,
pub upstream: String,
pub count: u32,
pub of: u32,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct UpstreamHealth {
pub url: String,
/// `healthy`, `down` or `pending`.
pub state: String,
pub last_check_at: Option<String>,
pub latency_ms: Option<u64>,
pub failure_kind: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HealthView {
/// `healthy`, `degraded`, `down`, `unknown` or `pending`.
pub state: String,
pub last_check_at: Option<String>,
pub latency_ms: Option<u64>,
pub since: Option<String>,
pub failure: Option<Failure>,
pub upstreams: Vec<UpstreamHealth>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct CertView {
/// `ok`, `pending` or `failed`.
pub state: String,
pub not_after: Option<String>,
pub error_code: Option<String>,
}
/// The health word for a host (docs/ui-api.md §1.1): `unknown` without a health check,
/// `pending` before the first check, `healthy` when every upstream passed its last check and
/// its recent ones, `degraded` when some fail or results are mixed, `down` when none passed.
pub fn health_state(h: &HostStatus) -> &'static str {
if !h.health_check {
return "unknown";
}
let checks: Vec<Vec<&crate::edgelink::Check>> = h
.upstreams
.iter()
.map(|u| {
u.checks
.iter()
.filter(|c| c.source == "health_check")
.collect()
})
.collect();
if checks.iter().all(|c| c.is_empty()) {
return "pending";
}
let last_ok: Vec<bool> = checks
.iter()
.map(|c| c.last().is_some_and(|x| x.ok))
.collect();
if !last_ok.iter().any(|x| *x) {
return "down";
}
let mixed = checks
.iter()
.any(|c| c.iter().any(|x| x.ok) && c.iter().any(|x| !x.ok));
if last_ok.iter().all(|x| *x) && !mixed {
"healthy"
} else {
"degraded"
}
}
fn scheme_url(spec: Option<&HostSpec>, address: &str) -> String {
let scheme = spec
.and_then(|s| s.upstreams.first())
.and_then(|u| u.split_once("://").map(|(s, _)| s.to_owned()))
.unwrap_or_else(|| "http".into());
format!("{scheme}://{address}")
}
pub fn health_view(
status: Option<&HostStatus>,
spec: Option<&HostSpec>,
since: Option<(&'static str, u64)>,
) -> HealthView {
let Some(h) = status else {
return HealthView {
state: if spec.is_some_and(|s| s.health_check.is_none()) {
"unknown"
} else {
"pending"
}
.into(),
last_check_at: None,
latency_ms: None,
since: None,
failure: None,
upstreams: Vec::new(),
};
};
let state = health_state(h);
let mut last_at = None;
let mut latency = None;
let mut failure: Option<Failure> = None;
let ups = h
.upstreams
.iter()
.map(|u| {
let checks: Vec<_> = u
.checks
.iter()
.filter(|c| c.source == "health_check")
.collect();
let last = checks.last();
if let Some(l) = last {
last_at = last_at.max(Some(l.at));
if l.ok {
latency = match (latency, l.latency_ms) {
(Some(a), Some(b)) => Some(u64::min(a, b)),
(a, b) => a.or(b),
};
} else if failure.is_none() {
failure = Some(Failure {
kind: l.kind.clone().unwrap_or_else(|| "bad_answer".into()),
upstream: scheme_url(spec, &u.address),
count: checks.iter().filter(|c| !c.ok).count() as u32,
of: checks.len() as u32,
});
}
}
UpstreamHealth {
url: scheme_url(spec, &u.address),
state: match last {
None => "pending",
Some(l) if l.ok => "healthy",
Some(_) => "down",
}
.into(),
last_check_at: last.map(|l| rfc3339(l.at)),
latency_ms: last.and_then(|l| l.latency_ms),
failure_kind: last.and_then(|l| l.kind.clone()),
}
})
.collect();
HealthView {
state: state.into(),
last_check_at: t(last_at),
latency_ms: latency,
since: since
.filter(|(s, _)| *s == state)
.map(|(_, at)| rfc3339(at)),
failure: if matches!(state, "down" | "degraded") {
failure
} else {
None
},
upstreams: if h.health_check { ups } else { Vec::new() },
}
}
pub fn cert_view(status: Option<&HostStatus>, spec: Option<&HostSpec>) -> CertView {
match status {
Some(h) => CertView {
state: h.certificate.state.clone(),
not_after: h
.certificate
.not_after
.and_then(|x| u64::try_from(x).ok())
.map(rfc3339),
error_code: (h.certificate.state == "failed").then(|| "cert.failed".into()),
},
None => CertView {
state: if spec.is_some_and(|s| s.tls == "domi") {
"ok"
} else {
"pending"
}
.into(),
not_after: None,
error_code: None,
},
}
}
// ---------------------------------------------------------------- hosts and overview
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HostRow {
pub hostname: String,
pub upstreams: Vec<String>,
pub tls: String,
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,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HostDetail {
pub host: HostSpec,
/// The routes commit this was read from; send it back as `base_rev`.
pub rev: String,
/// The host file as committed.
pub toml: String,
pub health: HealthView,
pub certificate: CertView,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HostList {
pub rev: String,
pub hosts: Vec<HostRow>,
}
#[derive(Debug, Clone, Default, Serialize, ToSchema)]
pub struct Counts {
pub hosts: usize,
pub healthy: usize,
pub degraded: usize,
pub down: usize,
pub unknown: usize,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct EngineView {
/// `pingora` or `caddy`.
pub running: String,
/// `running`, `switching` or `stopped` (control cannot reach it).
pub state: String,
pub since: Option<String>,
/// 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)]
pub struct UndoTarget {
pub change_id: String,
pub summary: String,
pub kept_at: Option<String>,
pub commit_short: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Blocked {
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct UndoView {
pub available: bool,
pub target: Option<UndoTarget>,
/// What Undo does, e.g. "Removes recipes.home.example".
pub effect: Option<String>,
pub blocked: Option<Blocked>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ActiveApply {
pub id: String,
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,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RepoView {
pub name: String,
pub last_push_at: Option<String>,
pub unpushed: u64,
pub push_error_code: Option<String>,
pub remote_configured: bool,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct SiteView {
pub forward_auth_configured: bool,
pub acme_configured: bool,
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)]
pub struct Overview {
pub counts: Counts,
pub hosts: Vec<HostRow>,
pub engine: EngineView,
pub last_apply: Option<ApplyView>,
pub undo: UndoView,
pub active_apply: Option<ActiveApply>,
pub repo: Option<RepoView>,
/// 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> {
c.records()
.iter()
.find(|r| r.kind == "add" && r.state == "kept" && r.hosts.iter().any(|h| h == hostname))
.and_then(|r| r.finished)
.map(rfc3339)
}
pub fn undo_view(c: &Control) -> UndoView {
let blocked = if let Some(p) = c.effective_pause() {
Some(Blocked {
code: "undo.paused".into(),
message: message("undo.paused", &messages::Params::new()) + " " + &p.message,
})
} else {
c.records()
.iter()
.rev()
.find(|r| r.is_running() && r.kind == "undo")
.map(|r| {
let left = r
.watch
.as_ref()
.map(|w| w.ends.saturating_sub(now()))
.unwrap_or(0);
Blocked {
code: "undo.watching".into(),
message: message(
"undo.watching",
&messages::params([("seconds", left.to_string())]),
),
}
})
};
match c.undo_target() {
None => UndoView {
available: false,
target: None,
effect: None,
blocked: Some(blocked.unwrap_or(Blocked {
code: "undo.nothing".into(),
message: message("undo.nothing", &messages::Params::new()),
})),
},
Some(t) => {
let effect = undo_effect(c, &t);
UndoView {
available: blocked.is_none(),
target: Some(UndoTarget {
change_id: t.id.clone(),
summary: t.summary.clone(),
kept_at: t.finished.map(rfc3339),
commit_short: short(&t.commit),
}),
effect,
blocked,
}
}
}
}
/// What undoing `t` would do: from its tree back to the tree before it.
pub fn undo_effect(c: &Control, t: &ApplyRecord) -> Option<String> {
let (commit, base) = (t.commit.as_ref()?, t.base.as_ref()?);
let from = c.repo.tree(commit).ok()?;
let to = c.repo.tree(base).ok()?;
let mut parts = Vec::new();
let mut names: std::collections::BTreeSet<String> = from.hostnames().into_iter().collect();
names.extend(to.hostnames());
for h in names {
match (from.host(&h), to.host(&h)) {
(Some(a), Some(b)) if a != b => parts.push(format!("Changes {h} back")),
(Some(_), None) => parts.push(format!("Removes {h}")),
(None, Some(_)) => parts.push(format!("Adds {h} back")),
_ => {}
}
}
Some(if parts.is_empty() {
"Changes the site settings back".into()
} else {
parts.join("; ")
})
}
pub fn host_rows(
c: &Control,
tree: &crate::repo::RouteTree,
status: Option<&EdgeStatus>,
since: &std::collections::HashMap<String, (&'static str, u64)>,
) -> Vec<HostRow> {
tree.hostnames()
.into_iter()
.map(|h| {
let spec = tree.host(&h).and_then(|t| HostSpec::from_toml(t).ok());
let st = status.and_then(|s| s.hosts.iter().find(|x| x.hostname == h));
HostRow {
upstreams: spec
.as_ref()
.map(|s| s.upstreams.clone())
.unwrap_or_default(),
tls: spec.as_ref().map(|s| s.tls.clone()).unwrap_or_default(),
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()),
hostname: h,
}
})
.collect()
}
// ---------------------------------------------------------------- history
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HistoryEntry {
pub change_id: String,
pub summary: String,
pub kind: String,
pub state: String,
pub at: String,
pub commit_short: Option<String>,
pub hosts: Vec<String>,
pub reason_short: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct History {
pub entries: Vec<HistoryEntry>,
/// Pass as `before` for older entries.
pub next_before: Option<String>,
}
pub fn history_row(r: &ApplyRecord) -> HistoryEntry {
HistoryEntry {
change_id: r.id.clone(),
summary: r.summary.clone(),
kind: r.kind.clone(),
state: r.state.clone(),
at: rfc3339(r.finished.unwrap_or(r.created)),
commit_short: short(&r.commit),
hosts: r.hosts.clone(),
reason_short: r.reason.as_ref().filter(|_| r.state != "kept").map(|x| {
x.params
.get("kind")
.cloned()
.unwrap_or_else(|| x.code.rsplit('.').next().unwrap_or("").replace('_', " "))
}),
}
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct FieldChange {
pub field: String,
pub from: String,
pub to: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HostChange {
pub hostname: String,
/// `added`, `removed` or `changed`.
pub effect: String,
pub fields: Vec<FieldChange>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RestorePreview {
pub restorable: bool,
pub same_as_current: bool,
pub changes: Vec<HostChange>,
pub blocked: Option<Blocked>,
}
// ---------------------------------------------------------------- tokens, shares, settings
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct TokenView {
pub id: String,
pub name: String,
pub created_at: String,
pub last_used_at: Option<String>,
pub expires_at: Option<String>,
pub revoked_at: Option<String>,
}
impl From<&crate::tokens::TokenRecord> for TokenView {
fn from(r: &crate::tokens::TokenRecord) -> Self {
TokenView {
id: r.id.clone(),
name: r.name.clone(),
created_at: rfc3339(r.created_at),
last_used_at: t(r.last_used_at),
expires_at: t(r.expires_at),
revoked_at: t(r.revoked_at),
}
}
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct TokenList {
pub items: Vec<TokenView>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct CreatedToken {
pub id: String,
pub name: String,
/// Shown once; Ianitor keeps only its hash.
pub token: String,
pub expires_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ShareLinkView {
pub id: String,
pub hostname: String,
pub path_prefix: String,
pub created_at: String,
pub expires_at: String,
pub has_password: bool,
/// `active`, `expired` or `stopped`.
pub state: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ShareLinkList {
pub items: Vec<ShareLinkView>,
pub epoch: u32,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct MintedLink {
pub id: String,
/// Contains the token; shown once.
pub url: String,
pub expires_at: String,
pub path_prefix: String,
pub has_password: bool,
/// `host.share.no_signin` when the host needs no sign-in anyway.
pub warning: Option<Blocked>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct StoppedAll {
pub epoch: u32,
pub message: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Settings {
pub repo: RepoView,
pub watch_seconds: u64,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct EdgeHealth {
pub attached: bool,
pub reachable: bool,
pub config_sha256: Option<String>,
pub trial_running: bool,
pub error: Option<String>,
pub read_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct HealthReport {
pub edge: EdgeHealth,
pub paused: Option<Blocked>,
pub queued: usize,
pub hosts: Vec<HostRow>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Done {
pub message: String,
}
+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),
}
}
}
}
+385
View File
@@ -0,0 +1,385 @@
// 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.toml`: where control keeps its state, the routes repository, the files it writes
//! for edge and Caddy, and the deployment facts both compilers need. Written by the NixOS
//! module; never holds a secret (secrets are credential *names* in `$CREDENTIALS_DIRECTORY`).
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use ianitor_core::compile::CompileOptions;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
/// The API listens here. Only loopback addresses are accepted.
#[serde(default = "default_listen")]
pub listen: SocketAddr,
/// Extra `Host` header values the API accepts (besides the listen address, `localhost`
/// and `127.0.0.1` on its port), e.g. the admin host edge forwards to control in phase 3.
#[serde(default)]
pub allowed_hosts: Vec<String>,
/// Tokens, share links, apply records, the apply journal.
pub state_dir: PathBuf,
/// Overrides `$CREDENTIALS_DIRECTORY` (dev mode and tests only).
pub credentials_dir: Option<PathBuf>,
/// The `git` binary.
#[serde(default = "default_git")]
pub git: PathBuf,
/// How long the health watch after an apply lasts.
#[serde(default = "default_watch")]
pub watch_secs: u64,
/// How often watched hosts are probed during the watch.
#[serde(default = "default_every")]
pub watch_every_secs: u64,
/// Extra time edge waits for a confirmation after the watch before it reverts by itself.
#[serde(default = "default_margin")]
pub trial_margin_secs: u64,
/// How often control reads health from edge for the overview.
#[serde(default = "default_poll")]
pub health_poll_secs: u64,
pub routes: Routes,
pub edge: Edge,
pub caddy: Caddy,
/// Deployment facts for both compilers.
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)]
#[serde(deny_unknown_fields)]
pub struct Routes {
/// The routes repository (bare). Created with an empty `ianitor.toml` when missing.
pub repo: PathBuf,
#[serde(default = "default_branch")]
pub branch: String,
/// Where kept changes are pushed (a URL or a path); none means no push.
pub remote: Option<String>,
/// Shown in the UI ("Last pushed to <name>").
#[serde(default = "default_remote_name")]
pub remote_name: String,
/// User name for HTTPS pushes.
#[serde(default = "default_push_user")]
pub push_username: String,
/// Credential (file name in `$CREDENTIALS_DIRECTORY`) holding the push password or token.
pub push_credential: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Edge {
/// The edge config file; only ever holds a config that passed its watch.
pub config: PathBuf,
/// The trial file edge loads during an apply (default `<config>.trial`).
pub trial: Option<PathBuf>,
/// Edge's admin socket; without it control applies without reload or health watch
/// (dev mode without an edge).
pub admin_socket: Option<PathBuf>,
/// The share-link revocation file edge reads.
pub share_revocations: PathBuf,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Caddy {
/// The Caddy JSON the caddy-fallback unit reads.
pub config: PathBuf,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Compile {
pub http_listen: SocketAddr,
pub https_listen: SocketAddr,
pub cert_dir: String,
pub state_dir: String,
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 {
pub fn options(&self) -> CompileOptions {
CompileOptions {
http_listen: self.http_listen,
https_listen: self.https_listen,
cert_dir: self.cert_dir.clone(),
state_dir: self.state_dir.clone(),
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(),
}
}
}
fn default_listen() -> SocketAddr {
SocketAddr::from(([127, 0, 0, 1], 7878))
}
fn default_git() -> PathBuf {
PathBuf::from("git")
}
fn default_watch() -> u64 {
60
}
fn default_every() -> u64 {
5
}
fn default_margin() -> u64 {
30
}
fn default_poll() -> u64 {
2
}
fn default_branch() -> String {
"main".into()
}
fn default_remote_name() -> String {
"Gitea".into()
}
fn default_push_user() -> String {
"ianitor".into()
}
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("cannot read {path}: {source}")]
Read {
path: PathBuf,
source: std::io::Error,
},
#[error("{path} is not a valid control config: {message}")]
Parse { path: PathBuf, message: String },
#[error("control config: {0}")]
Invalid(String),
}
impl Config {
pub fn load(path: &Path) -> Result<Config, ConfigError> {
let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
path: path.to_owned(),
source,
})?;
let c: Config = toml::from_str(&text).map_err(|e| ConfigError::Parse {
path: path.to_owned(),
message: e.message().to_owned(),
})?;
c.check()?;
Ok(c)
}
pub fn check(&self) -> Result<(), ConfigError> {
if !self.listen.ip().is_loopback() {
return Err(ConfigError::Invalid(format!(
"listen = {} is not a loopback address; ianitor-control only listens on 127.0.0.1 or ::1",
self.listen
)));
}
if !(1..=3600).contains(&self.watch_secs) {
return Err(ConfigError::Invalid("watch_secs must be 1 to 3600".into()));
}
if !(1..=60).contains(&self.watch_every_secs)
|| !(1..=600).contains(&self.trial_margin_secs)
{
return Err(ConfigError::Invalid(
"watch_every_secs must be 1 to 60 and trial_margin_secs 1 to 600".into(),
));
}
if self.routes.branch.is_empty()
|| !self
.routes
.branch
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c))
|| self.routes.branch.starts_with(['-', '.', '/'])
|| self.routes.branch.contains("..")
{
return Err(ConfigError::Invalid(
"routes.branch is not a plain branch name".into(),
));
}
if let Some(r) = &self.routes.remote
&& (r.starts_with('-') || r.is_empty())
{
return Err(ConfigError::Invalid("routes.remote is not usable".into()));
}
if let Some(c) = &self.routes.push_credential
&& !valid_credential_name(c)
{
return Err(ConfigError::Invalid(
"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())
.map_err(|e| ConfigError::Invalid(e.to_string()))?;
}
}
Ok(())
}
pub fn trial_path(&self) -> PathBuf {
self.edge
.trial
.clone()
.unwrap_or_else(|| suffixed(&self.edge.config, ".trial"))
}
pub fn caddy_trial_path(&self) -> PathBuf {
suffixed(&self.caddy.config, ".trial")
}
pub fn caddy_compile(&self) -> &Compile {
self.compile_caddy.as_ref().unwrap_or(&self.compile)
}
pub fn credentials_dir(&self) -> Option<PathBuf> {
self.credentials_dir
.clone()
.or_else(|| std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from))
}
/// Read a credential by name (trailing newline dropped). Never logged.
pub fn credential(&self, name: &str) -> Option<Vec<u8>> {
if !valid_credential_name(name) {
return None;
}
let raw = std::fs::read(self.credentials_dir()?.join(name)).ok()?;
let t = raw
.strip_suffix(b"\r\n")
.or_else(|| raw.strip_suffix(b"\n"))
.unwrap_or(&raw);
(!t.is_empty()).then(|| t.to_vec())
}
}
pub fn valid_credential_name(n: &str) -> bool {
!n.is_empty()
&& n.len() <= 64
&& n.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_' || c == b'-')
}
fn suffixed(p: &Path, suffix: &str) -> PathBuf {
let mut name = p.file_name().unwrap_or_default().to_os_string();
name.push(suffix);
p.with_file_name(name)
}
fn empty_model() -> Option<ianitor_core::Model> {
ianitor_core::load(
&ianitor_core::SourceFile {
name: "ianitor.toml",
contents: "",
},
&[],
)
.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()
}
+65
View File
@@ -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/.
//! Crash points for the crash-safety tests: with `IANITOR_TEST_CRASH_AT=<stage>` in its
//! 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] = [
"prepared",
"committed",
"trial_written",
"trial_loaded",
"watching",
"watched",
"confirmed",
"promoted",
"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}: 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"),
path.file_name(),
) {
(Some(want), Some(name)) if want == name => Err(format!(
"cannot write {}: IANITOR_TEST_FAIL_WRITE (injected)",
path.display()
)),
_ => Ok(()),
}
}
#[cfg(not(feature = "test-hooks"))]
#[inline(always)]
pub fn fail_write(_path: &std::path::Path) -> Result<(), String> {
Ok(())
}
+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/.
//! `ianitor-control --dev`: everything temporary, on 127.0.0.1. A fresh routes repository, a
//! state directory, a share-link key and one API token printed once. If an `ianitor-edge`
//! binary is found (`--edge-bin`, `$IANITOR_EDGE_BIN`, or next to this binary), it runs as
//! the dev proxy on 127.0.0.1:18080/18443 with an admin socket, so applies are loaded and
//! watched for real; otherwise applies are only written. Everything is removed on Ctrl-C.
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes};
use ianitor_control::repo::Repo;
use ianitor_control::tokens::Tokens;
use ianitor_control::util::{hex, random, write_atomic};
/// 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\
[forward_auth]\nurl = \"http://127.0.0.1:9091/api/authz/forward-auth\"\n";
struct Cleanup {
dir: PathBuf,
edge: Option<Child>,
}
impl Drop for Cleanup {
fn drop(&mut self) {
if let Some(c) = &mut self.edge {
let _ = c.kill();
let _ = c.wait();
}
let _ = std::fs::remove_dir_all(&self.dir);
}
}
fn find_edge(args: &[String]) -> Option<PathBuf> {
let mut it = args.iter();
while let Some(a) = it.next() {
if a == "--edge-bin" {
return it.next().map(PathBuf::from);
}
}
if let Some(p) = std::env::var_os("IANITOR_EDGE_BIN") {
return Some(PathBuf::from(p));
}
let me = std::env::current_exe().ok()?;
let sibling = me.with_file_name(if cfg!(windows) {
"ianitor-edge.exe"
} else {
"ianitor-edge"
});
sibling.is_file().then_some(sibling)
}
fn arg(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
}
pub async fn run(args: &[String]) -> Result<(), String> {
let listen: SocketAddr = arg(args, "--listen")
.unwrap_or_else(|| "127.0.0.1:7878".into())
.parse()
.map_err(|_| "--listen must be an address like 127.0.0.1:7878")?;
if !listen.ip().is_loopback() {
return Err("--dev listens on loopback only".into());
}
let dir = std::env::temp_dir().join(format!("ianitor-dev-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut cleanup = Cleanup {
dir: dir.clone(),
edge: None,
};
for d in [
"state",
"edge",
"caddy",
"certs",
"creds",
"logs",
"edge-state",
"offline-root",
] {
std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?;
}
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())?;
let edge_bin = if cfg!(unix) { find_edge(args) } else { None };
let s = |p: &str| dir.join(p).to_string_lossy().into_owned();
let cfg = Config {
listen,
allowed_hosts: Vec::new(),
state_dir: dir.join("state"),
credentials_dir: Some(dir.join("creds")),
git: PathBuf::from("git"),
watch_secs: arg(args, "--watch-secs")
.and_then(|v| v.parse().ok())
.unwrap_or(10),
watch_every_secs: 2,
trial_margin_secs: 20,
health_poll_secs: 2,
routes: Routes {
repo: dir.join("routes.git"),
branch: "main".into(),
remote: None,
remote_name: "Gitea".into(),
push_username: "ianitor".into(),
push_credential: None,
},
edge: Edge {
config: dir.join("edge/edge.json"),
trial: None,
admin_socket: edge_bin.as_ref().map(|_| dir.join("edge/admin.sock")),
share_revocations: dir.join("edge/share-revocations.json"),
},
caddy: Caddy {
config: dir.join("caddy/caddy.json"),
},
compile: Compile {
http_listen: "127.0.0.1:18080".parse().map_err(|_| "bad address")?,
https_listen: "127.0.0.1:18443".parse().map_err(|_| "bad address")?,
cert_dir: s("certs"),
state_dir: s("edge-state"),
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)
.map_err(|e| e.to_string())?;
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None)?;
// 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)?);
}
println!("Ianitor control (dev) on http://{listen}/api/v1");
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 any name; Domi root: {}",
b.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);
r
}
fn start_edge(bin: &Path, dir: &Path, cfg: &Config) -> Result<Child, String> {
let log = std::fs::File::create(dir.join("logs/edge.log")).map_err(|e| e.to_string())?;
let log2 = log.try_clone().map_err(|e| e.to_string())?;
let child = Command::new(bin)
.arg("--config")
.arg(&cfg.edge.config)
.arg("--admin-socket")
.arg(dir.join("edge/admin.sock"))
.arg("--share-revocations")
.arg(&cfg.edge.share_revocations)
.env("CREDENTIALS_DIRECTORY", dir.join("creds"))
.stdout(Stdio::from(log))
.stderr(Stdio::from(log2))
.spawn()
.map_err(|e| format!("cannot start {}: {e}", bin.display()))?;
let sock = dir.join("edge/admin.sock");
for _ in 0..100 {
if sock.exists() {
return Ok(child);
}
std::thread::sleep(Duration::from_millis(50));
}
Err(format!(
"the dev proxy did not start; see {}",
dir.join("logs/edge.log").display()
))
}
+227
View File
@@ -0,0 +1,227 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Control's side of edge's admin socket (see `ianitor_edge::admin`).
use std::path::PathBuf;
use std::time::Duration;
use serde::Deserialize;
use serde_json::{Value, json};
#[derive(Debug, thiserror::Error)]
pub enum EdgeLinkError {
/// Edge did not answer (not running, socket missing, timeout).
#[error("edge cannot be reached: {0}")]
Unreachable(String),
/// Edge answered with an error.
#[error("{message}")]
Refused { status: u16, message: String },
}
/// One probe result as edge reports it.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct Check {
pub seq: u64,
pub at: u64,
pub ok: bool,
pub source: String,
pub kind: Option<String>,
pub status: Option<u16>,
pub latency_ms: Option<u64>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct UpstreamStatus {
pub address: String,
pub healthy: bool,
pub checks: Vec<Check>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CertStatus {
pub state: String,
pub not_after: Option<i64>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct HostStatus {
pub hostname: String,
pub health_check: bool,
pub upstreams: Vec<UpstreamStatus>,
pub certificate: CertStatus,
}
#[derive(Debug, Clone, Deserialize)]
pub struct TrialStatus {
pub config_sha256: String,
pub seconds_left: u64,
}
#[derive(Debug, Clone, Deserialize)]
pub struct EdgeStatus {
pub generation: u64,
pub config_sha256: String,
pub started_at: u64,
pub trial: Option<TrialStatus>,
pub hosts: Vec<HostStatus>,
}
/// How control reaches edge. `None` in dev mode without an edge: applies are written but
/// not loaded or watched.
#[derive(Debug, Clone)]
pub enum EdgeLink {
Unix(PathBuf),
None,
}
const TIMEOUT: Duration = Duration::from_secs(10);
impl EdgeLink {
pub fn attached(&self) -> bool {
matches!(self, EdgeLink::Unix(_))
}
async fn call(
&self,
method: &str,
path: &str,
body: Option<Value>,
) -> Result<Value, EdgeLinkError> {
let EdgeLink::Unix(socket) = self else {
return Err(EdgeLinkError::Unreachable("no edge is attached".into()));
};
#[cfg(unix)]
{
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let body = body.map(|b| b.to_string()).unwrap_or_default();
let req = format!(
"{method} {path} HTTP/1.1\r\nHost: edge\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
body.len()
);
let exchange = async {
let mut s = tokio::net::UnixStream::connect(socket).await?;
s.write_all(req.as_bytes()).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(|_| EdgeLinkError::Unreachable("no answer within 10 s".into()))?
.map_err(|e| EdgeLinkError::Unreachable(e.to_string()))?;
let (status, json) = parse(&buf).map_err(EdgeLinkError::Unreachable)?;
if (200..300).contains(&status) {
Ok(json)
} else {
Err(EdgeLinkError::Refused {
status,
message: json["error"].as_str().unwrap_or("edge refused").to_owned(),
})
}
}
#[cfg(not(unix))]
{
let _ = (socket, method, path, body);
Err(EdgeLinkError::Unreachable(
"the admin socket needs Unix".into(),
))
}
}
pub async fn status(&self) -> Result<EdgeStatus, EdgeLinkError> {
let v = self.call("GET", "/v1/status", None).await?;
serde_json::from_value(v)
.map_err(|e| EdgeLinkError::Unreachable(format!("odd status: {e}")))
}
/// Load the trial file; returns its SHA-256 as edge computed it.
pub async fn trial(
&self,
confirm_within: u64,
watch_hosts: &[String],
every: u64,
) -> Result<String, EdgeLinkError> {
let v = self
.call(
"POST",
"/v1/trial",
Some(json!({
"confirm_within_secs": confirm_within,
"watch_hosts": watch_hosts,
"watch_every_secs": every,
})),
)
.await?;
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
}
pub async fn confirm(&self, sha: &str) -> Result<(), EdgeLinkError> {
self.call("POST", "/v1/confirm", Some(json!({ "config_sha256": sha })))
.await
.map(|_| ())
}
pub async fn abort(&self) -> Result<bool, EdgeLinkError> {
let v = self.call("POST", "/v1/abort", None).await?;
Ok(v["reverted"].as_bool().unwrap_or(false))
}
pub async fn reload(&self) -> Result<String, EdgeLinkError> {
let v = self.call("POST", "/v1/reload", None).await?;
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
.map(|_| ())
}
pub async fn acme_retry(&self) -> Result<(), EdgeLinkError> {
self.call("POST", "/v1/acme/retry", None).await.map(|_| ())
}
}
fn parse(raw: &[u8]) -> Result<(u16, Value), String> {
let end = raw
.windows(4)
.position(|w| w == b"\r\n\r\n")
.ok_or("no complete answer from edge")?;
let head = String::from_utf8_lossy(&raw[..end]);
let status: u16 = head
.split(' ')
.nth(1)
.and_then(|s| s.parse().ok())
.ok_or("no status from edge")?;
let chunked = head
.to_ascii_lowercase()
.contains("transfer-encoding: chunked");
let mut body = raw[end + 4..].to_vec();
if chunked {
let mut out = Vec::new();
let mut rest = &body[..];
while let Some(p) = rest.windows(2).position(|w| w == b"\r\n") {
let size = usize::from_str_radix(String::from_utf8_lossy(&rest[..p]).trim(), 16)
.map_err(|_| "odd chunk from edge")?;
rest = &rest[p + 2..];
if size == 0 || rest.len() < size {
break;
}
out.extend_from_slice(&rest[..size]);
rest = &rest[(size + 2).min(rest.len())..];
}
body = out;
}
let json = serde_json::from_slice(&body).unwrap_or(Value::Null);
Ok((status, json))
}
File diff suppressed because it is too large Load Diff
+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(())
}
}
+196
View File
@@ -0,0 +1,196 @@
// 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 host body of the API. It mirrors the host TOML file field for field (docs/ui-api.md
//! §1.2), so control writes exactly what Mark would write by hand. Core validates the TOML
//! control writes; this type only carries it.
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct HostSpec {
/// Lowercase DNS name, e.g. `wiki.home.example`.
pub hostname: String,
/// Where traffic goes, e.g. `http://10.0.0.23:3000`. Same scheme for all.
pub upstreams: Vec<String>,
/// `letsencrypt` or `domi`.
#[serde(default = "letsencrypt")]
pub tls: String,
/// `none` or `forward-auth`.
#[serde(default = "auth_none")]
pub auth: String,
#[serde(default = "yes")]
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,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub health_check: Option<HealthCheckSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub request_headers: Vec<HeaderRuleSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub response_headers: Vec<HeaderRuleSpec>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct HealthCheckSpec {
pub path: String,
#[serde(default = "ten")]
pub interval_secs: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct HeaderRuleSpec {
/// `set` or `remove`.
pub action: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
/// Name of a secret declared in `ianitor.toml`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub secret: Option<String>,
}
fn letsencrypt() -> String {
"letsencrypt".into()
}
fn auth_none() -> String {
"none".into()
}
fn off() -> String {
"off".into()
}
fn yes() -> bool {
true
}
fn ten() -> i64 {
10
}
impl HostSpec {
/// The TOML file control commits for this host. Every field is written out, so the file
/// says exactly what the form said.
pub fn to_toml(&self) -> Result<String, String> {
let body = toml::to_string(self).map_err(|e| e.to_string())?;
Ok(format!(
"# Written by Ianitor control. Edit through the web UI or the API.\n{body}"
))
}
pub fn from_toml(text: &str) -> Result<HostSpec, String> {
toml::from_str(text).map_err(|e| e.message().to_owned())
}
/// Field-level differences, labelled for the restore preview (docs/ui-api.md §1.4).
pub fn diff(&self, to: &HostSpec) -> Vec<(String, String, String)> {
let mut out = Vec::new();
let mut push = |f: &str, a: String, b: String| {
if a != b {
out.push((f.to_owned(), a, b));
}
};
push("hostname", self.hostname.clone(), to.hostname.clone());
push(
"upstreams",
self.upstreams.join(", "),
to.upstreams.join(", "),
);
push("tls", self.tls.clone(), to.tls.clone());
push("auth", self.auth.clone(), to.auth.clone());
push(
"websockets",
self.websockets.to_string(),
to.websockets.to_string(),
);
push(
"share_links",
self.share_links.to_string(),
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));
push(
"health_check.path",
a.as_ref().map(|x| x.0.clone()).unwrap_or_default(),
b.as_ref().map(|x| x.0.clone()).unwrap_or_default(),
);
push(
"health_check.interval_secs",
a.map(|x| x.1.to_string()).unwrap_or_default(),
b.map(|x| x.1.to_string()).unwrap_or_default(),
);
let rules =
|r: &[HeaderRuleSpec], q: &[HeaderRuleSpec]| format!("{} rules", r.len() + q.len());
if self.request_headers != to.request_headers
|| self.response_headers != to.response_headers
{
out.push((
"headers".into(),
rules(&self.request_headers, &self.response_headers),
rules(&to.request_headers, &to.response_headers),
));
}
out
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn round_trips_and_core_accepts_it() {
let h = HostSpec {
hostname: "wiki.home.test".into(),
upstreams: vec!["http://10.0.0.2:3000".into()],
tls: "domi".into(),
auth: "none".into(),
websockets: false,
share_links: true,
device_certs: true,
access_log: "truncated".into(),
health_check: Some(HealthCheckSpec {
path: "/health".into(),
interval_secs: 15,
}),
request_headers: vec![HeaderRuleSpec {
action: "set".into(),
name: "X-A".into(),
value: Some("1".into()),
secret: None,
}],
response_headers: vec![],
};
let text = h.to_toml().unwrap();
assert_eq!(HostSpec::from_toml(&text).unwrap(), h);
let m = ianitor_core::load(
&ianitor_core::SourceFile {
name: "ianitor.toml",
contents: "",
},
&[ianitor_core::SourceFile {
name: "hosts/wiki.home.test.toml",
contents: &text,
}],
);
assert!(m.is_ok(), "{m:?}");
}
}
+87
View File
@@ -0,0 +1,87 @@
// 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/.
//! Ianitor control: the routes repository, apply with automatic rollback, share links, API
//! tokens and the REST API, on loopback only. It never serves public traffic; if it stops,
//! 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;
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;
use std::sync::Arc;
pub use config::Config;
pub use engine::Control;
/// Open control, start its background tasks and serve the API until `shutdown` resolves.
pub async fn serve(
cfg: Config,
shutdown: impl std::future::Future<Output = ()> + Send + 'static,
) -> Result<(), String> {
cfg.check().map_err(|e| e.to_string())?;
let listen = cfg.listen;
let ctl = Control::open(cfg).await?;
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());
}
let listener = tokio::net::TcpListener::bind(listen)
.await
.map_err(|e| format!("cannot listen on {listen}: {e}"))?;
log::info!(target: "ianitor::control", "API on http://{listen}/api/v1");
axum::serve(listener, app)
.with_graceful_shutdown(shutdown)
.await
.map_err(|e| e.to_string())?;
drop(ctl);
Ok(())
}
/// Wait for Ctrl-C or SIGTERM.
pub async fn stop_signal() {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
let mut term = match signal(SignalKind::terminate()) {
Ok(s) => s,
Err(_) => {
let _ = tokio::signal::ctrl_c().await;
return;
}
};
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = term.recv() => {}
}
}
#[cfg(not(unix))]
{
let _ = tokio::signal::ctrl_c().await;
}
}
/// For tests: the router over an opened control.
pub fn app(ctl: Arc<Control>) -> axum::Router {
api::router(api::AppState::new(ctl))
}
+61
View File
@@ -0,0 +1,61 @@
// 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/.
//! Error log on stderr (journald under systemd). Control never logs request headers, bodies,
//! query strings, tokens, passwords or share links: request lines are logged as method and
//! route only, by the API layer.
use std::io::Write;
use log::{Level, LevelFilter, Log, Metadata, Record};
struct Stderr {
own: LevelFilter,
}
impl Log for Stderr {
fn enabled(&self, m: &Metadata<'_>) -> bool {
let limit = if m.target().starts_with("ianitor") {
self.own
} else {
self.own.min(LevelFilter::Info)
};
m.level() <= limit
}
fn log(&self, r: &Record<'_>) {
if self.enabled(r.metadata()) {
let lvl = match r.level() {
Level::Error => "ERROR",
Level::Warn => "WARN",
Level::Info => "INFO",
Level::Debug => "DEBUG",
Level::Trace => "TRACE",
};
let _ = writeln!(
std::io::stderr().lock(),
"{lvl} {}: {}",
r.target(),
r.args()
);
}
}
fn flush(&self) {
let _ = std::io::stderr().flush();
}
}
pub fn init(level: Option<&str>) {
let own = match level.map(str::to_ascii_lowercase).as_deref() {
Some("error") => LevelFilter::Error,
Some("warn") => LevelFilter::Warn,
Some("debug") => LevelFilter::Debug,
Some("trace") => LevelFilter::Trace,
_ => LevelFilter::Info,
};
if log::set_boxed_logger(Box::new(Stderr { own })).is_ok() {
log::set_max_level(own);
}
}
+432 -5
View File
@@ -2,11 +2,438 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this // 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/. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Placeholder for ianitor-control (ROADMAP phase 2). It deliberately opens no socket. //! ```text
//! ianitor-control --config <control.toml> run the control plane
//! ianitor-control --dev [--edge-bin <ianitor-edge>] temporary everything on 127.0.0.1
//! ianitor-control token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>)
//! 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`),
//! the binary answers git's prompt from the push credential file.
fn main() { use std::path::PathBuf;
println!( use std::process::ExitCode;
"ianitor-control {}: placeholder. The control plane (API on 127.0.0.1) arrives in phase 2.",
env!("CARGO_PKG_VERSION") use ianitor_control::{Config, logger, tokens::Tokens};
mod dev;
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> | \
caddy-revert --config <c> | caddy-guard --config <c>"
); );
ExitCode::from(2)
}
fn askpass() -> ExitCode {
// git asks "Username for 'https://…':" and "Password for 'https://…':".
let prompt = std::env::args().nth(1).unwrap_or_default();
if prompt.starts_with("Username") {
println!(
"{}",
std::env::var("IANITOR_ASKPASS_USER").unwrap_or_default()
);
return ExitCode::SUCCESS;
}
// Answer only the password prompt; anything else (a passphrase, a host key question)
// gets no answer, so the push fails instead of handing out the token.
if !prompt.starts_with("Password for") {
eprintln!("ianitor-control askpass: not answering {prompt:?}");
return ExitCode::FAILURE;
}
let Some(file) = std::env::var_os("IANITOR_ASKPASS_FILE") else {
return ExitCode::FAILURE;
};
match std::fs::read_to_string(file) {
Ok(v) => {
println!("{}", v.trim_end_matches(['\r', '\n']));
ExitCode::SUCCESS
}
Err(_) => ExitCode::FAILURE,
}
}
fn state_dir(args: &[String]) -> Result<PathBuf, String> {
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--state-dir" => {
return it
.next()
.map(PathBuf::from)
.ok_or("--state-dir needs a path".into());
}
"--config" => {
let p = it.next().ok_or("--config needs a path")?;
return Config::load(&PathBuf::from(p))
.map(|c| c.state_dir)
.map_err(|e| e.to_string());
}
_ => {}
}
}
Err("give --config <control.toml> or --state-dir <dir>".into())
}
/// The token files must stay owned by the user control runs as: refuse to touch them as
/// anyone else (typically root), instead of leaving root-owned files control cannot open.
#[cfg(unix)]
fn same_owner(dir: &std::path::Path) -> Result<(), String> {
use std::os::unix::fs::MetadataExt;
let existing = dir
.ancestors()
.find(|p| p.is_dir())
.ok_or_else(|| format!("no part of {} exists", dir.display()))?;
let owner = std::fs::metadata(existing)
.map_err(|e| format!("cannot read {}: {e}", existing.display()))?
.uid();
// Who we are, without libc: the owner of a file we create (in the temp dir, so nothing is
// created in the state dir by the wrong user).
let probe = std::env::temp_dir().join(format!(".ianitor-owner-probe-{}", std::process::id()));
// create_new: never follows or reuses a file someone else put there.
let me = std::fs::File::create_new(&probe)
.and_then(|f| f.metadata())
.map(|m| m.uid());
if me.is_ok() {
let _ = std::fs::remove_file(&probe);
}
let me = me.map_err(|e| format!("cannot create a probe file to learn who runs this: {e}"))?;
if me == 0 && !dir.is_dir() {
return Err(format!(
"{} does not exist; create it as the user control runs as (or run this as that user), not as root",
dir.display()
));
}
if me != owner {
return Err(format!(
"{} belongs to uid {owner}, but this runs as uid {me}; run it as that user (e.g. sudo -u ianitor ianitor-control token ...)",
existing.display()
));
}
Ok(())
}
#[cfg(not(unix))]
fn same_owner(_: &std::path::Path) -> Result<(), String> {
Ok(())
}
fn token(args: &[String]) -> Result<(), String> {
let dir = state_dir(args)?;
// Check the owner before creating anything: the nearest existing ancestor must belong to
// whoever runs this (so root does not create a state dir control cannot use).
same_owner(&dir)?;
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
let tokens = Tokens::new(&dir);
match args.first().map(String::as_str) {
Some("create") => {
let mut name = None;
let mut expires = Some(ianitor_control::util::now() + 365 * 86_400);
let mut it = args.iter().skip(1);
while let Some(a) = it.next() {
match a.as_str() {
"--name" => name = it.next().cloned(),
"--never" => expires = None,
"--expires-days" => {
let d: u64 = it
.next()
.and_then(|d| d.parse().ok())
.filter(|d| (1..=3650).contains(d))
.ok_or("--expires-days must be 1 to 3650")?;
expires = Some(ianitor_control::util::now() + d * 86_400);
}
_ => {}
}
}
let name = name.ok_or("--name <name> is required")?;
let (rec, value) = tokens.create(&name, expires).map_err(|e| {
if e == "token.name" {
"the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores"
.to_owned()
} else {
e
}
})?;
eprintln!(
"Token {} ({}) created. It is shown once; save it in Custos now:",
rec.id, rec.name
);
println!("{value}");
Ok(())
}
Some("list") => {
for t in tokens.list()? {
println!(
"{} {} created {}{}{}",
t.id,
t.name,
ianitor_control::util::rfc3339(t.created_at),
t.expires_at
.map(|e| format!(" expires {}", ianitor_control::util::rfc3339(e)))
.unwrap_or_default(),
t.revoked_at
.map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e)))
.unwrap_or_default()
);
}
Ok(())
}
Some("revoke") => {
let id = args.get(1).ok_or("token revoke <id>")?;
match tokens.revoke(id)? {
Some(_) => {
eprintln!("Token {id} revoked.");
Ok(())
}
None => Err(format!("there is no token {id}")),
}
}
_ => Err("token create | list | revoke".into()),
}
}
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();
}
logger::init(std::env::var("IANITOR_LOG").ok().as_deref());
let args: Vec<String> = std::env::args().skip(1).collect();
let rt = match tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
{
Ok(r) => r,
Err(e) => {
eprintln!("ianitor-control: cannot start: {e}");
return ExitCode::FAILURE;
}
};
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)) {
Ok(cfg) => rt.block_on(ianitor_control::serve(cfg, ianitor_control::stop_signal())),
Err(e) => Err(e.to_string()),
},
None => return usage(),
},
Some("--help" | "-h") | None => return usage(),
Some(_) => return usage(),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
log::error!(target: "ianitor::control", "{e}");
eprintln!("ianitor-control: {e}");
ExitCode::FAILURE
}
}
} }
+408
View File
@@ -0,0 +1,408 @@
// 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/.
//! Every user-facing message, by code, in the words of docs/ui-api.md §3. `{x}` is filled from
//! the params; a missing param leaves a plain gap rather than a placeholder.
use std::collections::BTreeMap;
pub type Params = BTreeMap<String, String>;
fn template(code: &str) -> &'static str {
match code {
// 3.1 host form
"host.hostname.missing" => "Enter the address people will type, like wiki.home.example.",
"host.hostname.uppercase" => "Use lowercase letters only: {suggestion}.",
"host.hostname.characters" => "Use only letters a–z, digits, dots and dashes.",
"host.hostname.spaces" => "Remove the spaces from the address.",
"host.hostname.wildcard" => {
"Addresses with * are not supported yet. Add each name as its own host."
}
"host.hostname.trailing_dot" => "Remove the dot at the end.",
"host.hostname.empty_label" => "There are two dots in a row. Remove one.",
"host.hostname.label_dash" => "A part of the address cannot start or end with a dash.",
"host.hostname.label_long" => "Each part between dots can be at most 63 characters.",
"host.hostname.too_long" => "The address can be at most 253 characters.",
"host.hostname.numeric" => {
"That looks like an IP address. Use a name, like wiki.home.example."
}
"host.hostname.taken" => "{hostname} is already a host.",
"host.hostname.mismatch" => {
"The address in the form ({hostname}) is not the host you are editing ({path_hostname})."
}
"host.file_name" => "The address does not match the file it is stored in.",
"host.upstreams.missing" => {
"Enter where Ianitor should send traffic, like http://10.0.0.23:3000."
}
"host.upstream.not_url" => "Write it as a full address, like http://10.0.0.23:3000.",
"host.upstream.scheme" => "Start the address with http:// or https://.",
"host.upstream.no_host" => "Add the server's name or IP address after http://.",
"host.upstream.host_name" => {
"The server name is not usable. Use letters a–z, digits, dots and dashes, or an IP address."
}
"host.upstream.no_port" => "Add the port at the end, like :3000.",
"host.upstream.port_zero" => {
"Port 0 cannot be used. Enter the port the service listens on."
}
"host.upstream.path" => "Leave out the path after the port. Visitors keep their own path.",
"host.upstream.query" | "host.upstream.fragment" => "Leave out everything after ? or #.",
"host.upstream.credentials" => {
"Leave out the user name and password. Put them in a header rule with a secret instead."
}
"host.upstream.duplicate" => "This address is listed twice.",
"host.upstream.mixed_schemes" => {
"All addresses for one host must start the same way: all http:// or all https://."
}
"host.upstream.too_many" => "One host can send traffic to at most {max} addresses.",
"host.auth.not_configured" => {
"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."
}
"host.header.name" => "\"{name}\" cannot be a header name. Use letters, digits and dashes.",
"host.header.value" => {
"This value has characters a header cannot carry. Use visible characters and spaces only."
}
"host.header.empty" => "Enter a value, or choose Remove to drop the header.",
"host.header.protected" => "Ianitor sets {name} itself, so a rule cannot change it.",
"host.header.duplicate" => "{name} already has a rule in this list.",
"host.header.both" => "Choose a fixed value or a secret, not both.",
"host.header.remove_value" => "Remove needs only the header name.",
"host.header.secret_unknown" => {
"There is no secret named {secret}. Secrets are listed in ianitor.toml and loaded from the server's credentials."
}
"host.header.secret_response" => {
"Secrets can only be sent to your service, never back to visitors."
}
"host.health.path" => "Start with / and use plain characters, like /health.",
"host.health.interval" => "Check every 1 to 3600 seconds.",
"host.field.unknown" => "Ianitor does not know the setting \"{field}\".",
"host.field.invalid" | "file.field.invalid" => {
"One of the settings has a value Ianitor cannot use. Show details to see which."
}
"file.field.missing" => "The setting \"{field}\" is missing.",
"change.conflict" => {
"{hostname} was changed at {time} (\"{summary}\") after you opened it. Your edits are still here. Check them, then Apply again."
}
"change.unchanged" => "This is the same as what is live now, so nothing changed.",
"host.not_found" => "{hostname} is no longer a host.",
"host.share.no_signin" => {
"Anyone can already open {hostname}, so a share link changes nothing."
}
// 3.2 apply, undo, restore, repository
"apply.queued" => "Waiting for \"{summary}\" to finish, about {seconds} s.",
"apply.kept" => "{hostname} is live. Health checks passed for {seconds} s.",
"apply.kept.no_watch" => {
"{hostname} is live. It has no health check, so Ianitor only checked that it answers."
}
"apply.kept.removed" => "{hostname} is removed.",
"apply.kept.no_edge" => {
"Saved. No proxy is attached (development mode), so nothing was checked."
}
"apply.reverted.refused" => {
"{hostname} was not {verb}. {upstream} refused the connection on {count} of {of} checks. Ianitor undid the change; every other host kept running."
}
"apply.reverted.timeout" => {
"{hostname} was not {verb}. {upstream} did not answer within 5 seconds on {count} of {of} checks. Ianitor undid the change."
}
"apply.reverted.not_found" => {
"{hostname} was not {verb}. {upstream} says {path} does not exist. Check the health check address. Ianitor undid the change."
}
"apply.reverted.server_error" => {
"{hostname} was not {verb}. {upstream} answered with an error page on {count} of {of} checks. Ianitor undid the change."
}
"apply.reverted.redirect" => {
"{hostname} was not {verb}. {upstream} sent visitors elsewhere instead of answering {path}. Use an address that answers directly, like /health."
}
"apply.reverted.sign_in" => {
"{hostname} was not {verb}. {upstream} asked for a sign-in on {path}. Use an address that answers without signing in."
}
"apply.reverted.name" => {
"{hostname} was not {verb}. The name {upstream_host} could not be found on this network."
}
"apply.reverted.tls" => {
"{hostname} was not {verb}. {upstream} uses https://, but its certificate could not be checked."
}
"apply.reverted.no_answer" => {
"{hostname} was not {verb}. No health check finished within {seconds} s. Ianitor undid the change."
}
"apply.reverted.edge_lost" => {
"The proxy restarted during the check, so it went back to the last good settings. Ianitor undid the change to match."
}
"apply.failed.reload" => {
"{engine} did not take the new settings, so nothing changed. Every host kept running."
}
"apply.failed.build" => {
"Ianitor could not build the settings for this change, so nothing changed."
}
"apply.failed.validation" => {
"This change no longer fits with the routes: {first_error} Nothing changed."
}
"apply.failed.edge_unreachable" => {
"Ianitor cannot reach the proxy right now, so nothing changed. Traffic is not affected."
}
"apply.interrupted" => {
"Ianitor restarted during the check, so it undid the change to be safe."
}
"apply.interrupted.queued" => {
"Ianitor restarted before this change ran, so nothing changed. Try again."
}
"apply.cancelled" => "Cancelled before it started. Nothing changed.",
"apply.needs_attention" => {
"The change failed its check, and Ianitor could not undo it by itself. Visitors are served the last good settings, but the routes repository still has the change."
}
"push.failed.unreachable" => {
"Kept, but not yet saved to {remote}: {remote} did not answer. Ianitor tries again at {time}."
}
"push.failed.rejected" => {
"Kept, but {remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server."
}
"push.failed.auth" => {
"Kept, but {remote} refused Ianitor's access key. Check the key in Custos."
}
"undo.nothing" => "Nothing to undo yet.",
"undo.watching" => "Wait for the check to finish ({seconds} s).",
"undo.paused" => "Changes are paused, so Undo is not available.",
"undo.target_moved" => {
"The last change is now \"{summary}\", so Undo did nothing. Look again and choose."
}
"restore.same" => "This version is the same as the current one. Nothing to restore.",
"restore.not_kept" => {
"This change was undone at the time, so there is nothing to go back to."
}
"change.not_found" => "There is no change with that id.",
"repo.unreadable" => {
"{file} in the routes repository cannot be read. Changes are paused until it is fixed."
}
"repo.unexpected_file" => "{file} does not belong in the routes repository.",
"repo.no_remote" => "No place to push to is set up.",
// 3.4 share links
"share.disabled" => {
"Share links are off for {hostname}. Turning them on is a change to the host, checked like any other."
}
"share.prefix" => "Start with /, like /share/summer-2026. / shares the whole site.",
"share.expiry" => "Choose between 1 hour and 90 days.",
"share.password_short" => "Use at least 8 characters.",
"share.password_long" => "Use at most 128 characters.",
"share.stopped" => "Stopped. The link stops working within a few seconds.",
"share.stopped_all" => "All share links are stopped. New ones work as usual.",
"share.unavailable" => {
"Share links are not set up on this server: the share-link key is missing from the credentials."
}
"share.too_many" => {
"There are 2,000 active share links already. Stop some, or stop all, then try again."
}
"share.not_found" => "There is no share link with that id.",
"share.replaces" => "The link to replace is not a link for {hostname}.",
// 3.5 tokens, limits
"token.missing" => "This request needs an API token. Make one in Settings, API.",
"token.unknown" => {
"This API token is not one Ianitor issued, or it was copied incompletely."
}
"token.expired" => {
"This API token expired on {date}. Make a new one in Settings, API, then revoke this one."
}
"token.revoked" => "This API token was revoked on {date}.",
"token.not_found" => "There is no API token with that id.",
"token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.",
"token.expiry" => "Choose between 1 and 3650 days, or never.",
"rate.limited" => "Too many requests in a short time. Try again in {seconds} s.",
"control.files_unwritten" => {
"The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them."
}
"control.paused" => "Changes are paused: {reason} Traffic keeps flowing.",
// request shape
"request.body" => "The request body is not valid: {problem}",
"request.body_unknown_field" => "Ianitor does not know the field \"{field}\".",
"request.too_large" => "The request body is too large.",
"request.csrf" => {
"This request came from a browser page without Ianitor's UI header, so it was refused."
}
"request.host" => "This request was sent to an address Ianitor does not answer on.",
"request.not_found" => "There is no such API call.",
"request.method" => "This API call does not take that method.",
"request.in_progress" => {
"The first request with this Idempotency-Key is still being handled. Try again in a moment."
}
"request.idempotency" => "This Idempotency-Key was already used for a different request.",
"request.base_rev" => "base_rev is not a commit in the routes history.",
"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.",
}
}
/// The message for `code`, with params filled in.
pub fn message(code: &str, params: &Params) -> String {
let t = template(code);
let mut out = String::with_capacity(t.len() + 32);
let mut rest = t;
while let Some(start) = rest.find('{') {
out.push_str(&rest[..start]);
let after = &rest[start + 1..];
match after.find('}') {
Some(end) => {
let key = &after[..end];
if let Some(v) = params.get(key) {
out.push_str(v);
}
rest = &after[end + 1..];
}
None => {
out.push_str(&rest[start..]);
rest = "";
}
}
}
out.push_str(rest);
out
}
pub fn params<const N: usize>(pairs: [(&str, String); N]) -> Params {
pairs.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn placeholders_are_filled() {
let p = params([("hostname", "a.test".into()), ("max", "64".into())]);
assert_eq!(
message("host.hostname.taken", &p),
"a.test is already a host."
);
assert_eq!(
message("host.upstream.too_many", &p),
"One host can send traffic to at most 64 addresses."
);
assert!(!message("token.revoked", &Params::new()).contains('{'));
}
}
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())])),
)
}
}
+201
View File
@@ -0,0 +1,201 @@
// 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/.
//! Apply records (one per user action: the history the UI shows, docs/ui-api.md §2.1) and the
//! apply journal (what a crash interrupted).
//!
//! The journal (`journal.json`) is written, atomically and durably, before every step that
//! changes the outside world, so after a crash control knows how far an apply got:
//!
//! | stage | what has happened | recovery |
//! |:--|:--|:--|
//! | `prepared` | commit object made, branch not moved | branch at base: nothing to undo; at the commit: as `committed` |
//! | `committed` | branch moved to the commit | revert commit, abort trial, drop trial files |
//! | `trial_written` | trial files written | same |
//! | `trial_loaded` | edge serves the trial (and reverts by itself at its deadline) | same |
//! | `confirmed` | edge confirmed the trial | promote trial files, record kept |
//! | `promoted` | files promoted | record kept |
//! | `reverting` | revert started | finish the revert |
//!
//! Throughout, `edge.json` and `caddy.json` only ever hold a config that passed its watch.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::hostspec::HostSpec;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct Step {
/// `validate`, `compile`, `write`, `reload`, `watch` or `push`.
pub key: String,
/// `pending`, `running`, `done`, `failed` or `skipped`.
pub state: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, ToSchema)]
pub struct WatchHost {
pub hostname: String,
pub passed: u32,
pub failed: u32,
pub total: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct Watch {
/// Unix seconds.
pub ends: u64,
pub hosts: Vec<WatchHost>,
}
/// Why an apply did not stay (or a detail of why it did).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, ToSchema)]
pub struct Reason {
pub code: String,
/// Plain English, from `messages`.
pub message: String,
pub hostname: Option<String>,
pub upstream: Option<String>,
pub field: Option<String>,
pub count: Option<u32>,
pub of: Option<u32>,
/// Technical detail (core's text, edge's error); never a secret.
pub detail: Option<String>,
#[serde(default)]
pub params: BTreeMap<String, String>,
}
/// One field problem, in the API error shape.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct FieldError {
pub code: String,
pub message: String,
pub field: Option<String>,
pub params: BTreeMap<String, String>,
pub detail: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ApplyRecord {
pub id: String,
/// `add`, `edit`, `remove`, `undo`, `restore` or `share_links`.
pub kind: String,
pub summary: String,
pub hosts: Vec<String>,
/// `queued`, `validating`, `applying`, `watching`, `kept`, `reverted`, `failed` or
/// `needs_attention`.
pub state: String,
pub steps: Vec<Step>,
pub created: u64,
pub started: Option<u64>,
pub finished: Option<u64>,
pub watch: Option<Watch>,
pub reason: Option<Reason>,
#[serde(default)]
pub errors: Vec<FieldError>,
/// Branch head when the apply started.
pub base: Option<String>,
/// The commit of this change (none if it never got one).
pub commit: Option<String>,
/// The commit that undid it, for reverted applies.
pub revert_commit: Option<String>,
pub undo_of: Option<String>,
pub restore_of: Option<String>,
/// Token name of whoever asked.
pub actor: String,
/// What was tried, for "Edit and try again".
pub attempted_host: Option<HostSpec>,
/// For undo: what it does ("Removes x").
pub effect: Option<String>,
}
pub const STEP_KEYS: [&str; 6] = ["validate", "compile", "write", "reload", "watch", "push"];
impl ApplyRecord {
pub fn new(
id: String,
kind: &str,
summary: String,
hosts: Vec<String>,
actor: &str,
t: u64,
) -> ApplyRecord {
ApplyRecord {
id,
kind: kind.into(),
summary,
hosts,
state: "queued".into(),
steps: STEP_KEYS
.iter()
.map(|k| Step {
key: (*k).into(),
state: "pending".into(),
})
.collect(),
created: t,
started: None,
finished: None,
watch: None,
reason: None,
errors: Vec::new(),
base: None,
commit: None,
revert_commit: None,
undo_of: None,
restore_of: None,
actor: actor.into(),
attempted_host: None,
effect: None,
}
}
pub fn step(&mut self, key: &str, state: &str) {
if let Some(s) = self.steps.iter_mut().find(|s| s.key == key) {
s.state = state.into();
}
}
pub fn is_active(&self) -> bool {
matches!(
self.state.as_str(),
"queued" | "validating" | "applying" | "watching"
)
}
pub fn is_running(&self) -> bool {
matches!(self.state.as_str(), "validating" | "applying" | "watching")
}
/// A kept change with a commit: something Undo can target.
pub fn is_kept_change(&self) -> bool {
self.state == "kept" && self.commit.is_some()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Journal {
pub apply_id: String,
pub stage: String,
pub base: String,
pub commit: String,
pub edge_sha256: Option<String>,
pub reason: Option<Reason>,
}
/// Push state, in `push.json`.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct PushState {
pub pushed: Option<String>,
pub last_push_at: Option<u64>,
pub last_attempt_at: Option<u64>,
pub next_try_at: Option<u64>,
pub error_code: Option<String>,
pub error_detail: Option<String>,
#[serde(default)]
pub failures: u32,
}
+561
View File
@@ -0,0 +1,561 @@
// 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 routes repository: a bare git repository driven through the `git` binary.
//!
//! Why the `git` binary (not git2 or gix): pushing to Gitea over HTTPS or SSH is required,
//! and gix cannot push yet; git2 would bring libgit2 plus OpenSSL/libssh2 as C dependencies
//! into the Nix build, while `git` is one store path Mark already uses, with the same
//! behaviour he sees by hand. Control only uses plumbing with fixed arguments: commit ids are
//! checked to be hex before they reach a command line, file content goes through stdin, the
//! environment is cleared (no user or system git config, no hooks, no prompts), and objects
//! and refs are fsync'ed so a crash cannot lose a commit edge already runs.
//!
//! Control never reads a working tree: trees are read from git objects, so symbolic links or
//! files outside the repository cannot be smuggled in. A tree must have exactly the shape
//! `ianitor_core::routes` allows.
use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use ianitor_core::routes::{self, EntryKind, SITE_FILE};
use ianitor_core::{MAX_FILE_BYTES, ValidationError};
#[derive(Debug, thiserror::Error)]
pub enum RepoError {
#[error("git {op} failed: {message}")]
Git { op: String, message: String },
#[error("the routes repository has files that do not belong there")]
Shape(Vec<ValidationError>),
#[error("{0} is not a commit in the routes history")]
UnknownCommit(String),
#[error("{0}")]
Other(String),
}
/// A commit id: 40 (SHA-1) or 64 (SHA-256) lowercase hex digits.
pub fn is_commit_id(s: &str) -> bool {
(s.len() == 40 || s.len() == 64)
&& s.bytes()
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
}
/// The files of one routes tree: path → content. Paths are exactly `ianitor.toml` and
/// `hosts/<hostname>.toml`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RouteTree {
pub files: BTreeMap<String, String>,
}
impl RouteTree {
pub fn site(&self) -> &str {
self.files.get(SITE_FILE).map_or("", String::as_str)
}
pub fn host(&self, hostname: &str) -> Option<&str> {
self.files
.get(&routes::host_path(hostname))
.map(String::as_str)
}
pub fn hostnames(&self) -> Vec<String> {
self.files
.keys()
.filter_map(|p| p.strip_prefix("hosts/")?.strip_suffix(".toml"))
.map(str::to_owned)
.collect()
}
pub fn set_host(&mut self, hostname: &str, contents: String) {
self.files.insert(routes::host_path(hostname), contents);
}
pub fn remove_host(&mut self, hostname: &str) -> bool {
self.files.remove(&routes::host_path(hostname)).is_some()
}
/// Load and validate with core.
pub fn model(&self) -> Result<ianitor_core::Model, ianitor_core::ValidationErrors> {
let hosts: Vec<ianitor_core::SourceFile> = self
.files
.iter()
.filter(|(p, _)| p.as_str() != SITE_FILE)
.map(|(p, c)| ianitor_core::SourceFile {
name: p,
contents: c,
})
.collect();
ianitor_core::load(
&ianitor_core::SourceFile {
name: SITE_FILE,
contents: self.site(),
},
&hosts,
)
}
}
/// Facts about one commit.
#[derive(Debug, Clone)]
pub struct CommitInfo {
pub id: String,
pub parents: Vec<String>,
pub time: u64,
pub subject: String,
}
pub struct Repo {
git: PathBuf,
dir: PathBuf,
home: PathBuf,
branch: String,
cache: Mutex<Option<(String, Arc<RouteTree>)>>,
}
fn null_device() -> &'static str {
if cfg!(windows) { "NUL" } else { "/dev/null" }
}
impl Repo {
/// Open (or create, with an empty `ianitor.toml`) the bare repository at `dir`.
pub fn open(git: &Path, dir: &Path, home: &Path, branch: &str) -> Result<Repo, RepoError> {
Repo::open_seeded(git, dir, home, branch, "")
}
/// Like [`Repo::open`]; a new repository starts with `site` as its `ianitor.toml`.
pub fn open_seeded(
git: &Path,
dir: &Path,
home: &Path,
branch: &str,
site: &str,
) -> Result<Repo, RepoError> {
let repo = Repo {
git: git.to_owned(),
dir: dir.to_owned(),
home: home.to_owned(),
branch: branch.to_owned(),
cache: Mutex::new(None),
};
if !dir.join("HEAD").exists() {
std::fs::create_dir_all(dir).map_err(|e| RepoError::Other(e.to_string()))?;
repo.run_in(
None,
&[
"init",
"--bare",
"--quiet",
&format!("--initial-branch={branch}"),
],
Some(dir),
None,
&[],
)?;
}
if repo.head()?.is_none() {
let mut t = RouteTree::default();
t.files.insert(SITE_FILE.into(), site.to_owned());
let tree = repo.write_tree(&t, None)?;
let c = repo.commit(&tree, &[], "Start the routes repository", "Ianitor control")?;
repo.update_ref(&c, None)?;
}
Ok(repo)
}
pub fn dir(&self) -> &Path {
&self.dir
}
fn command(&self) -> Command {
let mut c = Command::new(&self.git);
c.env_clear();
if let Some(p) = std::env::var_os("PATH") {
c.env("PATH", p);
}
#[cfg(windows)]
for v in ["SYSTEMROOT", "TEMP", "TMP"] {
if let Some(x) = std::env::var_os(v) {
c.env(v, x);
}
}
c.env("HOME", &self.home)
.env("LC_ALL", "C")
.env("GIT_CONFIG_NOSYSTEM", "1")
.env("GIT_CONFIG_GLOBAL", null_device())
.env("GIT_TERMINAL_PROMPT", "0")
.args([
"-c",
&format!("core.hooksPath={}", null_device()),
"-c",
"core.fsync=all",
"-c",
"core.fsyncMethod=fsync",
]);
c
}
fn run_in(
&self,
git_dir: Option<&Path>,
args: &[&str],
cwd: Option<&Path>,
stdin: Option<&[u8]>,
env: &[(&str, &str)],
) -> Result<Vec<u8>, RepoError> {
let mut c = self.command();
if let Some(d) = git_dir {
c.env("GIT_DIR", d);
}
if let Some(d) = cwd {
c.current_dir(d);
}
for (k, v) in env {
c.env(k, v);
}
c.args(args)
.stdin(if stdin.is_some() {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let op = args.first().copied().unwrap_or("").to_owned();
let mut child = c.spawn().map_err(|e| RepoError::Git {
op: op.clone(),
message: format!("cannot run {}: {e}", self.git.display()),
})?;
if let (Some(data), Some(mut si)) = (stdin, child.stdin.take()) {
si.write_all(data).map_err(|e| RepoError::Git {
op: op.clone(),
message: e.to_string(),
})?;
}
let out = child.wait_with_output().map_err(|e| RepoError::Git {
op: op.clone(),
message: e.to_string(),
})?;
if !out.status.success() {
return Err(RepoError::Git {
op,
message: String::from_utf8_lossy(&out.stderr)
.trim()
.chars()
.take(500)
.collect(),
});
}
Ok(out.stdout)
}
fn git(&self, args: &[&str], stdin: Option<&[u8]>) -> Result<Vec<u8>, RepoError> {
self.run_in(Some(&self.dir), args, None, stdin, &[])
}
fn git_str(&self, args: &[&str]) -> Result<String, RepoError> {
Ok(String::from_utf8_lossy(&self.git(args, None)?)
.trim()
.to_owned())
}
fn reference(&self) -> String {
format!("refs/heads/{}", self.branch)
}
/// The current commit of the branch.
pub fn head(&self) -> Result<Option<String>, RepoError> {
match self.git(
&["rev-parse", "--verify", "--quiet", &self.reference()],
None,
) {
Ok(out) => {
let s = String::from_utf8_lossy(&out).trim().to_owned();
Ok(is_commit_id(&s).then_some(s))
}
Err(RepoError::Git { .. }) => Ok(None),
Err(e) => Err(e),
}
}
pub fn head_required(&self) -> Result<String, RepoError> {
self.head()?
.ok_or_else(|| RepoError::Other("the routes branch has no commit".into()))
}
/// Is `id` a commit reachable from the branch head?
pub fn in_history(&self, id: &str) -> Result<bool, RepoError> {
if !is_commit_id(id) {
return Ok(false);
}
let head = self.head_required()?;
let mut c = self.command();
c.env("GIT_DIR", &self.dir)
.args(["merge-base", "--is-ancestor", id, &head])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
let st = c.status().map_err(|e| RepoError::Git {
op: "merge-base".into(),
message: e.to_string(),
})?;
Ok(st.success())
}
pub fn info(&self, id: &str) -> Result<CommitInfo, RepoError> {
if !is_commit_id(id) {
return Err(RepoError::UnknownCommit(id.chars().take(64).collect()));
}
let out = self
.git(
&[
"show",
"-s",
"--format=%H%x00%P%x00%at%x00%s",
"--end-of-options",
id,
],
None,
)
.map_err(|_| RepoError::UnknownCommit(id.to_owned()))?;
let text = String::from_utf8_lossy(&out);
let mut f = text.trim_end_matches('\n').split('\0');
let (Some(h), Some(p), Some(t), Some(s)) = (f.next(), f.next(), f.next(), f.next()) else {
return Err(RepoError::UnknownCommit(id.to_owned()));
};
Ok(CommitInfo {
id: h.to_owned(),
parents: p
.split(' ')
.filter(|x| !x.is_empty())
.map(str::to_owned)
.collect(),
time: t.parse().unwrap_or(0),
subject: s.to_owned(),
})
}
/// Read the tree of a commit, checking its shape. Cached for the last commit read.
pub fn tree(&self, commit: &str) -> Result<Arc<RouteTree>, RepoError> {
if !is_commit_id(commit) {
return Err(RepoError::UnknownCommit(commit.chars().take(64).collect()));
}
if let Ok(c) = self.cache.lock()
&& let Some((id, t)) = c.as_ref()
&& id == commit
{
return Ok(t.clone());
}
let listing = self.git(&["ls-tree", "-r", "-z", "--full-tree", "-l", commit], None)?;
let mut entries = Vec::new();
for rec in listing.split(|b| *b == 0).filter(|r| !r.is_empty()) {
let rec = String::from_utf8_lossy(rec);
let (meta, path) = rec
.split_once('\t')
.ok_or_else(|| RepoError::Other("unexpected ls-tree output".into()))?;
let mut m = meta.split_whitespace();
let (mode, kind, sha, size) = (m.next(), m.next(), m.next(), m.next());
let entry_kind = match (mode, kind) {
(Some("100644"), Some("blob")) => EntryKind::File,
(Some("100755"), Some("blob")) => EntryKind::Executable,
(Some("120000"), _) => EntryKind::Symlink,
_ => EntryKind::Submodule,
};
let size: usize = size.and_then(|s| s.parse().ok()).unwrap_or(0);
entries.push((
path.to_owned(),
entry_kind,
sha.unwrap_or("").to_owned(),
size,
));
}
routes::check_tree(entries.iter().map(|(p, k, _, _)| (p.as_str(), *k)))
.map_err(RepoError::Shape)?;
let mut tree = RouteTree::default();
for (path, _, sha, size) in entries {
if size > MAX_FILE_BYTES {
return Err(RepoError::Shape(vec![ValidationError::FileTooLarge {
file: path,
max: MAX_FILE_BYTES,
}]));
}
if !is_commit_id(&sha) {
return Err(RepoError::Other("unexpected object id".into()));
}
let blob = self.git(&["cat-file", "blob", &sha], None)?;
let text = String::from_utf8(blob).map_err(|_| {
RepoError::Shape(vec![ValidationError::Syntax {
file: path.clone(),
line: None,
message: "the file is not UTF-8 text".into(),
}])
})?;
tree.files.insert(path, text);
}
let tree = Arc::new(tree);
if let Ok(mut c) = self.cache.lock() {
*c = Some((commit.to_owned(), tree.clone()));
}
Ok(tree)
}
/// Write the tree objects for `tree`; returns the tree id.
pub fn write_tree(&self, tree: &RouteTree, _base: Option<&str>) -> Result<String, RepoError> {
let mut hosts = Vec::new();
let mut root = Vec::new();
for (path, content) in &tree.files {
let sha = self.git_str_in(&["hash-object", "-w", "--stdin"], content.as_bytes())?;
if let Some(name) = path.strip_prefix("hosts/") {
hosts.extend_from_slice(format!("100644 blob {sha}\t{name}\0").as_bytes());
} else {
root.extend_from_slice(format!("100644 blob {sha}\t{path}\0").as_bytes());
}
}
if !hosts.is_empty() {
let sub = self.git_str_in(&["mktree", "-z"], &hosts)?;
root.extend_from_slice(format!("040000 tree {sub}\thosts\0").as_bytes());
}
self.git_str_in(&["mktree", "-z"], &root)
}
fn git_str_in(&self, args: &[&str], stdin: &[u8]) -> Result<String, RepoError> {
let out = self.git(args, Some(stdin))?;
let s = String::from_utf8_lossy(&out).trim().to_owned();
if !is_commit_id(&s) {
return Err(RepoError::Other(format!(
"git {} gave no object id",
args[0]
)));
}
Ok(s)
}
/// Create a commit object (not yet on the branch).
pub fn commit(
&self,
tree: &str,
parents: &[&str],
message: &str,
author: &str,
) -> Result<String, RepoError> {
let mut args = vec!["commit-tree", tree];
for p in parents {
args.push("-p");
args.push(p);
}
args.extend(["-F", "-"]);
let author: String = author
.chars()
.filter(|c| !c.is_control() && !"<>".contains(*c))
.take(64)
.collect();
let author = if author.trim().is_empty() {
"Ianitor control".to_owned()
} else {
author
};
let env = [
("GIT_AUTHOR_NAME", author.as_str()),
("GIT_AUTHOR_EMAIL", "ianitor@localhost"),
("GIT_COMMITTER_NAME", "Ianitor control"),
("GIT_COMMITTER_EMAIL", "ianitor@localhost"),
];
let out = self.run_in(Some(&self.dir), &args, None, Some(message.as_bytes()), &env)?;
let s = String::from_utf8_lossy(&out).trim().to_owned();
if !is_commit_id(&s) {
return Err(RepoError::Other("git commit-tree gave no commit id".into()));
}
Ok(s)
}
pub fn tree_id(&self, commit: &str) -> Result<String, RepoError> {
if !is_commit_id(commit) {
return Err(RepoError::UnknownCommit(commit.to_owned()));
}
self.git_str(&["rev-parse", "--verify", &format!("{commit}^{{tree}}")])
}
/// Move the branch to `new` only if it is still at `old` (compare and swap).
pub fn update_ref(&self, new: &str, old: Option<&str>) -> Result<(), RepoError> {
let zero = "0".repeat(new.len());
let old = old.unwrap_or(&zero);
self.git(&["update-ref", &self.reference(), new, old], None)
.map(|_| ())
}
/// Number of commits in `to` that are not in `from` (`from` none: all of `to`).
pub fn count_between(&self, from: Option<&str>, to: &str) -> Result<u64, RepoError> {
let range = match from {
Some(f) if is_commit_id(f) => format!("{f}..{to}"),
_ => to.to_owned(),
};
Ok(self
.git_str(&["rev-list", "--count", &range])?
.parse()
.unwrap_or(0))
}
/// Push `commit` to the branch on `remote`. Credentials come through `GIT_ASKPASS`
/// (this binary's `askpass` mode), never on a command line or in a file.
pub async fn push(
&self,
remote: &str,
commit: &str,
askpass: Option<(PathBuf, String, PathBuf)>,
timeout: std::time::Duration,
) -> Result<(), RepoError> {
if !is_commit_id(commit) {
return Err(RepoError::UnknownCommit(commit.to_owned()));
}
let std_cmd = self.command();
let mut c = tokio::process::Command::from(std_cmd);
c.env("GIT_DIR", &self.dir);
if let Some((exe, user, file)) = askpass {
c.env("GIT_ASKPASS", exe)
.env("IANITOR_ASKPASS", "1")
.env("IANITOR_ASKPASS_USER", user)
.env("IANITOR_ASKPASS_FILE", file);
}
c.args([
"push",
"--porcelain",
"--",
remote,
&format!("{commit}:{}", self.reference()),
])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let child = c.spawn().map_err(|e| RepoError::Git {
op: "push".into(),
message: e.to_string(),
})?;
let out = tokio::time::timeout(timeout, child.wait_with_output())
.await
.map_err(|_| RepoError::Git {
op: "push".into(),
message: format!("no answer within {} s", timeout.as_secs()),
})?
.map_err(|e| RepoError::Git {
op: "push".into(),
message: e.to_string(),
})?;
if out.status.success() {
Ok(())
} else {
let text = format!(
"{} {}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
Err(RepoError::Git {
op: "push".into(),
message: text.trim().chars().take(500).collect(),
})
}
}
}
+309
View File
@@ -0,0 +1,309 @@
// 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/.
//! Share links on control's side: minting, the list, stopping.
//!
//! Control keeps what it minted in `share-links.json` (never the token itself) and writes
//! the revocation file edge reads (`{"epoch": n, "deny": [ids]}`): ids of stopped links that
//! have not expired yet, and the epoch below which every token is refused ("stop all").
//! The file lives outside git, is written atomically, and edge re-reads it when control asks
//! and on its own every 5 s. When control is down nothing can be stopped, but edge keeps
//! refusing what is already on the list, also across its own restarts.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use ianitor_core::share::{self, LinkSpec, ShareId, ShareKey};
use serde::{Deserialize, Serialize};
use crate::util::{now, random, read_json, write_json};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LinkRecord {
pub id: String,
pub hostname: String,
pub path_prefix: String,
pub epoch: u32,
pub created_at: u64,
pub expires_at: u64,
pub has_password: bool,
pub created_by: String,
pub stopped_at: Option<u64>,
}
impl LinkRecord {
pub fn state(&self, epoch: u32, t: u64) -> &'static str {
if self.stopped_at.is_some() || self.epoch < epoch {
"stopped"
} else if t >= self.expires_at {
"expired"
} else {
"active"
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ShareFile {
pub epoch: u32,
pub links: Vec<LinkRecord>,
}
#[derive(Serialize)]
struct RevocationFile {
epoch: u32,
deny: Vec<String>,
}
/// Kept in the list this long after expiry or stop.
const KEEP_SECS: u64 = 30 * 86_400;
pub const MIN_EXPIRY: u64 = 3600;
pub const MAX_EXPIRY: u64 = 90 * 86_400;
/// Most active links at once.
pub const MAX_ACTIVE: usize = 2000;
/// Most ids edge takes on its deny list (edge refuses 10,000 and more).
const MAX_DENY: usize = 9_999;
pub struct Shares {
path: PathBuf,
revocations: PathBuf,
lock: std::sync::Mutex<()>,
}
pub struct Minted {
pub record: LinkRecord,
pub token: String,
}
#[derive(Debug, PartialEq, Eq)]
pub enum MintError {
Prefix,
Expiry,
PasswordShort,
PasswordLong,
Replaces,
/// More active links than [`MAX_ACTIVE`].
TooMany,
Store(String),
}
impl Shares {
pub fn new(state_dir: &Path, revocations: &Path) -> Shares {
Shares {
path: state_dir.join("share-links.json"),
revocations: revocations.to_owned(),
lock: std::sync::Mutex::new(()),
}
}
pub fn load(&self) -> Result<ShareFile, String> {
Ok(read_json(&self.path)?.unwrap_or_default())
}
/// The revocation file as edge has it now, if it can be read.
fn published(&self) -> Option<(u32, BTreeSet<String>)> {
#[derive(Deserialize)]
struct Published {
epoch: u32,
deny: Vec<String>,
}
let p: Published = serde_json::from_slice(&std::fs::read(&self.revocations).ok()?).ok()?;
Some((p.epoch, p.deny.into_iter().collect()))
}
/// The records, with the epoch never below the published one (records lost or restored
/// from an older backup must not bring stopped links back).
fn load_reconciled(&self) -> Result<ShareFile, String> {
let mut f = self.load()?;
if let Some((epoch, _)) = self.published()
&& epoch > f.epoch
{
log::warn!(target: "ianitor::share", "share-link records are behind the published revocations (epoch {} < {epoch}); continuing from {epoch}", f.epoch);
f.epoch = epoch;
}
Ok(f)
}
fn save(&self, f: &mut ShareFile) -> Result<(), String> {
let t = now();
// Kept at least until they expire: a stopped link must stay on the deny list as long
// as its token would otherwise work.
f.links
.retain(|l| t < l.expires_at.saturating_add(KEEP_SECS));
let deny = self.reconcile(f);
write_json(&self.path, f)?;
self.publish(f.epoch, deny)
}
/// The deny list for `f`, raising `f.epoch` when the list cannot be kept whole:
/// - a published id that the records cannot account for (stopped link lost from the
/// records) is never just dropped: the epoch goes up, which stops every older link;
/// - a list longer than edge accepts also raises the epoch, instead of being cut short.
fn reconcile(&self, f: &mut ShareFile) -> Vec<String> {
let t = now();
let published = self.published();
if let Some((epoch, _)) = &published {
f.epoch = f.epoch.max(*epoch);
}
let deny_for = |f: &ShareFile| -> Vec<String> {
let mut d: Vec<String> = f
.links
.iter()
.filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch)
.map(|l| l.id.clone())
.collect();
d.sort();
d
};
let mut deny = deny_for(f);
if let Some((epoch, old)) = published
&& epoch == f.epoch
{
let accounted = |id: &String| {
deny.binary_search(id).is_ok()
|| f.links
.iter()
.any(|l| &l.id == id && (l.expires_at <= t || l.epoch < f.epoch))
};
if !old.iter().all(accounted) {
log::warn!(target: "ianitor::share", "stopped links are missing from the records; raising the epoch, which stops every earlier link");
f.epoch = f.epoch.saturating_add(1);
deny = deny_for(f);
}
}
if deny.len() > MAX_DENY {
log::warn!(target: "ianitor::share", "more than {MAX_DENY} stopped links; raising the epoch, which stops every earlier link");
f.epoch = f.epoch.saturating_add(1);
deny = deny_for(f);
}
deny
}
/// Write the revocation file edge reads.
fn publish(&self, epoch: u32, deny: Vec<String>) -> Result<(), String> {
// Readable by edge (another user); it holds only random link ids.
let text =
serde_json::to_vec(&RevocationFile { epoch, deny }).map_err(|e| e.to_string())?;
crate::util::write_atomic(&self.revocations, &text, 0o644)
.map_err(|e| format!("cannot write {}: {e}", self.revocations.display()))
}
pub fn ensure_revocation_file(&self) -> Result<(), String> {
let _g = self
.lock
.lock()
.map_err(|_| "share store unavailable".to_owned())?;
let mut f = self.load()?;
self.save(&mut f)
}
#[allow(clippy::too_many_arguments)]
pub fn mint(
&self,
key: &ShareKey,
hostname: &str,
prefix: &str,
expires_in: u64,
password: Option<&str>,
replaces: Option<&str>,
actor: &str,
) -> Result<Minted, MintError> {
let prefix = share::check_prefix(prefix).map_err(|_| MintError::Prefix)?;
if !(MIN_EXPIRY..=MAX_EXPIRY).contains(&expires_in) {
return Err(MintError::Expiry);
}
if let Some(p) = password {
let n = p.chars().count();
if n < share::MIN_PASSWORD_CHARS {
return Err(MintError::PasswordShort);
}
if n > share::MAX_PASSWORD_CHARS {
return Err(MintError::PasswordLong);
}
}
let _g = self
.lock
.lock()
.map_err(|_| MintError::Store("share store unavailable".into()))?;
let mut f = self.load_reconciled().map_err(MintError::Store)?;
let t0 = now();
if f.links
.iter()
.filter(|l| l.stopped_at.is_none() && l.expires_at > t0)
.count()
>= MAX_ACTIVE
{
return Err(MintError::TooMany);
}
if let Some(r) = replaces {
let Some(old) = f
.links
.iter_mut()
.find(|l| l.id == r && l.hostname == hostname)
else {
return Err(MintError::Replaces);
};
old.stopped_at.get_or_insert(now());
}
// Settle the epoch first (lost records, an overflowing deny list): a link minted
// below the epoch that is about to be published would be dead on arrival.
let _ = self.reconcile(&mut f);
let id = ShareId(random::<16>().map_err(|e| MintError::Store(e.to_string()))?);
let t = now();
let spec = LinkSpec {
id,
epoch: f.epoch,
expires_at: t + expires_in,
prefix: &prefix,
password,
};
let token =
share::mint(key, hostname, &spec).map_err(|e| MintError::Store(e.to_string()))?;
let record = LinkRecord {
id: id.to_hex(),
hostname: hostname.to_owned(),
path_prefix: prefix.clone(),
epoch: f.epoch,
created_at: t,
expires_at: t + expires_in,
has_password: password.is_some(),
created_by: actor.to_owned(),
stopped_at: None,
};
f.links.push(record.clone());
self.save(&mut f).map_err(MintError::Store)?;
Ok(Minted { record, token })
}
/// Stop one link. `Ok(None)` when there is no such link.
pub fn stop(&self, id: &str) -> Result<Option<LinkRecord>, String> {
let _g = self
.lock
.lock()
.map_err(|_| "share store unavailable".to_owned())?;
let mut f = self.load_reconciled()?;
let Some(l) = f.links.iter_mut().find(|l| l.id == id) else {
return Ok(None);
};
l.stopped_at.get_or_insert(now());
let r = l.clone();
self.save(&mut f)?;
Ok(Some(r))
}
/// Stop every link minted so far by raising the epoch.
pub fn stop_all(&self) -> Result<u32, String> {
let _g = self
.lock
.lock()
.map_err(|_| "share store unavailable".to_owned())?;
let mut f = self.load_reconciled()?;
f.epoch = f.epoch.saturating_add(1);
let e = f.epoch;
self.save(&mut f)?;
Ok(e)
}
}
+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,
}
}
+263
View File
@@ -0,0 +1,263 @@
// 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/.
//! API tokens. A token is `ian_<id>_<secret>`: a 16-hex-digit id (for listing and lookup)
//! and 32 random bytes. Control stores only SHA-256 of the whole token, in `tokens.json`
//! (mode 0600), and compares in constant time.
//!
//! A fast hash is enough here: the secret has 256 bits of entropy, so nobody can find a
//! preimage by guessing, slow or fast; slow password hashes only help low-entropy secrets
//! that people pick. The comparison is constant-time anyway (it compares hashes of the
//! presented value, so even a timing leak would say nothing about a stored hash's preimage).
//!
//! The value is shown once, in the response that creates it (or by `ianitor-control token
//! create`), and never logged. Revoked and expired tokens stay listed so a script gets a
//! precise message ("revoked on …").
use std::path::{Path, PathBuf};
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::{Deserialize, Serialize};
use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TokenRecord {
pub id: String,
pub name: String,
pub sha256: String,
pub created_at: u64,
pub expires_at: Option<u64>,
pub last_used_at: Option<u64>,
pub revoked_at: Option<u64>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct TokenFile {
tokens: Vec<TokenRecord>,
}
/// Why a presented token was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Refusal {
Missing,
Unknown,
Expired(u64),
Revoked(u64),
}
pub const MAX_TOKENS: usize = 200;
const LAST_USED_GRANULARITY: u64 = 60;
pub struct Tokens {
path: PathBuf,
/// Serialises read-modify-write of the file inside this process.
lock: std::sync::Mutex<()>,
}
struct StoreGuard<'a> {
_m: std::sync::MutexGuard<'a, ()>,
_f: std::fs::File,
}
pub fn valid_name(n: &str) -> bool {
let n = n.trim();
!n.is_empty()
&& n.chars().count() <= 64
&& n.chars()
.all(|c| c.is_ascii_alphanumeric() || " ._-".contains(c))
}
impl Tokens {
pub fn new(state_dir: &Path) -> Tokens {
Tokens {
path: state_dir.join("tokens.json"),
lock: std::sync::Mutex::new(()),
}
}
/// Exclusive access to `tokens.json` for one read-modify-write: a mutex inside this
/// process and an advisory lock on `tokens.lock` across processes (the CLI and the
/// server), released when the guard is dropped, also if the process dies.
fn guard(&self) -> Result<StoreGuard<'_>, String> {
let m = self
.lock
.lock()
.map_err(|_| "token store unavailable".to_owned())?;
let path = self.path.with_file_name("tokens.lock");
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
}
let f = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
f.lock()
.map_err(|e| format!("cannot lock {}: {e}", path.display()))?;
Ok(StoreGuard { _m: m, _f: f })
}
fn load(&self) -> Result<TokenFile, String> {
Ok(read_json(&self.path)?.unwrap_or_default())
}
fn save(&self, f: &TokenFile) -> Result<(), String> {
write_json(&self.path, f)
}
/// Create a token; returns the record and the value (shown once).
pub fn create(
&self,
name: &str,
expires_at: Option<u64>,
) -> Result<(TokenRecord, String), String> {
let _g = self.guard()?;
if !valid_name(name) {
return Err("token.name".into());
}
let mut f = self.load()?;
if f.tokens.iter().filter(|t| t.revoked_at.is_none()).count() >= MAX_TOKENS {
return Err("too many tokens; revoke some first".into());
}
let id = hex(&random::<8>().map_err(|e| e.to_string())?);
let secret = URL_SAFE_NO_PAD.encode(random::<32>().map_err(|e| e.to_string())?);
let value = format!("ian_{id}_{secret}");
let rec = TokenRecord {
id,
name: name.trim().to_owned(),
sha256: sha256_hex(value.as_bytes()),
created_at: now(),
expires_at,
last_used_at: None,
revoked_at: None,
};
f.tokens.push(rec.clone());
self.save(&f)?;
Ok((rec, value))
}
pub fn list(&self) -> Result<Vec<TokenRecord>, String> {
let _g = self.guard()?;
Ok(self.load()?.tokens)
}
pub fn revoke(&self, id: &str) -> Result<Option<TokenRecord>, String> {
let _g = self.guard()?;
let mut f = self.load()?;
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
return Ok(None);
};
if t.revoked_at.is_none() {
t.revoked_at = Some(now());
}
let r = t.clone();
self.save(&f)?;
Ok(Some(r))
}
pub fn rename(&self, id: &str, name: &str) -> Result<Option<TokenRecord>, String> {
let _g = self.guard()?;
if !valid_name(name) {
return Err("token.name".into());
}
let mut f = self.load()?;
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
return Ok(None);
};
t.name = name.trim().to_owned();
let r = t.clone();
self.save(&f)?;
Ok(Some(r))
}
/// Check a presented `Authorization` value. The token never appears in an error.
pub fn check(&self, header: Option<&str>) -> Result<TokenRecord, Refusal> {
let Some(h) = header else {
return Err(Refusal::Missing);
};
let Some(value) = h.strip_prefix("Bearer ").map(str::trim) else {
return Err(Refusal::Unknown);
};
let id = value
.strip_prefix("ian_")
.and_then(|r| r.split_once('_'))
.map(|(id, _)| id)
.filter(|id| id.len() == 16)
.ok_or(Refusal::Unknown)?;
let _g = self.guard().map_err(|_| Refusal::Unknown)?;
let mut f = self.load().map_err(|_| Refusal::Unknown)?;
let presented = sha256_hex(value.as_bytes());
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
return Err(Refusal::Unknown);
};
if !ct_eq(t.sha256.as_bytes(), presented.as_bytes()) {
return Err(Refusal::Unknown);
}
if let Some(r) = t.revoked_at {
return Err(Refusal::Revoked(r));
}
let n = now();
if let Some(e) = t.expires_at
&& n >= e
{
return Err(Refusal::Expired(e));
}
let rec = t.clone();
if t.last_used_at
.is_none_or(|l| n.saturating_sub(l) >= LAST_USED_GRANULARITY)
{
t.last_used_at = Some(n);
if let Err(e) = self.save(&f) {
log::warn!(target: "ianitor::tokens", "cannot record token use: {e}");
}
}
Ok(rec)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn create_check_revoke() {
let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id()));
let t = Tokens::new(&d);
let (rec, value) = t.create("laptop", None).unwrap();
assert!(value.starts_with("ian_"));
let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap();
assert!(!stored.contains(&value[21..]), "only the hash is stored");
assert_eq!(
t.check(Some(&format!("Bearer {value}"))).unwrap().id,
rec.id
);
assert_eq!(t.check(None).unwrap_err(), Refusal::Missing);
assert_eq!(t.check(Some(&value)).unwrap_err(), Refusal::Unknown);
let mut wrong = value.clone();
wrong.pop();
wrong.push('x');
assert_eq!(
t.check(Some(&format!("Bearer {wrong}"))).unwrap_err(),
Refusal::Unknown
);
t.revoke(&rec.id).unwrap();
assert!(matches!(
t.check(Some(&format!("Bearer {value}"))).unwrap_err(),
Refusal::Revoked(_)
));
let (_, v2) = t.create("old", Some(1)).unwrap();
assert_eq!(
t.check(Some(&format!("Bearer {v2}"))).unwrap_err(),
Refusal::Expired(1)
);
let _ = std::fs::remove_dir_all(&d);
}
}
+170
View File
@@ -0,0 +1,170 @@
// 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/.
//! Small shared helpers: time, randomness, hashing, atomic file writes.
use std::io::Write;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use ring::rand::{SecureRandom, SystemRandom};
use serde::Serialize;
use serde::de::DeserializeOwned;
pub fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
pub fn rfc3339(t: u64) -> String {
ianitor_core::time::rfc3339(t)
}
pub fn random<const N: usize>() -> Result<[u8; N], std::io::Error> {
let mut b = [0u8; N];
SystemRandom::new()
.fill(&mut b)
.map_err(|_| std::io::Error::other("the system random generator failed"))?;
Ok(b)
}
pub fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn sha256_hex(data: &[u8]) -> String {
hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
}
/// Compare two byte strings in time that depends only on their length.
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut d = 0u8;
for (x, y) in a.iter().zip(b) {
d |= x ^ y;
}
std::hint::black_box(d) == 0
}
/// Write `data` to `path` so that readers see the old or the new content, never a mix, and
/// the new content survives a crash once this returns: temporary file in the same directory,
/// fsync, rename, fsync of the directory.
pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()> {
crate::crash::fail_write(path).map_err(std::io::Error::other)?;
let dir = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
std::fs::create_dir_all(dir)?;
let mut name = path.file_name().unwrap_or_default().to_os_string();
// Unique per write (process, counter, random), so two writers of the same file never
// share a temporary file.
static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let r = random::<4>().map(|b| hex(&b))?;
name.push(format!(".tmp-{}-{n}-{r}", std::process::id()));
let tmp = dir.join(name);
{
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, mode);
#[cfg(not(unix))]
let _ = mode;
let mut f = opts.open(&tmp)?;
f.write_all(data)?;
f.sync_all()?;
}
std::fs::rename(&tmp, path)?;
sync_dir(dir)
}
/// Rename `from` to `to` atomically and durably.
pub fn rename_durable(from: &Path, to: &Path) -> std::io::Result<()> {
crate::crash::fail_write(to).map_err(std::io::Error::other)?;
std::fs::rename(from, to)?;
sync_dir(to.parent().unwrap_or(Path::new(".")))
}
pub fn sync_dir(dir: &Path) -> std::io::Result<()> {
#[cfg(unix)]
{
std::fs::File::open(dir)?.sync_all()?;
}
#[cfg(not(unix))]
let _ = dir;
Ok(())
}
pub fn remove_if_exists(path: &Path) -> std::io::Result<()> {
match std::fs::remove_file(path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
}
/// Read a JSON state file; `Ok(None)` when it does not exist.
pub fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, String> {
match std::fs::read(path) {
Ok(b) => serde_json::from_slice(&b)
.map(Some)
.map_err(|e| format!("{} is damaged: {e}", path.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(format!("cannot read {}: {e}", path.display())),
}
}
/// Write a JSON state file atomically, readable by its owner only.
pub fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
let mut text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
text.push(b'\n');
write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display()))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn constant_time_compare() {
assert!(ct_eq(b"abc", b"abc"));
assert!(!ct_eq(b"abc", b"abd"));
assert!(!ct_eq(b"abc", b"ab"));
}
#[test]
fn concurrent_atomic_writes_of_one_file_all_succeed() {
let d = std::env::temp_dir().join(format!("ianitor-util-c-{}", std::process::id()));
let p = d.join("paused.json");
let threads: Vec<_> = (0..16)
.map(|i| {
let p = p.clone();
std::thread::spawn(move || {
(0..50).all(|_| write_atomic(&p, format!("{i}").as_bytes(), 0o600).is_ok())
})
})
.collect();
for t in threads {
assert!(t.join().unwrap(), "a write failed");
}
let left: Vec<_> = std::fs::read_dir(&d).unwrap().collect();
assert_eq!(left.len(), 1, "no temporary files left");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn atomic_write_replaces() {
let d = std::env::temp_dir().join(format!("ianitor-util-{}", std::process::id()));
let p = d.join("f.json");
write_atomic(&p, b"one", 0o600).unwrap();
write_atomic(&p, b"two", 0o600).unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"two");
let _ = std::fs::remove_dir_all(&d);
}
}
+549
View File
@@ -0,0 +1,549 @@
// 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 API's edges (ROADMAP §6 phase 2, tests first): requests without a valid token are
//! rejected on every route and tokens never reach a log, an error or a state file; request
//! bodies are hostile input; the routes repository holds only host files; control only
//! listens on loopback; the OpenAPI document covers the API.
#![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 (edge admin socket); run it in WSL2",
file!()
);
}
#[cfg(unix)]
mod unix {
use std::time::Duration;
use crate::common::{Env, EnvSpec, host};
use ianitor_testkit::more::tcp_raw;
use ianitor_testkit::upstream::Echo;
use serde_json::{Value, json};
/// Every (method, path) in the OpenAPI document, with path parameters filled in.
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
.replace("{hostname}", "a.test")
.replace("{id}", "x")
.replace("{change_id}", "x");
out.push((method.to_uppercase(), p));
}
}
}
out
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn requests_without_a_valid_token_are_rejected_and_tokens_are_never_logged() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
let doc = env.call("GET", "/api/v1/openapi.json", None).await;
assert_eq!(doc.status, 200, "{}", doc.text);
let routes = routes(&doc.json);
assert!(routes.len() >= 25, "{routes:?}");
// Make a second token through the API and revoke it, to test a revoked one too.
let made = env
.call("POST", "/api/v1/tokens", Some(json!({ "name": "script" })))
.await;
assert_eq!(made.status, 201, "{}", made.text);
let revoked = made.json["token"].as_str().unwrap().to_owned();
let rid = made.json["id"].as_str().unwrap().to_owned();
assert_eq!(
env.call("DELETE", &format!("/api/v1/tokens/{rid}"), None)
.await
.status,
204
);
// A listing never shows values or hashes.
let list = env.call("GET", "/api/v1/tokens", None).await;
assert!(
!list.text.contains(&revoked) && !list.text.contains("sha256"),
"{}",
list.text
);
assert!(!list.text.contains(&env.token));
let mut wrong = env.token.clone();
wrong.pop();
wrong.push(if env.token.ends_with('A') { 'B' } else { 'A' });
type Case = (String, Vec<(String, String)>, &'static str);
let cases: Vec<Case> = vec![
("no header".into(), vec![], "token.missing"),
(
"not bearer".into(),
vec![("Authorization".into(), env.token.clone())],
"token.unknown",
),
(
"basic".into(),
vec![("Authorization".into(), "Basic YWRtaW46YWRtaW4=".into())],
"token.unknown",
),
(
"one char off".into(),
vec![("Authorization".into(), format!("Bearer {wrong}"))],
"token.unknown",
),
(
"made up".into(),
vec![(
"Authorization".into(),
"Bearer ian_0000000000000000_xxxxxxxx".into(),
)],
"token.unknown",
),
(
"revoked".into(),
vec![("Authorization".into(), format!("Bearer {revoked}"))],
"token.revoked",
),
(
"empty bearer".into(),
vec![("Authorization".into(), "Bearer ".into())],
"token.unknown",
),
// 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()),
],
"ui.no_proof",
),
];
for (what, headers, code) in &cases {
let hs: Vec<(&str, &str)> = headers
.iter()
.map(|(a, b)| (a.as_str(), b.as_str()))
.collect();
for (method, path) in &routes {
let body = (method != "GET" && method != "DELETE").then(|| json!({}));
let r = env.call_with(method, path, &hs, body).await;
assert_eq!(r.status, 401, "{what}: {method} {path}: {}", r.text);
assert_eq!(r.json["error"]["code"], *code, "{what}: {method} {path}");
assert!(r.json["error"]["message"].as_str().unwrap().len() > 10);
assert!(r.json["request_id"].is_string() && r.json["server_time"].is_string());
}
}
// Unknown paths are refused the same way, before anything else.
assert_eq!(
env.call_with("GET", "/api/v1/nope", &[], 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);
let raw = format!(
"GET /api/v1/overview HTTP/1.1\r\nHost: evil.example\r\nAuthorization: {auth}\r\nConnection: close\r\n\r\n"
);
let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap();
assert_eq!(r.status, 403, "{}", r.text());
// A browser write without the UI header is refused (CSRF).
let r = env
.call_with(
"POST",
"/api/v1/hosts",
&[("Authorization", &auth), ("Origin", "https://evil.example")],
Some(json!({ "host": host("a.test", &good.url(), false) })),
)
.await;
assert_eq!(r.status, 403, "{}", r.text);
assert_eq!(r.json["error"]["code"], "request.csrf");
let r = env
.call_with(
"POST",
"/api/v1/hosts",
&[
("Authorization", &auth),
("Origin", "http://127.0.0.1"),
("X-Ianitor-UI", "1"),
],
Some(json!({ "host": host("a.test", &good.url(), false) })),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
env.wait_apply(r.json["apply"]["id"].as_str().unwrap())
.await;
// Exercise the rest with the good token, then look for any token anywhere.
for (method, path) in &routes {
if method == "GET" {
env.call(method, path, None).await;
}
}
tokio::time::sleep(Duration::from_millis(300)).await;
env.kill_control();
let mut everything = env.control_log();
for f in [
"applies.json",
"push.json",
"share-links.json",
"journal.json",
] {
everything.push_str(&env.file(&format!("state/{f}")));
}
everything.push_str(&env.file("edge/edge.json"));
everything.push_str(&env.git(&["log", "-p", "--all"]));
// `ian_<16 hex>_<secret>`; the secret itself may contain '_'.
let secret_part = |t: &str| {
assert!(t.starts_with("ian_") && t.as_bytes()[20] == b'_');
t[21..].to_owned()
};
for t in [&env.token, &revoked] {
assert!(
!everything.contains(secret_part(t).as_str()),
"a token leaked"
);
}
let stored = env.file("state/tokens.json");
for t in [&env.token, &revoked] {
assert!(
!stored.contains(secret_part(t).as_str()),
"tokens.json holds a value, not a hash"
);
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(env.dir.join("state/tokens.json"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o077, 0, "tokens.json is private");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn bodies_are_hostile_input() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
let auth = format!("Bearer {}", env.token);
// Unknown fields, at the top and inside the host.
let r = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("a.test", &good.url(), false), "colour": 1 })),
)
.await;
assert_eq!(r.status, 422, "{}", r.text);
assert_eq!(r.json["error"]["code"], "request.body_unknown_field");
assert_eq!(r.json["error"]["field"], "colour");
let mut h = host("a.test", &good.url(), false);
h["upstream"] = json!("typo");
let r = env
.call("POST", "/api/v1/hosts", Some(json!({ "host": h })))
.await;
assert_eq!(
r.json["error"]["code"], "request.body_unknown_field",
"{}",
r.text
);
// Wrong types never echo the value sent.
let r = env
.call(
"POST",
"/api/v1/tokens",
Some(json!({ "name": ["secret-ish-value"] })),
)
.await;
assert_eq!(r.status, 400, "{}", r.text);
assert!(!r.text.contains("secret-ish-value"), "{}", r.text);
// Nor do odd field names, path parameters or credentials in an upstream URL.
let r = env
.call("POST", "/api/v1/tokens", Some(json!({ "pass:hunter2": 1 })))
.await;
assert_eq!(r.status, 422, "{}", r.text);
assert!(!r.text.contains("hunter2"), "{}", r.text);
let r = env.call("GET", "/api/v1/hosts/x%3Chunter2%3E", None).await;
assert_eq!(r.status, 404, "{}", r.text);
assert!(!r.text.contains("hunter2"), "{}", r.text);
let mut leaky = host("a.test", "http://admin:hunter2@10.0.0.2:3000", false);
leaky["upstreams"] = json!(["http://admin:hunter2@10.0.0.2:3000", "ftp://u:hunter2@x"]);
let r = env
.call("POST", "/api/v1/hosts", Some(json!({ "host": leaky })))
.await;
assert_eq!(r.status, 422, "{}", r.text);
assert!(!r.text.contains("hunter2"), "{}", r.text);
// Not JSON, wrong content type, too large.
let raw = format!(
"POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: application/json\r\nContent-Length: 5\r\nConnection: close\r\n\r\n{{{{{{{{{{",
env.api
);
let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap();
assert_eq!(r.status, 400, "{}", r.text());
let raw = format!(
"POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}",
env.api
);
let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap();
assert_eq!(r.status, 415, "{}", r.text());
let big = "x".repeat(70 * 1024);
let r = env
.call("POST", "/api/v1/tokens", Some(json!({ "name": big })))
.await;
assert_eq!(r.status, 413, "{}", &r.text[..r.text.len().min(300)]);
// Field errors come back as one envelope with codes and field paths.
let mut bad = host("a.test", "ftp://x", true);
bad["health_check"]["interval_secs"] = json!(0);
let r = env
.call("POST", "/api/v1/hosts", Some(json!({ "host": bad })))
.await;
assert_eq!(r.status, 422, "{}", r.text);
let fields: Vec<&str> = r.json["errors"]
.as_array()
.unwrap()
.iter()
.filter_map(|e| e["field"].as_str())
.collect();
assert!(fields.contains(&"upstreams[0]"), "{fields:?}");
assert!(fields.contains(&"health_check.interval_secs"), "{fields:?}");
assert_eq!(r.json["error"]["code"], "apply.failed.validation");
let codes: Vec<&str> = r.json["errors"]
.as_array()
.unwrap()
.iter()
.filter_map(|e| e["code"].as_str())
.collect();
assert!(codes.contains(&"host.upstream.scheme"), "{codes:?}");
let msg = r.json["errors"][0]["message"].as_str().unwrap();
assert!(
!msg.contains("TOML") && !msg.contains("hosts/"),
"plain English: {msg}"
);
// Validate without applying.
let r = env
.call(
"POST",
"/api/v1/hosts/validate?mode=create",
Some(host("a.test", &good.url(), false)),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
// A hostname that does not match the path, a host that does not exist.
let r = env
.call(
"PUT",
"/api/v1/hosts/b.test",
Some(json!({ "host": host("a.test", &good.url(), false) })),
)
.await;
assert_eq!(
r.json["error"]["code"], "host.hostname.mismatch",
"{}",
r.text
);
let r = env.call("DELETE", "/api/v1/hosts/nope.test", None).await;
assert_eq!(r.status, 404);
let r = env.call("GET", "/api/v1/hosts/..%2f..%2fetc", None).await;
assert_eq!(r.status, 404);
// base_rev must be a commit of the history.
let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "0".repeat(40) }))).await;
assert_eq!(r.json["error"]["code"], "request.base_rev", "{}", r.text);
let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "--upload-pack=touch /tmp/x" }))).await;
assert_eq!(r.status, 422, "{}", r.text);
// Idempotency-Key: a retry returns the same apply; another body with it is refused.
let body = json!({ "host": host("a.test", &good.url(), false) });
let k = [
("Authorization", auth.as_str()),
("Idempotency-Key", "click-1"),
];
let first = env
.call_with("POST", "/api/v1/hosts", &k, Some(body.clone()))
.await;
assert_eq!(first.status, 202, "{}", first.text);
let again = env.call_with("POST", "/api/v1/hosts", &k, Some(body)).await;
assert_eq!(again.status, 202, "{}", again.text);
assert_eq!(again.json["apply"]["id"], first.json["apply"]["id"]);
let other = env
.call_with(
"POST",
"/api/v1/hosts",
&k,
Some(json!({ "host": host("b.test", &good.url(), false) })),
)
.await;
assert_eq!(other.status, 422);
assert_eq!(other.json["error"]["code"], "request.idempotency");
env.wait_apply(first.json["apply"]["id"].as_str().unwrap())
.await;
// Taken hostname.
let r = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("a.test", &good.url(), false) })),
)
.await;
assert_eq!(r.json["error"]["code"], "host.hostname.taken", "{}", r.text);
assert_eq!(r.json["error"]["field"], "hostname");
// The overview answers 304 to its own ETag.
let o = env.call("GET", "/api/v1/overview", None).await;
let etag = o.header("etag").unwrap().to_owned();
let r = env
.call_with(
"GET",
"/api/v1/overview",
&[("Authorization", &auth), ("If-None-Match", &etag)],
None,
)
.await;
assert_eq!(r.status, 304);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_routes_repository_holds_only_host_files() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
assert_eq!(
env.add_host(host("a.test", &good.url(), false)).await["state"],
"kept"
);
let good_edge = env.file("edge/edge.json");
env.kill_control();
// Someone pushes a stray file and a nested folder straight into the repository.
let work = env.dir.join("work");
let git = |args: &[&str], cwd: &std::path::Path| {
let o = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args(args)
.current_dir(cwd)
.output()
.unwrap();
assert!(
o.status.success(),
"{args:?} {}",
String::from_utf8_lossy(&o.stderr)
);
};
git(
&[
"clone",
"--quiet",
&env.repo().to_string_lossy(),
&work.to_string_lossy(),
],
&env.dir.join("."),
);
std::fs::create_dir_all(work.join("hosts/sub")).unwrap();
std::fs::write(work.join("README.md"), "hello").unwrap();
std::fs::write(
work.join("hosts/sub/b.test.toml"),
"hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
)
.unwrap();
git(&["add", "-A"], &work);
git(&["commit", "--quiet", "-m", "stray"], &work);
git(&["push", "--quiet", "origin", "HEAD:main"], &work);
env.start_control(None);
let o = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
let r = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("c.test", &good.url(), false) })),
)
.await;
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "control.paused");
// Edge keeps the last good config; nothing stray was compiled.
assert_eq!(env.file("edge/edge.json"), good_edge);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn control_only_listens_on_loopback() {
let env = Env::new(EnvSpec::default()).await;
let text = std::fs::read_to_string(env.config_path()).unwrap();
let open = text.replace(
&format!("listen = \"{}\"", env.api),
"listen = \"0.0.0.0:7979\"",
);
std::fs::write(env.config_path(), open).unwrap();
let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
.arg("--config")
.arg(env.config_path())
.output()
.unwrap();
assert!(!out.status.success());
assert!(
String::from_utf8_lossy(&out.stderr).contains("loopback"),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert!(std::net::TcpStream::connect("127.0.0.1:7979").is_err());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_overview_has_everything_the_main_screen_needs() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
env.add_host(host("a.test", &good.url(), true)).await;
tokio::time::sleep(Duration::from_secs(2)).await;
let o = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(o.status, 200, "{}", o.text);
for k in [
"counts",
"hosts",
"engine",
"last_apply",
"undo",
"repo",
"site",
"server_time",
"rev",
] {
assert!(o.json.get(k).is_some(), "{k} missing: {}", o.text);
}
assert_eq!(o.json["counts"]["hosts"], 1);
assert_eq!(o.json["counts"]["healthy"], 1, "{}", o.text);
let h = &o.json["hosts"][0];
assert_eq!(h["health"]["state"], "healthy");
assert!(h["health"]["latency_ms"].is_u64());
assert_eq!(h["certificate"]["state"], "ok");
assert_eq!(o.json["engine"]["running"], "pingora");
assert_eq!(o.json["engine"]["state"], "running");
assert_eq!(o.json["last_apply"]["state"], "kept");
assert_eq!(o.json["undo"]["available"], true);
assert!(o.json["intermediate"].is_null());
// The CLI lists tokens without values.
let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
.args(["token", "list", "--config"])
.arg(env.config_path())
.output()
.unwrap();
let text = String::from_utf8_lossy(&out.stdout);
assert!(text.contains("test") && !text.contains(&env.token[21..]));
}
}
File diff suppressed because it is too large Load Diff
+570
View File
@@ -0,0 +1,570 @@
// 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 control-plane test environment on 127.0.0.1: an edge running in this process (with its
//! admin socket), the real `ianitor-control` binary as a child process (so a test can kill it
//! or make it abort at a crash point), a bare routes repository, test upstreams and a test CA.
//! The first API token comes from `ianitor-control token create`, as in production.
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};
use ianitor_core::compile::{self, CompileOptions};
use ianitor_core::{SourceFile, load};
use ianitor_testkit::more::{JsonResp, tcp_json, unix_json};
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
use ianitor_testkit::tls::TestCa;
use rustls::RootCertStore;
use serde_json::{Value, json};
pub const HOSTS: [&str; 7] = [
"a.test",
"b.test",
"c.test",
"d.test",
"e.test",
"f.test",
"share.test",
];
pub const SHARE_KEY: &str = "control-test-share-key-0123456789abcdef0123456789";
pub struct Edge {
stop: Option<tokio::sync::oneshot::Sender<()>>,
pub http: SocketAddr,
pub https: SocketAddr,
pub admin: PathBuf,
}
impl Drop for Edge {
fn drop(&mut self) {
if let Some(s) = self.stop.take() {
let _ = s.send(());
}
}
}
pub struct Env {
pub dir: TempDir,
pub ca: TestCa,
pub edge: Option<Edge>,
pub control: Option<ChildGuard>,
pub api: SocketAddr,
pub token: String,
pub opts: CompileOptions,
pub watch_secs: u64,
pub remote: Option<String>,
log_n: u32,
}
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 {
fn default() -> Self {
EnvSpec {
watch_secs: 2,
site: String::new(),
remote: None,
extra_config: String::new(),
}
}
}
fn s(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
impl Env {
pub async fn new(spec: EnvSpec) -> Env {
let dir = TempDir::new("ctl");
for d in [
"state",
"edge",
"caddy",
"certs",
"creds",
"logs",
"edge-state",
] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
let ca = TestCa::new("Ianitor Control Test CA");
for h in HOSTS {
let leaf = ca.issue(&[h]);
std::fs::write(dir.join(&format!("certs/{h}.crt")), leaf.cert_pem).unwrap();
std::fs::write(dir.join(&format!("certs/{h}.key")), leaf.key_pem).unwrap();
}
std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap();
let opts = CompileOptions {
http_listen: local(free_port()),
https_listen: local(free_port()),
cert_dir: dir.str("certs"),
state_dir: dir.str("edge-state"),
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(
&SourceFile {
name: "ianitor.toml",
contents: "",
},
&[],
)
.unwrap();
std::fs::write(
dir.join("edge/edge.json"),
compile::edge(&empty, &opts).unwrap(),
)
.unwrap();
std::fs::write(
dir.join("edge/share-revocations.json"),
"{\"epoch\":0,\"deny\":[]}",
)
.unwrap();
let api = local(free_port());
let mut env = Env {
edge: None,
control: None,
api,
token: String::new(),
opts,
watch_secs: spec.watch_secs,
remote: spec.remote.clone(),
ca,
dir,
log_n: 0,
};
env.write_config(&spec);
env.start_edge();
// Seed the routes repository with the site file, then make the first token.
if !spec.site.is_empty() {
env.seed_site(&spec.site);
}
env.token = env.cli_token("test");
env
}
fn write_config(&self, spec: &EnvSpec) {
let d = |p: &str| s(&self.dir.join(p));
let remote = spec
.remote
.as_ref()
.map(|r| format!("remote = \"{r}\"\n"))
.unwrap_or_default();
let text = format!(
r#"listen = "{api}"
state_dir = "{state}"
credentials_dir = "{creds}"
watch_secs = {watch}
watch_every_secs = 1
trial_margin_secs = 2
health_poll_secs = 1
[routes]
repo = "{repo}"
{remote}
[edge]
config = "{edge}/edge.json"
admin_socket = "{edge}/admin.sock"
share_revocations = "{edge}/share-revocations.json"
[caddy]
config = "{caddy}/caddy.json"
[compile]
http_listen = "{http}"
https_listen = "{https}"
cert_dir = "{certs}"
state_dir = "{edge_state}"
access_log = "{log}"
caddy_credentials_dir = "{creds}"
"#,
api = self.api,
state = d("state"),
creds = d("creds"),
watch = spec.watch_secs,
repo = d("routes.git"),
edge = d("edge"),
caddy = d("caddy"),
http = self.opts.http_listen,
https = self.opts.https_listen,
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();
}
pub fn config_path(&self) -> PathBuf {
self.dir.join("control.toml")
}
pub fn repo(&self) -> PathBuf {
self.dir.join("routes.git")
}
pub fn start_edge(&mut self) {
let opts = ianitor_edge::Options {
config: self.dir.join("edge/edge.json"),
admin_socket: Some(self.dir.join("edge/admin.sock")),
share_revocations: Some(self.dir.join("edge/share-revocations.json")),
credentials_dir: Some(self.dir.join("creds")),
..Default::default()
};
let shared = ianitor_edge::prepare(&opts).expect("edge config");
let server = ianitor_edge::server(shared, &opts).expect("edge server");
let (tx, rx) = tokio::sync::oneshot::channel();
std::thread::spawn(move || ianitor_edge::run_until(server, rx));
assert!(wait_for_port(
self.opts.https_listen,
Duration::from_secs(20)
));
let deadline = Instant::now() + Duration::from_secs(5);
while !self.dir.join("edge/admin.sock").exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
self.edge = Some(Edge {
stop: Some(tx),
http: self.opts.http_listen,
https: self.opts.https_listen,
admin: self.dir.join("edge/admin.sock"),
});
}
/// Stop the in-process edge (and wait until its listeners are gone).
pub fn stop_edge(&mut self) {
self.edge = None;
let deadline = Instant::now() + Duration::from_secs(15);
while std::net::TcpStream::connect(self.opts.https_listen).is_ok()
&& Instant::now() < deadline
{
std::thread::sleep(Duration::from_millis(50));
}
std::thread::sleep(Duration::from_millis(200));
}
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");
c
}
pub fn cli_token(&self, name: &str) -> String {
let out = self
.command()
.args(["token", "create", "--name", name, "--config"])
.arg(self.config_path())
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let t = String::from_utf8_lossy(&out.stdout).trim().to_owned();
assert!(t.starts_with("ian_"), "{t}");
t
}
/// Put an `ianitor.toml` into a fresh repository (before control first starts).
fn seed_site(&self, site: &str) {
let work = self.dir.join("seed");
std::fs::create_dir_all(&work).unwrap();
let git = |args: &[&str], cwd: &Path| {
let o = Command::new("git")
.args([
"-c",
"user.name=test",
"-c",
"user.email=t@t",
"-c",
"init.defaultBranch=main",
])
.args(args)
.current_dir(cwd)
.output()
.unwrap();
assert!(
o.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&o.stderr)
);
};
git(
&["init", "--bare", "--quiet", &s(&self.repo())],
&self.dir.join("."),
);
git(&["init", "--quiet"], &work);
std::fs::write(work.join("ianitor.toml"), site).unwrap();
git(&["add", "ianitor.toml"], &work);
git(&["commit", "--quiet", "-m", "Site settings"], &work);
git(
&["push", "--quiet", &s(&self.repo()), "HEAD:refs/heads/main"],
&work,
);
let _ = std::fs::remove_dir_all(&work);
}
pub fn control_log(&self) -> String {
let mut out = String::new();
for i in 0..=self.log_n {
out.push_str(
&std::fs::read_to_string(self.dir.join(&format!("logs/control-{i}.log")))
.unwrap_or_default(),
);
}
out
}
/// Start the control binary; with `crash_at`, it aborts when an apply reaches that stage.
pub fn start_control(&mut self, crash_at: Option<&str>) {
self.start_control_env(crash_at, &[]);
}
/// Like [`Env::start_control`], with extra environment (fault injection).
pub fn start_control_env(&mut self, crash_at: Option<&str>, envs: &[(&str, &str)]) {
self.log_n += 1;
let log = std::fs::File::create(self.dir.join(&format!("logs/control-{}.log", self.log_n)))
.unwrap();
let mut c = self.command();
c.arg("--config").arg(self.config_path());
c.env("IANITOR_LOG", "debug");
if let Some(stage) = crash_at {
c.env("IANITOR_TEST_CRASH_AT", stage);
}
for (k, v) in envs {
c.env(k, v);
}
c.stdout(Stdio::from(log.try_clone().unwrap()))
.stderr(Stdio::from(log));
self.control = Some(ChildGuard(c.spawn().unwrap()));
if !wait_for_port(self.api, Duration::from_secs(30)) {
panic!("control did not start:\n{}", self.control_log());
}
}
pub fn kill_control(&mut self) {
self.control = None;
let deadline = Instant::now() + Duration::from_secs(10);
while std::net::TcpStream::connect(self.api).is_ok() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(50));
}
}
/// Wait for control to exit by itself (a crash point).
pub fn wait_control_exit(&mut self, timeout: Duration) -> Option<std::process::ExitStatus> {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if let Some(c) = &mut self.control
&& let Some(st) = c.0.try_wait().unwrap()
{
self.control = None;
return Some(st);
}
std::thread::sleep(Duration::from_millis(50));
}
None
}
pub async fn call(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
let auth = format!("Bearer {}", self.token);
self.call_with(method, path, &[("Authorization", &auth)], body)
.await
}
pub async fn call_with(
&self,
method: &str,
path: &str,
headers: &[(&str, &str)],
body: Option<Value>,
) -> JsonResp {
tcp_json(self.api, method, path, headers, body.as_ref())
.await
.unwrap_or_else(|e| panic!("{method} {path}: {e}\n{}", self.control_log()))
}
/// Wait for an apply to end; returns its record.
pub async fn wait_apply(&self, id: &str) -> Value {
let deadline = Instant::now() + Duration::from_secs(90);
loop {
let r = self
.call("GET", &format!("/api/v1/applies/{id}"), None)
.await;
assert_eq!(r.status, 200, "{}", r.text);
let st = r.json["state"].as_str().unwrap_or("").to_owned();
if ["kept", "reverted", "failed", "needs_attention"].contains(&st.as_str()) {
return r.json;
}
if Instant::now() > deadline {
panic!("apply {id} still {st}:\n{}", self.control_log());
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
/// Submit and wait.
pub async fn apply(&self, method: &str, path: &str, body: Option<Value>) -> Value {
let r = self.call(method, path, body).await;
assert_eq!(r.status, 202, "{method} {path}: {}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
self.wait_apply(&id).await
}
pub async fn add_host(&self, host: Value) -> Value {
self.apply("POST", "/api/v1/hosts", Some(json!({ "host": host })))
.await
}
pub async fn edge_status(&self) -> Value {
let r = unix_json(&self.dir.join("edge/admin.sock"), "GET", "/v1/status", None)
.await
.unwrap();
r.json
}
pub fn roots(&self) -> Arc<RootCertStore> {
self.ca.roots()
}
pub fn git(&self, args: &[&str]) -> String {
let o = Command::new("git")
.env("GIT_DIR", self.repo())
.args(args)
.output()
.unwrap();
assert!(
o.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&o.stderr)
);
String::from_utf8_lossy(&o.stdout).trim().to_owned()
}
pub fn head(&self) -> String {
self.git(&["rev-parse", "refs/heads/main"])
}
/// The routes files at the branch head.
pub fn head_files(&self) -> Vec<(String, String)> {
let list = self.git(&["ls-tree", "-r", "--name-only", "refs/heads/main"]);
list.lines()
.map(|p| {
(
p.to_owned(),
self.git(&["show", &format!("refs/heads/main:{p}")]) + "\n",
)
})
.collect()
}
/// What edge.json and caddy.json must hold for the branch head.
pub fn expected_configs(&self) -> (String, String) {
let files = self.head_files();
let site = files
.iter()
.find(|(p, _)| p == "ianitor.toml")
.map(|(_, c)| c.clone())
.unwrap_or_default();
let hosts: Vec<SourceFile> = files
.iter()
.filter(|(p, _)| p != "ianitor.toml")
.map(|(p, c)| SourceFile {
name: p,
contents: c,
})
.collect();
let model = load(
&SourceFile {
name: "ianitor.toml",
contents: &site,
},
&hosts,
)
.expect("head validates");
(
compile::edge(&model, &self.opts).unwrap(),
compile::caddy(&model, &self.opts).unwrap(),
)
}
pub fn file(&self, p: &str) -> String {
std::fs::read_to_string(self.dir.join(p)).unwrap_or_default()
}
/// The repository, both files and edge agree, and nothing is left half done.
pub async fn assert_consistent(&self) {
let (edge_text, caddy_text) = self.expected_configs();
assert_eq!(
self.file("edge/edge.json"),
edge_text,
"edge.json matches the branch head"
);
assert_eq!(
self.file("caddy/caddy.json"),
caddy_text,
"caddy.json matches the branch head"
);
let st = self.edge_status().await;
assert!(st["trial"].is_null(), "no trial left running: {st}");
assert_eq!(
st["config_sha256"],
sha256(&edge_text),
"edge runs edge.json"
);
assert!(
!self.dir.join("edge/edge.json.trial").exists(),
"no trial file left"
);
assert!(
!self.dir.join("caddy/caddy.json.trial").exists(),
"no Caddy trial file left"
);
assert!(
!self.dir.join("state/journal.json").exists(),
"no journal left"
);
}
}
pub fn sha256(text: &str) -> String {
ring::digest::digest(&ring::digest::SHA256, text.as_bytes())
.as_ref()
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
/// A host body for the API.
pub fn host(name: &str, upstream: &str, health: bool) -> Value {
let mut h = json!({
"hostname": name,
"upstreams": [upstream],
"tls": "domi",
"auth": "none",
"websockets": true,
"share_links": false,
"access_log": "off",
});
if health {
h["health_check"] = json!({ "path": "/healthz", "interval_secs": 1 });
}
h
}
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);
}
}
+198
View File
@@ -0,0 +1,198 @@
// 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/.
//! Token and share-link stores (QC fix round 1, M2 and M4): a CLI revoke is never lost to the
//! server recording token use at the same time, and losing `share-links.json` never revives a
//! stopped link.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use ianitor_control::shares::Shares;
use ianitor_control::tokens::{Refusal, Tokens};
use ianitor_core::share::ShareKey;
use ianitor_testkit::proc::TempDir;
use serde_json::Value;
fn revocations(p: &std::path::Path) -> Value {
serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap()
}
#[test]
fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() {
let bin = env!("CARGO_BIN_EXE_ianitor-control");
let rounds = 20;
let mut lost = 0;
for _ in 0..rounds {
let d = TempDir::new("tok-race");
let server = Tokens::new(d.path());
let values: Vec<_> = (0..150)
.map(|i| server.create(&format!("t{i}"), None).unwrap())
.collect();
let victim = values[75].0.id.clone();
let mut cli = std::process::Command::new(bin)
.args(["token", "revoke", &victim, "--state-dir"])
.arg(d.path())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
for (_, v) in &values {
let _ = server.check(Some(&format!("Bearer {v}")));
}
assert!(cli.wait().unwrap().success());
if !matches!(
server.check(Some(&format!("Bearer {}", values[75].1))),
Err(Refusal::Revoked(_))
) {
lost += 1;
}
}
assert_eq!(
lost, 0,
"the CLI said revoked but the token still worked in {lost}/{rounds} rounds"
);
}
#[test]
fn concurrent_creates_from_the_cli_and_the_server_all_survive() {
let bin = env!("CARGO_BIN_EXE_ianitor-control");
let d = TempDir::new("tok-create");
let server = Tokens::new(d.path());
let mut clis: Vec<_> = (0..8)
.map(|i| {
std::process::Command::new(bin)
.args([
"token",
"create",
"--name",
&format!("cli{i}"),
"--state-dir",
])
.arg(d.path())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap()
})
.collect();
for i in 0..40 {
server.create(&format!("srv{i}"), None).unwrap();
}
for c in &mut clis {
assert!(c.wait().unwrap().success());
}
assert_eq!(server.list().unwrap().len(), 48);
}
#[test]
fn losing_share_links_json_never_lowers_the_revocation_epoch() {
let d = TempDir::new("epoch");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let key = ShareKey::new(&[9u8; 32]).unwrap();
let m = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
s.stop(&m.record.id).unwrap();
s.stop_all().unwrap();
s.stop_all().unwrap();
assert_eq!(revocations(&rev)["epoch"], 2);
std::fs::remove_file(d.join("share-links.json")).unwrap();
Shares::new(d.path(), &rev)
.ensure_revocation_file()
.unwrap();
assert!(
revocations(&rev)["epoch"].as_u64().unwrap() >= 2,
"{}",
revocations(&rev)
);
// Minting after the loss continues from there.
let m2 = Shares::new(d.path(), &rev)
.mint(&key, "a.test", "/", 3600, None, None, "t")
.unwrap();
assert!(m2.record.epoch >= 2);
}
#[test]
fn a_lost_deny_list_raises_the_epoch_instead_of_shrinking() {
let d = TempDir::new("deny");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let key = ShareKey::new(&[9u8; 32]).unwrap();
let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
let _b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
s.stop(&a.record.id).unwrap();
let before = revocations(&rev);
assert_eq!(before["deny"][0], a.record.id);
assert_eq!(before["epoch"], 0);
// The records are gone (or an older backup without the stop is restored).
std::fs::remove_file(d.join("share-links.json")).unwrap();
Shares::new(d.path(), &rev)
.ensure_revocation_file()
.unwrap();
let after = revocations(&rev);
let still_denied = after["deny"]
.as_array()
.unwrap()
.iter()
.any(|x| x == &before["deny"][0]);
assert!(
still_denied || after["epoch"].as_u64().unwrap() > 0,
"stopped link {} works again: {after}",
a.record.id
);
}
#[test]
fn a_deny_list_that_would_overflow_raises_the_epoch() {
let d = TempDir::new("overflow");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let t = ianitor_control::util::now();
let links: Vec<Value> = (0..10_050u32)
.map(|i| {
serde_json::json!({
"id": format!("{:032x}", i + 1), "hostname": "a.test", "path_prefix": "/", "epoch": 0,
"created_at": t, "expires_at": t + 3600, "has_password": false, "created_by": "t",
"stopped_at": t
})
})
.collect();
std::fs::write(
d.join("share-links.json"),
serde_json::json!({ "epoch": 0, "links": links }).to_string(),
)
.unwrap();
s.ensure_revocation_file().unwrap();
let r = revocations(&rev);
assert!(
r["epoch"].as_u64().unwrap() >= 1,
"an overflowing deny list must raise the epoch: {}",
r["epoch"]
);
assert!(r["deny"].as_array().unwrap().len() < 10_000);
}
#[test]
fn a_link_minted_after_the_records_were_lost_works() {
let d = TempDir::new("doa");
let rev = d.join("share-revocations.json");
let s = Shares::new(d.path(), &rev);
let key = ShareKey::new(&[9u8; 32]).unwrap();
let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
s.stop(&a.record.id).unwrap();
std::fs::remove_file(d.join("share-links.json")).unwrap();
let b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
let published = revocations(&rev);
assert!(
u64::from(b.record.epoch) >= published["epoch"].as_u64().unwrap(),
"dead on arrival: link epoch {} < published {}",
b.record.epoch,
published["epoch"]
);
let list = s.load().unwrap();
let rec = list.links.iter().find(|l| l.id == b.record.id).unwrap();
assert_eq!(
rec.state(list.epoch, ianitor_control::util::now()),
"active"
);
}
+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());
}
}
+10
View File
@@ -13,6 +13,16 @@ serde_json.workspace = true
toml.workspace = true toml.workspace = true
thiserror.workspace = true thiserror.workspace = true
url.workspace = true 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] [lints]
workspace = true workspace = true
+56 -9
View File
@@ -10,7 +10,7 @@
use serde_json::{Map, Value, json}; 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::{ use crate::{
AccessLog, AuthMode, ForwardAuth, HeaderRule, HeaderValue, Host, Model, Scheme, TlsMode, AccessLog, AuthMode, ForwardAuth, HeaderRule, HeaderValue, Host, Model, Scheme, TlsMode,
Upstream, Upstream,
@@ -26,9 +26,13 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
root.insert( root.insert(
"admin".into(), "admin".into(),
match o.caddy_admin { match (&o.caddy_admin_socket, o.caddy_admin) {
Some(addr) => json!({ "listen": addr.to_string() }), // Only the ianitor group (control) can reach it; no TCP port for local processes.
None => json!({ "disabled": true }), (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( root.insert(
@@ -52,13 +56,23 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
routes.push(not_found()); routes.push(not_found());
let domi: Vec<&Host> = hosts.iter().filter(|h| h.tls == TlsMode::Domi).collect(); 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() .iter()
.filter(|h| h.tls == TlsMode::Domi || h.device_certs)
.map(|h| { .map(|h| {
json!({ let mut p = Map::new();
"match": { "sni": [h.hostname.as_str()] }, p.insert("match".into(), json!({ "sni": [h.hostname.as_str()] }));
"certificate_selection": { "any_tag": [cert_tag(h)] } 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(); .collect();
policies.push(json!({})); policies.push(json!({}));
@@ -75,6 +89,18 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
}), }),
); );
https.insert("protocols".into(), json!(["h1", "h2"])); 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() { if !logged.is_empty() {
let names: Map<String, Value> = logged let names: Map<String, Value> = logged
.iter() .iter()
@@ -203,6 +229,14 @@ fn logging(file: &str) -> Value {
fn host_route(h: &Host, fa: Option<&ForwardAuth>, o: &CompileOptions) -> Value { fn host_route(h: &Host, fa: Option<&ForwardAuth>, o: &CompileOptions) -> Value {
let mut steps = Vec::new(); 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) { if let (AuthMode::ForwardAuth, Some(fa)) = (h.auth, fa) {
// Client-sent identity headers never reach the auth server or the upstream. // Client-sent identity headers never reach the auth server or the upstream.
steps.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": strip_headers(fa) } }] })); steps.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": strip_headers(fa) } }] }));
@@ -339,3 +373,16 @@ fn forward_auth(fa: &ForwardAuth) -> Value {
); );
Value::Object(rp) 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"
})
}
+14 -3
View File
@@ -4,10 +4,10 @@
//! Model → [`EdgeConfig`] for the Pingora data plane. //! 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::{ use crate::edge_config::{
EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeForwardAuth, EdgeHeaderOp, EdgeHealthCheck, EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeDeviceCerts, EdgeForwardAuth, EdgeHeaderOp,
EdgeHost, EdgeTls, EdgeUpstream, EdgeValue, EdgeHealthCheck, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
}; };
use crate::{AccessLog, AuthMode, HeaderRule, HeaderValue, Model, Scheme, TlsMode, Upstream}; 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(), directory: site.acme.directory.clone(),
email: site.acme.email.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 { forward_auth: site.forward_auth.as_ref().map(|fa| EdgeForwardAuth {
upstream: upstream(&fa.upstream), upstream: upstream(&fa.upstream),
path_and_query: fa.path_and_query.clone(), path_and_query: fa.path_and_query.clone(),
@@ -54,6 +63,8 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
interval_secs: hc.interval_secs, interval_secs: hc.interval_secs,
}), }),
access_log: h.access_log == AccessLog::Truncated, access_log: h.access_log == AccessLog::Truncated,
share_links: h.share_links,
device_certs: h.device_certs,
}) })
.collect(), .collect(),
} }
+18
View File
@@ -17,6 +17,11 @@
mod caddy; mod caddy;
mod edge; 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 std::net::SocketAddr;
use crate::Model; use crate::Model;
@@ -36,6 +41,13 @@ pub struct CompileOptions {
pub caddy_credentials_dir: String, pub caddy_credentials_dir: String,
/// Caddy admin endpoint; `None` disables the admin API. /// Caddy admin endpoint; `None` disables the admin API.
pub caddy_admin: Option<SocketAddr>, 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)] #[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> { 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 [ for (option, value) in [
("cert_dir", &o.cert_dir), ("cert_dir", &o.cert_dir),
("state_dir", &o.state_dir), ("state_dir", &o.state_dir),
+22 -1
View File
@@ -9,7 +9,7 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Bumped on any incompatible change; edge refuses other versions. /// Bumped on any incompatible change; edge refuses other versions.
pub const EDGE_CONFIG_VERSION: u32 = 1; pub const EDGE_CONFIG_VERSION: u32 = 3;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
@@ -29,6 +29,11 @@ pub struct EdgeConfig {
pub access_log: String, pub access_log: String,
pub acme: Option<EdgeAcme>, pub acme: Option<EdgeAcme>,
pub forward_auth: Option<EdgeForwardAuth>, 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. /// Sorted by hostname.
pub hosts: Vec<EdgeHost>, pub hosts: Vec<EdgeHost>,
} }
@@ -103,4 +108,20 @@ pub struct EdgeHost {
pub response_headers: Vec<EdgeHeaderOp>, pub response_headers: Vec<EdgeHeaderOp>,
pub health_check: Option<EdgeHealthCheck>, pub health_check: Option<EdgeHealthCheck>,
pub access_log: bool, pub access_log: bool,
/// 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,
} }
+321 -9
View File
@@ -2,11 +2,67 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this // 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/. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Typed validation errors. Every message names the file and says what is wrong in plain English, //! Typed validation errors. Every message names the file and says what is wrong in plain English.
//! so the UI can show it as is. //!
//! Each error also has a stable [`ValidationError::code`], the form field it is about
//! ([`ValidationError::field`], e.g. `upstreams[1]`) and the values the UI shows in bold
//! ([`ValidationError::params`]). The control API maps the code to the UI's copy
//! (docs/ui-api.md §3.1) and keeps the `Display` text below as the technical detail.
use std::collections::BTreeMap;
use std::fmt; use std::fmt;
/// The reasons carried in `&'static str` fields. [`ValidationError::code`] compares them by
/// value, so every reason is written once, here.
pub(crate) mod reason {
pub const HOST_EMPTY: &str = "it is empty";
pub const HOST_TOO_LONG: &str = "it is longer than 253 characters";
pub const HOST_IP: &str = "IP addresses are not hostnames";
pub const HOST_WILDCARD: &str = "wildcards are not supported";
pub const HOST_TRAILING_DOT: &str = "it must not end with a dot";
pub const HOST_UPPERCASE: &str = "it must be lowercase";
pub const HOST_SPACES: &str = "it must not contain spaces";
pub const HOST_EMPTY_LABEL: &str = "it has an empty label";
pub const HOST_LABEL_LONG: &str = "a label is longer than 63 characters";
pub const HOST_CHARACTERS: &str = "only a-z, 0-9, '-' and '.' are allowed";
pub const HOST_LABEL_DASH: &str = "a label must not start or end with '-'";
pub const HOST_NUMERIC: &str = "the last label must not be numeric";
pub const URL_ASCII: &str = "it must be plain ASCII without spaces";
pub const URL_NOT_URL: &str = "it is not a URL like http://127.0.0.1:8080";
pub const URL_SCHEME: &str = "only http:// and https:// are supported";
pub const URL_CREDENTIALS: &str = "credentials in the URL are not allowed";
pub const URL_FRAGMENT: &str = "a #fragment is not allowed";
pub const URL_NO_HOST: &str = "it has no host";
pub const URL_HOST_NAME: &str = "the host name is not valid";
pub const URL_NO_PORT: &str = "it has no port";
pub const URL_PORT_ZERO: &str = "port 0 is not usable";
pub const URL_PATH: &str = "a path is not allowed; requests keep their own path";
pub const URL_QUERY: &str = "a ?query is not allowed";
pub const URL_BRACES: &str = "'{' and '}' are not allowed";
pub const URL_MIXED: &str = "all upstreams of a host must use the same scheme";
pub const VALUE_EMPTY: &str = "an empty value is not allowed; use action = \"remove\"";
pub const VALUE_LONG: &str = "it is longer than 4096 characters";
pub const VALUE_ASCII: &str = "only visible ASCII characters and spaces are allowed";
pub const VALUE_BRACES: &str = "'{' and '}' are not allowed (they are placeholders in Caddy)";
pub const VALUE_EDGE_SPACE: &str = "it must not start or end with a space";
pub const RULE_REMOVE_VALUE: &str = "remove takes no value or secret";
pub const RULE_BOTH: &str = "give either value or secret, not both";
pub const RULE_NEITHER: &str = "set needs a value or a secret";
pub const HEALTH_PATH: &str =
"path must start with '/' and contain only visible ASCII without '{', '}' or '#'";
pub const HEALTH_INTERVAL: &str = "interval_secs must be between 1 and 3600";
pub const PATH_LAYOUT: &str =
"only ianitor.toml and hosts/<hostname>.toml belong in the routes repository";
pub const PATH_SUBDIR: &str = "folders inside hosts/ are not allowed";
pub const PATH_NAME: &str = "the file name must be a lowercase hostname followed by .toml";
pub const PATH_KIND: &str = "symbolic links, executables and submodules are not allowed";
}
/// One problem found in the route files. /// One problem found in the route files.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ValidationError { pub enum ValidationError {
@@ -26,8 +82,10 @@ pub enum ValidationError {
DuplicateFile { file: String }, DuplicateFile { file: String },
#[error("{file} is larger than {max} bytes")] #[error("{file} is larger than {max} bytes")]
FileTooLarge { file: String, max: usize }, FileTooLarge { file: String, max: usize },
#[error("{file} must be named after its hostname: {hostname}.toml")] #[error("{file} must be named after its hostname: hosts/{hostname}.toml")]
FileNameMismatch { file: String, hostname: String }, FileNameMismatch { file: String, hostname: String },
#[error("{file}: {reason}")]
UnexpectedFile { file: String, reason: &'static str },
#[error("{file}: at most {max} upstreams per host")] #[error("{file}: at most {max} upstreams per host")]
TooManyUpstreams { file: String, max: usize }, TooManyUpstreams { file: String, max: usize },
#[error("{file}: `{hostname}` is not a valid hostname: {reason}")] #[error("{file}: `{hostname}` is not a valid hostname: {reason}")]
@@ -49,41 +107,73 @@ pub enum ValidationError {
file: String, file: String,
url: String, url: String,
reason: &'static str, reason: &'static str,
/// Position in `upstreams`; `None` when the problem is about the list as a whole.
index: Option<usize>,
}, },
#[error("{file}: upstream `{url}` is listed twice")] #[error("{file}: upstream `{url}` is listed twice")]
DuplicateUpstream { file: String, url: String }, DuplicateUpstream {
file: String,
url: String,
index: usize,
},
#[error("{file}: secret `{secret}` is used but not declared in the site file")] #[error("{file}: secret `{secret}` is used but not declared in the site file")]
UndefinedSecret { file: String, secret: String }, UndefinedSecret {
file: String,
secret: String,
field: String,
},
#[error( #[error(
"{file}: response header `{header}` may not use a secret; secrets only go to upstreams" "{file}: response header `{header}` may not use a secret; secrets only go to upstreams"
)] )]
SecretInResponseHeader { file: String, header: String }, SecretInResponseHeader {
file: String,
header: String,
field: String,
},
#[error( #[error(
"{file}: `{name}` is not a valid secret name (use a-z, 0-9, '_' and '-', at most 64 characters)" "{file}: `{name}` is not a valid secret name (use a-z, 0-9, '_' and '-', at most 64 characters)"
)] )]
InvalidSecretName { file: String, name: String }, InvalidSecretName { file: String, name: String },
#[error("{file}: `{name}` is not a valid header name")] #[error("{file}: `{name}` is not a valid header name")]
InvalidHeaderName { file: String, name: String }, InvalidHeaderName {
file: String,
name: String,
field: String,
},
#[error("{file}: value for header `{header}` is not allowed: {reason}")] #[error("{file}: value for header `{header}` is not allowed: {reason}")]
InvalidHeaderValue { InvalidHeaderValue {
file: String, file: String,
header: String, header: String,
reason: &'static str, reason: &'static str,
field: String,
}, },
#[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")] #[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")]
ProtectedHeader { file: String, header: String }, ProtectedHeader {
file: String,
header: String,
field: String,
},
#[error("{file}: header `{header}` has more than one rule in the same list")] #[error("{file}: header `{header}` has more than one rule in the same list")]
DuplicateHeaderRule { file: String, header: String }, DuplicateHeaderRule {
file: String,
header: String,
field: String,
},
#[error("{file}: rule for header `{header}` is incomplete: {reason}")] #[error("{file}: rule for header `{header}` is incomplete: {reason}")]
BadHeaderRule { BadHeaderRule {
file: String, file: String,
header: String, header: String,
reason: &'static str, reason: &'static str,
field: String,
}, },
#[error("{file}: health check is not usable: {reason}")] #[error("{file}: health check is not usable: {reason}")]
BadHealthCheck { file: String, reason: &'static str }, BadHealthCheck { file: String, reason: &'static str },
#[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")] #[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")]
ForwardAuthNotConfigured { file: String }, 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}")] #[error("{file}: forward_auth is not usable: {reason}")]
BadForwardAuth { file: String, reason: &'static str }, BadForwardAuth { file: String, reason: &'static str },
#[error("{file}: acme is not usable: {reason}")] #[error("{file}: acme is not usable: {reason}")]
@@ -97,6 +187,223 @@ fn line_suffix(line: Option<usize>) -> String {
} }
} }
impl ValidationError {
/// The file the problem is in (for a duplicate hostname: the second file).
pub fn file(&self) -> &str {
use ValidationError as E;
match self {
E::Syntax { file, .. }
| E::UnknownField { file, .. }
| E::MissingField { file, .. }
| E::InvalidValue { file, .. }
| E::DuplicateFile { file }
| E::FileTooLarge { file, .. }
| E::FileNameMismatch { file, .. }
| E::UnexpectedFile { file, .. }
| E::TooManyUpstreams { file, .. }
| E::InvalidHostname { file, .. }
| E::NoUpstreams { file }
| E::BadUpstreamUrl { file, .. }
| E::DuplicateUpstream { file, .. }
| E::UndefinedSecret { file, .. }
| E::SecretInResponseHeader { file, .. }
| E::InvalidSecretName { file, .. }
| E::InvalidHeaderName { file, .. }
| E::InvalidHeaderValue { file, .. }
| E::ProtectedHeader { file, .. }
| E::DuplicateHeaderRule { file, .. }
| E::BadHeaderRule { file, .. }
| E::BadHealthCheck { file, .. }
| E::ForwardAuthNotConfigured { file }
| E::ProofWithoutSignIn { file }
| E::BadForwardAuth { file, .. }
| E::BadAcme { file, .. } => file,
E::DuplicateHostname { second, .. } => second,
}
}
/// True when the problem is in the site file (or a stray file), not in a host file.
pub fn in_site_file(&self) -> bool {
!self.file().starts_with("hosts/")
}
/// A stable code the UI switches on, e.g. `host.upstream.no_port` (docs/ui-api.md §3.1).
pub fn code(&self) -> &'static str {
use ValidationError as E;
use reason as r;
let site = self.in_site_file();
match self {
E::Syntax { .. } => "file.syntax",
E::UnknownField { .. } if site => "site.field.unknown",
E::UnknownField { .. } => "host.field.unknown",
E::MissingField { field, .. } if !site && field == "hostname" => {
"host.hostname.missing"
}
E::MissingField { field, .. } if !site && field == "upstreams" => {
"host.upstreams.missing"
}
E::MissingField { .. } => "file.field.missing",
E::InvalidValue { .. } => "file.field.invalid",
E::DuplicateFile { .. } => "repo.duplicate_file",
E::FileTooLarge { .. } => "file.too_large",
E::FileNameMismatch { .. } => "host.file_name",
E::UnexpectedFile { .. } => "repo.unexpected_file",
E::TooManyUpstreams { .. } => "host.upstream.too_many",
E::InvalidHostname { reason, .. } => match *reason {
x if x == r::HOST_EMPTY => "host.hostname.missing",
x if x == r::HOST_TOO_LONG => "host.hostname.too_long",
x if x == r::HOST_IP || x == r::HOST_NUMERIC => "host.hostname.numeric",
x if x == r::HOST_WILDCARD => "host.hostname.wildcard",
x if x == r::HOST_TRAILING_DOT => "host.hostname.trailing_dot",
x if x == r::HOST_UPPERCASE => "host.hostname.uppercase",
x if x == r::HOST_SPACES => "host.hostname.spaces",
x if x == r::HOST_EMPTY_LABEL => "host.hostname.empty_label",
x if x == r::HOST_LABEL_LONG => "host.hostname.label_long",
x if x == r::HOST_LABEL_DASH => "host.hostname.label_dash",
_ => "host.hostname.characters",
},
E::DuplicateHostname { .. } => "host.hostname.taken",
E::NoUpstreams { .. } => "host.upstreams.missing",
E::BadUpstreamUrl { reason, .. } => match *reason {
x if x == r::URL_SCHEME => "host.upstream.scheme",
x if x == r::URL_CREDENTIALS => "host.upstream.credentials",
x if x == r::URL_FRAGMENT => "host.upstream.fragment",
x if x == r::URL_NO_HOST => "host.upstream.no_host",
x if x == r::URL_HOST_NAME => "host.upstream.host_name",
x if x == r::URL_NO_PORT => "host.upstream.no_port",
x if x == r::URL_PORT_ZERO => "host.upstream.port_zero",
x if x == r::URL_PATH => "host.upstream.path",
x if x == r::URL_QUERY => "host.upstream.query",
x if x == r::URL_MIXED => "host.upstream.mixed_schemes",
_ => "host.upstream.not_url",
},
E::DuplicateUpstream { .. } => "host.upstream.duplicate",
E::UndefinedSecret { .. } => "host.header.secret_unknown",
E::SecretInResponseHeader { .. } => "host.header.secret_response",
E::InvalidSecretName { .. } => "site.secret.name",
E::InvalidHeaderName { .. } | E::ProtectedHeader { .. } if site => {
"site.forward_auth.header"
}
E::InvalidHeaderName { .. } => "host.header.name",
E::InvalidHeaderValue { reason, .. } if *reason == r::VALUE_EMPTY => {
"host.header.empty"
}
E::InvalidHeaderValue { .. } => "host.header.value",
E::ProtectedHeader { .. } => "host.header.protected",
E::DuplicateHeaderRule { .. } => "host.header.duplicate",
E::BadHeaderRule { reason, .. } => match *reason {
x if x == r::RULE_BOTH => "host.header.both",
x if x == r::RULE_REMOVE_VALUE => "host.header.remove_value",
_ => "host.header.empty",
},
E::BadHealthCheck { reason, .. } if *reason == r::HEALTH_INTERVAL => {
"host.health.interval"
}
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",
}
}
/// The form field the problem is about, as a path into the host body (`hostname`,
/// `upstreams[0]`, `request_headers[2].name`, `health_check.path`), or `None`.
pub fn field(&self) -> Option<String> {
use ValidationError as E;
if self.in_site_file() {
return None;
}
match self {
E::UnknownField { field, .. } | E::MissingField { field, .. } => Some(field.clone()),
E::FileNameMismatch { .. }
| E::InvalidHostname { .. }
| E::DuplicateHostname { .. } => Some("hostname".into()),
E::TooManyUpstreams { .. } | E::NoUpstreams { .. } => Some("upstreams".into()),
E::BadUpstreamUrl { index, .. } => Some(match index {
Some(i) => format!("upstreams[{i}]"),
None => "upstreams".into(),
}),
E::DuplicateUpstream { index, .. } => Some(format!("upstreams[{index}]")),
E::UndefinedSecret { field, .. }
| E::SecretInResponseHeader { field, .. }
| E::InvalidHeaderName { field, .. }
| E::InvalidHeaderValue { field, .. }
| E::ProtectedHeader { field, .. }
| E::DuplicateHeaderRule { field, .. }
| E::BadHeaderRule { field, .. } => Some(field.clone()),
E::BadHealthCheck { reason, .. } if *reason == reason::HEALTH_INTERVAL => {
Some("health_check.interval_secs".into())
}
E::BadHealthCheck { .. } => Some("health_check.path".into()),
E::ForwardAuthNotConfigured { .. } => Some("auth".into()),
E::ProofWithoutSignIn { .. } => Some("auth".into()),
_ => None,
}
}
/// The values a message shows: always `file`, plus `line`, `field`, `max`, `hostname`,
/// `suggestion`, `url`, `name` or `secret` where they apply.
pub fn params(&self) -> BTreeMap<&'static str, String> {
use ValidationError as E;
let mut p = BTreeMap::new();
p.insert("file", self.file().to_owned());
match self {
E::Syntax { line: Some(l), .. } => {
p.insert("line", l.to_string());
}
E::UnknownField { field, .. } | E::MissingField { field, .. } => {
p.insert("field", field.clone());
}
E::FileTooLarge { max, .. } | E::TooManyUpstreams { max, .. } => {
p.insert("max", max.to_string());
}
E::FileNameMismatch { hostname, .. } | E::DuplicateHostname { hostname, .. } => {
p.insert("hostname", hostname.clone());
}
E::InvalidHostname {
hostname, reason, ..
} => {
p.insert("hostname", hostname.clone());
if *reason == reason::HOST_UPPERCASE || *reason == reason::HOST_TRAILING_DOT {
p.insert(
"suggestion",
hostname.trim_end_matches('.').to_ascii_lowercase(),
);
}
}
E::BadUpstreamUrl { url, reason, .. } => {
p.insert("url", url.clone());
if [reason::URL_PATH, reason::URL_QUERY, reason::URL_FRAGMENT].contains(reason)
&& let Ok(u) = url::Url::parse(url)
&& let Some(host) = u.host_str()
{
let port = u.port().map(|p| format!(":{p}")).unwrap_or_default();
p.insert("suggestion", format!("{}://{host}{port}", u.scheme()));
}
}
E::DuplicateUpstream { url, .. } => {
p.insert("url", url.clone());
}
E::UndefinedSecret { secret, .. } => {
p.insert("secret", secret.clone());
}
E::InvalidSecretName { name, .. } | E::InvalidHeaderName { name, .. } => {
p.insert("name", name.clone());
}
E::SecretInResponseHeader { header, .. }
| E::InvalidHeaderValue { header, .. }
| E::ProtectedHeader { header, .. }
| E::DuplicateHeaderRule { header, .. }
| E::BadHeaderRule { header, .. } => {
p.insert("name", header.clone());
}
_ => {}
}
p
}
}
/// All problems found in one load, in a stable order (file by file, then hostname checks). /// All problems found in one load, in a stable order (file by file, then hostname checks).
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationErrors(pub(crate) Vec<ValidationError>); pub struct ValidationErrors(pub(crate) Vec<ValidationError>);
@@ -109,6 +416,11 @@ impl ValidationErrors {
pub fn into_errors(self) -> Vec<ValidationError> { pub fn into_errors(self) -> Vec<ValidationError> {
self.0 self.0
} }
/// Wrap errors found outside [`crate::load`] (e.g. by [`crate::routes::check_path`]).
pub fn from_errors(errors: Vec<ValidationError>) -> ValidationErrors {
ValidationErrors(errors)
}
} }
impl fmt::Display for ValidationErrors { impl fmt::Display for ValidationErrors {
+7 -2
View File
@@ -12,12 +12,17 @@ pub mod compile;
pub mod edge_config; pub mod edge_config;
mod error; mod error;
mod model; mod model;
pub mod pki;
pub mod routes;
pub mod share;
pub mod time;
mod validate; mod validate;
pub use error::{ValidationError, ValidationErrors}; pub use error::{ValidationError, ValidationErrors};
pub use model::{ pub use model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, Model, Scheme, HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES,
SecretName, Site, TlsMode, Upstream, UpstreamHost, MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream,
UpstreamHost,
}; };
pub use validate::{SourceFile, load}; pub use validate::{SourceFile, load};
+6
View File
@@ -171,6 +171,8 @@ pub struct Host {
pub health_check: Option<HealthCheck>, pub health_check: Option<HealthCheck>,
pub share_links: bool, pub share_links: bool,
pub access_log: AccessLog, 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`). /// 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. /// 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"; pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/directory";
/// Let's Encrypt staging 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
}
}
+105
View File
@@ -0,0 +1,105 @@
// 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 shape of the routes repository: exactly `ianitor.toml` and `hosts/<hostname>.toml`,
//! regular files only. Anything else (other names, folders inside `hosts/`, symbolic links,
//! submodules, executables) is refused, so the repository can never hold something the
//! compilers do not read.
use crate::error::{ValidationError, reason};
use crate::validate::check_hostname;
/// The site file at the root of the repository.
pub const SITE_FILE: &str = "ianitor.toml";
/// The folder holding one file per host.
pub const HOSTS_DIR: &str = "hosts";
/// Most host files one repository may hold.
pub const MAX_HOST_FILES: usize = 1000;
/// What a tree entry is, as git reports it (`git ls-tree` modes).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntryKind {
/// Mode 100644.
File,
/// Mode 100755.
Executable,
/// Mode 120000.
Symlink,
/// Mode 160000.
Submodule,
}
/// A path the repository may hold.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RoutePath {
Site,
Host { hostname: String },
}
/// The path of the file for `hostname`.
pub fn host_path(hostname: &str) -> String {
format!("{HOSTS_DIR}/{hostname}.toml")
}
/// Check one path of the repository tree (as listed recursively, `/`-separated).
pub fn check_path(path: &str, kind: EntryKind) -> Result<RoutePath, ValidationError> {
let bad = |reason| ValidationError::UnexpectedFile {
file: path.to_owned(),
reason,
};
if kind != EntryKind::File {
return Err(bad(reason::PATH_KIND));
}
if path == SITE_FILE {
return Ok(RoutePath::Site);
}
let Some(rest) = path.strip_prefix("hosts/") else {
return Err(bad(reason::PATH_LAYOUT));
};
if rest.contains(['/', '\\']) {
return Err(bad(reason::PATH_SUBDIR));
}
let Some(hostname) = rest.strip_suffix(".toml") else {
return Err(bad(reason::PATH_NAME));
};
if check_hostname(hostname).is_err() {
return Err(bad(reason::PATH_NAME));
}
Ok(RoutePath::Host {
hostname: hostname.to_owned(),
})
}
/// Check a whole tree listing. Returns every problem; at most [`MAX_HOST_FILES`] host files.
pub fn check_tree<'a>(
entries: impl IntoIterator<Item = (&'a str, EntryKind)>,
) -> Result<(), Vec<ValidationError>> {
let mut errors = Vec::new();
let mut hosts = 0usize;
let mut site = false;
for (path, kind) in entries {
match check_path(path, kind) {
Ok(RoutePath::Site) => site = true,
Ok(RoutePath::Host { .. }) => hosts += 1,
Err(e) => errors.push(e),
}
}
if !site {
errors.push(ValidationError::MissingField {
file: SITE_FILE.into(),
field: "(the file itself)".into(),
});
}
if hosts > MAX_HOST_FILES {
errors.push(ValidationError::UnexpectedFile {
file: HOSTS_DIR.into(),
reason: "more than 1000 host files",
});
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
+554
View File
@@ -0,0 +1,554 @@
// 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/.
//! Share links: stateless tokens minted by control and checked by edge.
//!
//! A link token is `ish1.` + base64url(payload ‖ mac):
//!
//! ```text
//! payload = version (1) ‖ id (16) ‖ epoch (u32 BE) ‖ expires_at (u64 BE, Unix s) ‖ flags (1) ‖ path prefix
//! mac = HMAC-SHA256(key, "ianitor share link v1" 0 host 0 payload [0 HMAC-SHA256(key, "ianitor share password v1" 0 id password)])
//! ```
//!
//! - The host is not in the token but in the MAC, so a token for one host fails on another.
//! - With a password (flag bit 0), the MAC can only be checked by someone who has both the key
//! and the password: the token carries no password hash, so holding a link does not allow
//! guessing its password offline. Edge rate-limits guesses.
//! - The session cookie edge sets after a successful check is `iss1.` + base64url(payload ‖
//! HMAC(key, "ianitor share session v1" 0 host 0 payload)): a different domain, so a link
//! token is never accepted as a cookie and a cookie never as a link (and a cookie for a
//! password link proves the password was given).
//! - Revocation: every token carries the epoch it was minted in; edge refuses tokens from an
//! older epoch ("stop all") and ids on the deny list ("stop this link").
//!
//! [`path_within`] decides whether a raw request path lies under a link's prefix. It refuses
//! anything an upstream might read differently from a plain byte comparison.
use std::collections::BTreeSet;
use std::fmt;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use ring::hmac;
/// Name of the credential (`$CREDENTIALS_DIRECTORY/<name>`) holding the share-link key, read by
/// both edge and control.
pub const KEY_CREDENTIAL: &str = "share-link-key";
/// Shortest key accepted, in bytes.
pub const MIN_KEY_LEN: usize = 32;
/// Query parameter carrying a link token. Edge only takes values that start with
/// [`LINK_PREFIX`]; anything else is left to the upstream.
pub const QUERY_PARAM: &str = "share";
/// Start of every link token.
pub const LINK_PREFIX: &str = "ish1.";
/// Start of every session cookie value.
pub const SESSION_PREFIX: &str = "iss1.";
/// Session cookie name (`__Secure-`: browsers only accept it with `Secure`).
pub const COOKIE_NAME: &str = "__Secure-ianitor-share";
/// Path the password form posts to, on hosts with share links.
pub const PASSWORD_PATH: &str = "/.well-known/ianitor/share";
/// Longest path prefix.
pub const MAX_PREFIX_LEN: usize = 256;
/// Password length limits, in characters.
pub const MIN_PASSWORD_CHARS: usize = 8;
pub const MAX_PASSWORD_CHARS: usize = 128;
const VERSION: u8 = 1;
const FLAG_PASSWORD: u8 = 1;
const FIXED_LEN: usize = 1 + 16 + 4 + 8 + 1;
const MAC_LEN: usize = 32;
/// Longest token or cookie accepted before decoding.
const MAX_ENCODED_LEN: usize = 1024;
/// A link id: 16 random bytes, written as 32 lowercase hex digits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ShareId(pub [u8; 16]);
impl ShareId {
pub fn to_hex(&self) -> String {
self.0.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn from_hex(s: &str) -> Option<ShareId> {
if s.len() != 32
|| !s
.bytes()
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
{
return None;
}
let mut out = [0u8; 16];
for (i, o) in out.iter_mut().enumerate() {
*o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?;
}
Some(ShareId(out))
}
}
impl fmt::Display for ShareId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
/// The HMAC key. Never printed.
pub struct ShareKey(hmac::Key);
impl fmt::Debug for ShareKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ShareKey(<redacted>)")
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ShareError {
#[error("the share-link key must be at least {MIN_KEY_LEN} bytes")]
KeyTooShort,
#[error("the path prefix is not usable: {0}")]
Prefix(&'static str),
#[error("the password must be {MIN_PASSWORD_CHARS} to {MAX_PASSWORD_CHARS} characters")]
Password,
}
impl ShareKey {
pub fn new(bytes: &[u8]) -> Result<ShareKey, ShareError> {
if bytes.len() < MIN_KEY_LEN {
return Err(ShareError::KeyTooShort);
}
Ok(ShareKey(hmac::Key::new(hmac::HMAC_SHA256, bytes)))
}
}
/// What a token says. For a token checked with [`verify_link`] or [`verify_session`], all of
/// it is proven by the MAC; from [`peek`], none of it is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Claims {
pub id: ShareId,
pub epoch: u32,
pub expires_at: u64,
pub password: bool,
pub prefix: String,
}
/// What to mint.
#[derive(Debug, Clone)]
pub struct LinkSpec<'a> {
pub id: ShareId,
pub epoch: u32,
pub expires_at: u64,
/// Already checked with [`check_prefix`].
pub prefix: &'a str,
pub password: Option<&'a str>,
}
/// Why a token was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rejection {
/// Not a token at all (bad encoding, wrong version, too long).
Malformed,
/// The MAC does not match: altered, minted for another host, made with another key, or
/// (for a password link) the wrong password.
Invalid,
/// The link needs a password and none was given.
PasswordRequired,
/// Proven genuine, but past its expiry.
Expired { expires_at: u64 },
/// Proven genuine, but stopped (deny list or an older epoch).
Revoked,
}
/// The revocation state edge checks against (from the deny-list file control writes).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Revocations {
/// Tokens minted in an older epoch are refused ("stop all").
pub epoch: u32,
/// Stopped links.
pub deny: BTreeSet<ShareId>,
}
impl Revocations {
pub fn is_revoked(&self, c: &Claims) -> bool {
c.epoch < self.epoch || self.deny.contains(&c.id)
}
}
fn payload(spec: &LinkSpec<'_>) -> Vec<u8> {
let mut p = Vec::with_capacity(FIXED_LEN + spec.prefix.len());
p.push(VERSION);
p.extend_from_slice(&spec.id.0);
p.extend_from_slice(&spec.epoch.to_be_bytes());
p.extend_from_slice(&spec.expires_at.to_be_bytes());
p.push(if spec.password.is_some() {
FLAG_PASSWORD
} else {
0
});
p.extend_from_slice(spec.prefix.as_bytes());
p
}
fn password_tag(key: &ShareKey, id: &ShareId, password: &str) -> hmac::Tag {
let mut ctx = hmac::Context::with_key(&key.0);
ctx.update(b"ianitor share password v1\0");
ctx.update(&id.0);
ctx.update(password.as_bytes());
ctx.sign()
}
fn link_message(
key: &ShareKey,
host: &str,
payload: &[u8],
id: &ShareId,
password: Option<&str>,
) -> Vec<u8> {
let mut m = Vec::with_capacity(64 + host.len() + payload.len());
m.extend_from_slice(b"ianitor share link v1\0");
m.extend_from_slice(host.as_bytes());
m.push(0);
m.extend_from_slice(payload);
if let Some(pw) = password {
m.push(0);
m.extend_from_slice(password_tag(key, id, pw).as_ref());
}
m
}
fn session_message(host: &str, payload: &[u8]) -> Vec<u8> {
let mut m = Vec::with_capacity(64 + host.len() + payload.len());
m.extend_from_slice(b"ianitor share session v1\0");
m.extend_from_slice(host.as_bytes());
m.push(0);
m.extend_from_slice(payload);
m
}
fn check_password(pw: &str) -> Result<(), ShareError> {
let n = pw.chars().count();
if (MIN_PASSWORD_CHARS..=MAX_PASSWORD_CHARS).contains(&n) {
Ok(())
} else {
Err(ShareError::Password)
}
}
/// Mint a link token for `host` (a validated hostname).
pub fn mint(key: &ShareKey, host: &str, spec: &LinkSpec<'_>) -> Result<String, ShareError> {
let prefix = check_prefix(spec.prefix).map_err(ShareError::Prefix)?;
if prefix != spec.prefix {
return Err(ShareError::Prefix("it is not in its normal form"));
}
if let Some(pw) = spec.password {
check_password(pw)?;
}
let p = payload(spec);
let tag = hmac::sign(
&key.0,
&link_message(key, host, &p, &spec.id, spec.password),
);
let mut raw = p;
raw.extend_from_slice(tag.as_ref());
Ok(format!("{LINK_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw)))
}
/// Split and decode without checking the MAC. Only for showing a password page.
fn decode(token: &str, prefix: &str) -> Result<(Claims, Vec<u8>, Vec<u8>), Rejection> {
if token.len() > MAX_ENCODED_LEN {
return Err(Rejection::Malformed);
}
let body = token.strip_prefix(prefix).ok_or(Rejection::Malformed)?;
let raw = URL_SAFE_NO_PAD
.decode(body)
.map_err(|_| Rejection::Malformed)?;
if raw.len() < FIXED_LEN + MAC_LEN + 1 {
return Err(Rejection::Malformed);
}
let (p, mac) = raw.split_at(raw.len() - MAC_LEN);
if p[0] != VERSION || p[FIXED_LEN - 1] & !FLAG_PASSWORD != 0 {
return Err(Rejection::Malformed);
}
let mut id = [0u8; 16];
id.copy_from_slice(&p[1..17]);
let mut e = [0u8; 4];
e.copy_from_slice(&p[17..21]);
let mut x = [0u8; 8];
x.copy_from_slice(&p[21..29]);
let prefix = std::str::from_utf8(&p[FIXED_LEN..]).map_err(|_| Rejection::Malformed)?;
// A token whose prefix is not in normal form was never minted.
if check_prefix(prefix).ok().as_deref() != Some(prefix) {
return Err(Rejection::Malformed);
}
Ok((
Claims {
id: ShareId(id),
epoch: u32::from_be_bytes(e),
expires_at: u64::from_be_bytes(x),
password: p[FIXED_LEN - 1] & FLAG_PASSWORD != 0,
prefix: prefix.to_owned(),
},
p.to_vec(),
mac.to_vec(),
))
}
/// What a link token claims, unchecked (for the password page: is a password needed, and
/// until when does it claim to work). Never grant anything on this alone.
pub fn peek(token: &str) -> Result<Claims, Rejection> {
decode(token, LINK_PREFIX).map(|(c, _, _)| c)
}
/// Check a link token for `host`. The order of checks fixes what a visitor learns: a password
/// is asked for before anything else is proven; expiry and revocation are reported only for
/// tokens proven genuine.
pub fn verify_link(
key: &ShareKey,
host: &str,
token: &str,
password: Option<&str>,
now: u64,
revocations: &Revocations,
) -> Result<Claims, Rejection> {
let (claims, p, mac) = decode(token, LINK_PREFIX)?;
let password = match (claims.password, password) {
(true, None) => return Err(Rejection::PasswordRequired),
(true, Some(pw)) => Some(pw),
(false, _) => None,
};
let msg = link_message(key, host, &p, &claims.id, password);
hmac::verify(&key.0, &msg, &mac).map_err(|_| Rejection::Invalid)?;
finish(claims, now, revocations)
}
fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result<Claims, Rejection> {
if now >= claims.expires_at {
return Err(Rejection::Expired {
expires_at: claims.expires_at,
});
}
if revocations.is_revoked(&claims) {
return Err(Rejection::Revoked);
}
Ok(claims)
}
/// The session cookie value for claims proven by [`verify_link`].
pub fn session_value(key: &ShareKey, host: &str, claims: &Claims) -> String {
let spec = LinkSpec {
id: claims.id,
epoch: claims.epoch,
expires_at: claims.expires_at,
prefix: &claims.prefix,
password: claims.password.then_some(""),
};
let p = payload(&spec);
let tag = hmac::sign(&key.0, &session_message(host, &p));
let mut raw = p;
raw.extend_from_slice(tag.as_ref());
format!("{SESSION_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw))
}
/// Check a session cookie value for `host`.
pub fn verify_session(
key: &ShareKey,
host: &str,
value: &str,
now: u64,
revocations: &Revocations,
) -> Result<Claims, Rejection> {
let (claims, p, mac) = decode(value, SESSION_PREFIX)?;
hmac::verify(&key.0, &session_message(host, &p), &mac).map_err(|_| Rejection::Invalid)?;
finish(claims, now, revocations)
}
/// Normalise and check a path prefix: starts with `/`, at most [`MAX_PREFIX_LEN`] bytes, only
/// unreserved characters and `!$&'()*+,=:@-._~`, no `%`, `;`, backslash, empty segment or dot
/// segment. A trailing `/` is dropped (except for `/` itself).
pub fn check_prefix(prefix: &str) -> Result<String, &'static str> {
if !prefix.starts_with('/') {
return Err("it must start with /");
}
if prefix.len() > MAX_PREFIX_LEN {
return Err("it is longer than 256 characters");
}
let ok = |c: u8| c.is_ascii_alphanumeric() || b"/!$&'()*+,=:@-._~".contains(&c);
if !prefix.bytes().all(ok) {
return Err("only letters, digits, / and -._~!$&'()*+,=:@ are allowed");
}
if prefix.contains("//") {
return Err("it has an empty segment (//)");
}
let trimmed = if prefix.len() > 1 {
prefix.strip_suffix('/').unwrap_or(prefix)
} else {
prefix
};
if trimmed == "/" {
return Ok("/".into());
}
for seg in trimmed[1..].split('/') {
if seg.is_empty() {
return Err("it has an empty segment (//)");
}
if seg.bytes().all(|c| c == b'.') {
return Err("it has a . or .. segment");
}
}
Ok(trimmed.to_owned())
}
/// Percent-encodings no plain path needs (lowercased before matching): `.`, `/`, `\`, `%`
/// itself (double encoding), NUL, and IIS `%u` escapes.
pub const REFUSED_ENCODINGS: &[&str] = &["%2e", "%2f", "%5c", "%25", "%00", "%u"];
/// ASCII characters a look-alike must not stand for after NFKC normalisation.
/// ASCII characters a non-ASCII character must not turn into under NFKC.
const STRUCTURAL: &[char] = &['/', '\\', ';', '?', '#', '%'];
/// Slash and backslash look-alikes NFKC leaves alone (some upstreams still treat them as
/// separators): division slash, fraction slash, big solidus, big reverse solidus, set minus,
/// reverse solidus operator, box-drawing diagonals.
const SLASH_LOOKALIKES: &[char] = &[
'\u{2215}', '\u{2044}', '\u{29F8}', '\u{29F9}', '\u{2216}', '\u{29F5}', '\u{2571}', '\u{2572}',
];
/// Unicode's Default_Ignorable_Code_Point (DerivedCoreProperties.txt, Unicode 15).
fn default_ignorable(c: char) -> bool {
matches!(
c as u32,
0x00AD
| 0x034F
| 0x061C
| 0x115F..=0x1160
| 0x17B4..=0x17B5
| 0x180B..=0x180F
| 0x200B..=0x200F
| 0x202A..=0x202E
| 0x2060..=0x206F
| 0x3164
| 0xFE00..=0xFE0F
| 0xFEFF
| 0xFFA0
| 0xFFF0..=0xFFF8
| 0x1BCA0..=0x1BCA3
| 0x1D173..=0x1D17A
| 0xE0000..=0xE0FFF
)
}
/// Decode `%xx` escapes once. `None` for a broken escape.
fn percent_decode(raw: &str) -> Option<Vec<u8>> {
let b = raw.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'%' {
let hex = raw.get(i + 1..i + 3)?;
// from_str_radix would also take "+f".
if !hex.bytes().all(|c| c.is_ascii_hexdigit()) {
return None;
}
out.push(u8::from_str_radix(hex, 16).ok()?);
i += 3;
} else {
out.push(b[i]);
i += 1;
}
}
Some(out)
}
/// Is `raw_path` (the request path exactly as sent, still percent-encoded) under `prefix`?
///
/// Refused outright, whatever the prefix:
/// - anything but visible ASCII, a backslash, an empty segment (`//`);
/// - the encodings in [`REFUSED_ENCODINGS`] and broken `%` escapes;
/// - escapes that do not decode to valid UTF-8 (this refuses every overlong form, such as
/// `%c0%ae`);
/// - any encoded character that NFKC normalisation turns into something containing `/`, `\`,
/// `;`, `?`, `#`, `%` or a control character (fullwidth and small forms), and the slash
/// look-alikes NFKC leaves alone ([`SLASH_LOOKALIKES`]);
/// - a segment that NFKC turns into only dots or nothing, after dropping default-ignorable
/// characters and combining marks and trimming whitespace (two-dot
/// leaders, ellipses, fullwidth dots, look-alike spaces); look-alike dots and spaces inside a
/// name with other characters (`Wait….pdf`, an ideographic space) are fine;
/// - a segment of only dots, also with `;params` (`..;x`, `..%3b`), and any segment that is
/// one or more dots followed by a percent-encoded byte (`..%20`, `..%3f`, `..%23`), since
/// some servers trim or decode that into a dot segment.
///
/// Other paths match on whole segments, case-sensitively: prefix `/a` covers `/a` and `/a/x`,
/// not `/ab` or `/A`.
pub fn path_within(prefix: &str, raw_path: &str) -> bool {
use unicode_normalization::UnicodeNormalization;
if !raw_path.starts_with('/')
|| !raw_path.bytes().all(|c| c.is_ascii_graphic())
|| raw_path.contains('\\')
{
return false;
}
let lower = raw_path.to_ascii_lowercase();
if REFUSED_ENCODINGS.iter().any(|bad| lower.contains(bad)) {
return false;
}
// An empty segment anywhere but at the end (a trailing slash) is `//`.
if raw_path.contains("//") {
return false;
}
let Some(decoded) = percent_decode(raw_path) else {
return false;
};
let Ok(decoded) = String::from_utf8(decoded) else {
return false;
};
let looks_structural = decoded.chars().filter(|c| !c.is_ascii()).any(|c| {
SLASH_LOOKALIKES.contains(&c)
|| std::iter::once(c)
.nfkc()
.any(|n| STRUCTURAL.contains(&n) || n.is_control())
});
if looks_structural {
return false;
}
// Dot segments as an upstream that normalises (NFKC) and trims whitespace would see them.
let segments: Vec<&str> = decoded[1..].split('/').collect();
for (i, seg) in segments.iter().enumerate() {
if seg.is_empty() && i + 1 == segments.len() {
continue; // trailing slash
}
if seg.is_ascii() {
continue; // the raw checks below cover ASCII segments
}
// Invisible characters (default-ignorable code points, combining marks) do not count:
// `\u{200B}..` is `..` to a server that drops them.
let n: String = seg.nfkc().collect();
let visible: String = n
.split(';')
.next()
.unwrap_or("")
.chars()
.filter(|c| {
!default_ignorable(*c) && !unicode_normalization::char::is_combining_mark(*c)
})
.collect();
if visible.trim().chars().all(|c| c == '.') {
return false;
}
}
for seg in lower[1..].split('/') {
// `..;x` is `..` to Tomcat and friends; `..%3b` is `..;` to servers that decode
// before splitting.
let seg = seg.replace("%3b", ";");
let name = seg.split(';').next().unwrap_or("");
let after_dots = name.trim_start_matches('.');
if name.starts_with('.') && (after_dots.is_empty() || after_dots.starts_with('%')) {
return false;
}
}
if prefix == "/" {
return true;
}
match raw_path.strip_prefix(prefix) {
Some(rest) => rest.is_empty() || rest.starts_with('/'),
None => false,
}
}
+73
View File
@@ -0,0 +1,73 @@
// 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/.
//! Unix seconds to calendar dates (UTC), for API timestamps and visitor pages. Pure: the
//! caller passes the time in.
/// Days since 1970-01-01 → (year, month 1–12, day 1–31). Howard Hinnant's `civil_from_days`.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
/// `2026-11-14T14:20:00Z`.
pub fn rfc3339(unix: u64) -> String {
let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2);
let (y, m, d) = civil_from_days(secs.div_euclid(86_400));
let s = secs.rem_euclid(86_400);
format!(
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
s / 3600,
(s / 60) % 60,
s % 60
)
}
const MONTHS: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
/// `14 November 2026` (UTC).
pub fn long_date(unix: u64) -> String {
let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2);
let (y, m, d) = civil_from_days(secs.div_euclid(86_400));
let month = MONTHS
.get(m.saturating_sub(1) as usize)
.copied()
.unwrap_or("?");
format!("{d} {month} {y}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_dates() {
assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z");
assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z");
assert_eq!(rfc3339(1_794_666_000), "2026-11-14T14:20:00Z");
assert_eq!(long_date(1_794_666_000), "14 November 2026");
assert_eq!(long_date(4_133_980_799), "31 December 2100");
}
}
+158 -54
View File
@@ -11,11 +11,11 @@ use std::net::IpAddr;
use serde::Deserialize; use serde::Deserialize;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use crate::error::{ValidationError as E, ValidationErrors}; use crate::error::{ValidationError as E, ValidationErrors, reason as r};
use crate::model::{ use crate::model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model, 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). /// One route file handed in by the caller (core does no I/O).
@@ -121,6 +121,8 @@ struct RawHost {
#[serde(default)] #[serde(default)]
share_links: bool, share_links: bool,
#[serde(default)] #[serde(default)]
device_certs: bool,
#[serde(default)]
access_log: RawAccessLog, access_log: RawAccessLog,
health_check: Option<RawHealthCheck>, health_check: Option<RawHealthCheck>,
#[serde(default)] #[serde(default)]
@@ -274,11 +276,13 @@ fn check_site(file: &str, raw: RawSite, errors: &mut Vec<E>) -> Option<Site> {
errors.push(E::InvalidHeaderName { errors.push(E::InvalidHeaderName {
file: file.to_owned(), file: file.to_owned(),
name: h.clone(), name: h.clone(),
field: "forward_auth.copy_headers".into(),
}); });
} else if is_protected(h) { } else if is_protected(h) {
errors.push(E::ProtectedHeader { errors.push(E::ProtectedHeader {
file: file.to_owned(), file: file.to_owned(),
header: h.clone(), header: h.clone(),
field: "forward_auth.copy_headers".into(),
}); });
} else if !seen.insert(h.to_ascii_lowercase()) { } else if !seen.insert(h.to_ascii_lowercase()) {
errors.push(bad("copy_headers lists a header twice")); errors.push(bad("copy_headers lists a header twice"));
@@ -375,9 +379,8 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
reason, reason,
}), }),
Ok(()) => { Ok(()) => {
// One TOML per host, named after it: `hosts/<hostname>.toml`. // One TOML per host, named after it: exactly `hosts/<hostname>.toml`.
let base = file.rsplit(['/', '\\']).next().unwrap_or(file); if file != format!("hosts/{}.toml", raw.hostname) {
if base != format!("{}.toml", raw.hostname) {
errors.push(E::FileNameMismatch { errors.push(E::FileNameMismatch {
file: f(), file: f(),
hostname: raw.hostname.clone(), hostname: raw.hostname.clone(),
@@ -397,7 +400,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
} }
let mut upstreams: Vec<Upstream> = Vec::new(); let mut upstreams: Vec<Upstream> = Vec::new();
let mut seen_upstreams = BTreeSet::new(); let mut seen_upstreams = BTreeSet::new();
for u in raw.upstreams.iter().take(MAX_UPSTREAMS) { for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() {
match parse_url(u, false) { match parse_url(u, false) {
Ok((up, _)) => { Ok((up, _)) => {
if seen_upstreams.insert(up.clone()) { if seen_upstreams.insert(up.clone()) {
@@ -405,14 +408,16 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
} else { } else {
errors.push(E::DuplicateUpstream { errors.push(E::DuplicateUpstream {
file: f(), file: f(),
url: u.clone(), url: shown_url(u),
index,
}); });
} }
} }
Err(reason) => errors.push(E::BadUpstreamUrl { Err(reason) => errors.push(E::BadUpstreamUrl {
file: f(), file: f(),
url: u.clone(), url: shown_url(u),
reason, reason,
index: Some(index),
}), }),
} }
} }
@@ -420,8 +425,14 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
if upstreams.windows(2).any(|w| w[0].scheme != w[1].scheme) { if upstreams.windows(2).any(|w| w[0].scheme != w[1].scheme) {
errors.push(E::BadUpstreamUrl { errors.push(E::BadUpstreamUrl {
file: f(), file: f(),
url: raw.upstreams.join(", "), url: raw
reason: "all upstreams of a host must use the same scheme", .upstreams
.iter()
.map(|u| shown_url(u))
.collect::<Vec<_>>()
.join(", "),
reason: r::URL_MIXED,
index: None,
}); });
} }
@@ -450,8 +461,22 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
} }
AuthMode::None => Vec::new(), AuthMode::None => Vec::new(),
}; };
let request_headers = check_rules(file, raw.request_headers, true, &identity, site, errors); let request_headers = check_rules(
let response_headers = check_rules(file, raw.response_headers, false, &[], site, errors); file,
"request_headers",
raw.request_headers,
&identity,
site,
errors,
);
let response_headers = check_rules(
file,
"response_headers",
raw.response_headers,
&[],
site,
errors,
);
let health_check = raw.health_check.and_then(|hc| { let health_check = raw.health_check.and_then(|hc| {
let bad = |reason| E::BadHealthCheck { file: f(), reason }; let bad = |reason| E::BadHealthCheck { file: f(), reason };
@@ -462,9 +487,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
.bytes() .bytes()
.all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c)); .all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c));
if !ok_path { if !ok_path {
errors.push(bad( errors.push(bad(r::HEALTH_PATH));
"path must start with '/' and contain only visible ASCII without '{', '}' or '#'",
));
return None; return None;
} }
match u32::try_from(hc.interval_secs) { match u32::try_from(hc.interval_secs) {
@@ -473,12 +496,21 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
interval_secs: i, interval_secs: i,
}), }),
_ => { _ => {
errors.push(bad("interval_secs must be between 1 and 3600")); errors.push(bad(r::HEALTH_INTERVAL));
None None
} }
} }
}); });
// 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 { if errors.len() != before {
return None; return None;
} }
@@ -496,6 +528,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
websockets: raw.websockets, websockets: raw.websockets,
health_check, health_check,
share_links: raw.share_links, share_links: raw.share_links,
device_certs: raw.device_certs,
access_log: match raw.access_log { access_log: match raw.access_log {
RawAccessLog::Off => AccessLog::Off, RawAccessLog::Off => AccessLog::Off,
RawAccessLog::Truncated => AccessLog::Truncated, RawAccessLog::Truncated => AccessLog::Truncated,
@@ -527,45 +560,65 @@ fn is_protected(name: &str) -> bool {
fn check_rules( fn check_rules(
file: &str, file: &str,
list: &str,
raw: Vec<RawRule>, raw: Vec<RawRule>,
request: bool,
identity: &[String], identity: &[String],
site: Option<&Site>, site: Option<&Site>,
errors: &mut Vec<E>, errors: &mut Vec<E>,
) -> Vec<HeaderRule> { ) -> Vec<HeaderRule> {
let request = list == "request_headers";
let f = || file.to_owned(); let f = || file.to_owned();
let mut out = Vec::new(); let mut out = Vec::new();
let mut seen = BTreeSet::new(); let mut seen = BTreeSet::new();
for r in raw { for (i, r) in raw.into_iter().enumerate() {
let at = |part: &str| {
if part.is_empty() {
format!("{list}[{i}]")
} else {
format!("{list}[{i}].{part}")
}
};
let header = r.name.clone(); let header = r.name.clone();
if !valid_header_name(&r.name) { if !valid_header_name(&r.name) {
errors.push(E::InvalidHeaderName { errors.push(E::InvalidHeaderName {
file: f(), file: f(),
name: r.name, name: r.name,
field: at("name"),
}); });
continue; continue;
} }
let lower = r.name.to_ascii_lowercase(); let lower = r.name.to_ascii_lowercase();
if is_protected(&r.name) || identity.contains(&lower) { if is_protected(&r.name) || identity.contains(&lower) {
errors.push(E::ProtectedHeader { file: f(), header }); errors.push(E::ProtectedHeader {
file: f(),
header,
field: at("name"),
});
continue; continue;
} }
if !seen.insert(lower) { if !seen.insert(lower) {
errors.push(E::DuplicateHeaderRule { file: f(), header }); errors.push(E::DuplicateHeaderRule {
file: f(),
header,
field: at("name"),
});
continue; continue;
} }
let bad = |reason| E::BadHeaderRule { let bad = |reason| E::BadHeaderRule {
file: f(), file: f(),
header: header.clone(), header: header.clone(),
reason, reason,
field: at(if reason == r::RULE_NEITHER {
"value"
} else {
""
}),
}; };
match (r.action, r.value, r.secret) { match (r.action, r.value, r.secret) {
(RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }), (RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }),
(RawAction::Remove, _, _) => errors.push(bad("remove takes no value or secret")), (RawAction::Remove, _, _) => errors.push(bad(r::RULE_REMOVE_VALUE)),
(RawAction::Set, Some(_), Some(_)) => { (RawAction::Set, Some(_), Some(_)) => errors.push(bad(r::RULE_BOTH)),
errors.push(bad("give either value or secret, not both")) (RawAction::Set, None, None) => errors.push(bad(r::RULE_NEITHER)),
}
(RawAction::Set, None, None) => errors.push(bad("set needs a value or a secret")),
(RawAction::Set, Some(v), None) => match check_header_value(&v) { (RawAction::Set, Some(v), None) => match check_header_value(&v) {
Ok(()) => out.push(HeaderRule::Set { Ok(()) => out.push(HeaderRule::Set {
name: r.name, name: r.name,
@@ -575,15 +628,21 @@ fn check_rules(
file: f(), file: f(),
header, header,
reason, reason,
field: at("value"),
}), }),
}, },
(RawAction::Set, None, Some(s)) => { (RawAction::Set, None, Some(s)) => {
if !request { if !request {
errors.push(E::SecretInResponseHeader { file: f(), header }); errors.push(E::SecretInResponseHeader {
file: f(),
header,
field: at(""),
});
} else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) { } else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) {
errors.push(E::UndefinedSecret { errors.push(E::UndefinedSecret {
file: f(), file: f(),
secret: s, secret: s,
field: at("secret"),
}); });
} else { } else {
out.push(HeaderRule::Set { out.push(HeaderRule::Set {
@@ -608,19 +667,19 @@ fn valid_header_name(n: &str) -> bool {
fn check_header_value(v: &str) -> Result<(), &'static str> { fn check_header_value(v: &str) -> Result<(), &'static str> {
if v.is_empty() { if v.is_empty() {
return Err("an empty value is not allowed; use action = \"remove\""); return Err(r::VALUE_EMPTY);
} }
if v.len() > 4096 { if v.len() > 4096 {
return Err("it is longer than 4096 characters"); return Err(r::VALUE_LONG);
} }
if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) { if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) {
return Err("only visible ASCII characters and spaces are allowed"); return Err(r::VALUE_ASCII);
} }
if v.contains(['{', '}']) { if v.contains(['{', '}']) {
return Err("'{' and '}' are not allowed (they are placeholders in Caddy)"); return Err(r::VALUE_BRACES);
} }
if v.starts_with(' ') || v.ends_with(' ') { if v.starts_with(' ') || v.ends_with(' ') {
return Err("it must not start or end with a space"); return Err(r::VALUE_EDGE_SPACE);
} }
Ok(()) Ok(())
} }
@@ -629,44 +688,47 @@ fn check_header_value(v: &str) -> Result<(), &'static str> {
pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> { pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> {
if h.is_empty() { if h.is_empty() {
return Err("it is empty"); return Err(r::HOST_EMPTY);
} }
if h.len() > 253 { if h.len() > 253 {
return Err("it is longer than 253 characters"); return Err(r::HOST_TOO_LONG);
} }
if h.parse::<IpAddr>().is_ok() || h.starts_with('[') { if h.parse::<IpAddr>().is_ok() || h.starts_with('[') {
return Err("IP addresses are not hostnames"); return Err(r::HOST_IP);
} }
if h.contains('*') { if h.contains('*') {
return Err("wildcards are not supported"); return Err(r::HOST_WILDCARD);
}
if h.contains(char::is_whitespace) {
return Err(r::HOST_SPACES);
} }
if h.ends_with('.') { if h.ends_with('.') {
return Err("it must not end with a dot"); return Err(r::HOST_TRAILING_DOT);
} }
if h.bytes().any(|c| c.is_ascii_uppercase()) { if h.bytes().any(|c| c.is_ascii_uppercase()) {
return Err("it must be lowercase"); return Err(r::HOST_UPPERCASE);
} }
let mut last = ""; let mut last = "";
for label in h.split('.') { for label in h.split('.') {
if label.is_empty() { if label.is_empty() {
return Err("it has an empty label"); return Err(r::HOST_EMPTY_LABEL);
} }
if label.len() > 63 { if label.len() > 63 {
return Err("a label is longer than 63 characters"); return Err(r::HOST_LABEL_LONG);
} }
if !label if !label
.bytes() .bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-') .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
{ {
return Err("only a-z, 0-9, '-' and '.' are allowed"); return Err(r::HOST_CHARACTERS);
} }
if label.starts_with('-') || label.ends_with('-') { if label.starts_with('-') || label.ends_with('-') {
return Err("a label must not start or end with '-'"); return Err(r::HOST_LABEL_DASH);
} }
last = label; last = label;
} }
if last.bytes().all(|c| c.is_ascii_digit()) { if last.bytes().all(|c| c.is_ascii_digit()) {
return Err("the last label must not be numeric"); return Err(r::HOST_NUMERIC);
} }
Ok(()) Ok(())
} }
@@ -675,42 +737,42 @@ pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> {
/// (for the forward-auth endpoint); otherwise any path other than `/` is rejected. /// (for the forward-auth endpoint); otherwise any path other than `/` is rejected.
fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static str> { fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static str> {
if !raw.bytes().all(|c| c.is_ascii_graphic()) { if !raw.bytes().all(|c| c.is_ascii_graphic()) {
return Err("it must be plain ASCII without spaces"); return Err(r::URL_ASCII);
} }
let u = url::Url::parse(raw).map_err(|_| "it is not a URL like http://127.0.0.1:8080")?; let u = url::Url::parse(raw).map_err(|_| r::URL_NOT_URL)?;
let scheme = match u.scheme() { let scheme = match u.scheme() {
"http" => Scheme::Http, "http" => Scheme::Http,
"https" => Scheme::Https, "https" => Scheme::Https,
_ => return Err("only http:// and https:// are supported"), _ => return Err(r::URL_SCHEME),
}; };
if !u.username().is_empty() || u.password().is_some() { if !u.username().is_empty() || u.password().is_some() {
return Err("credentials in the URL are not allowed"); return Err(r::URL_CREDENTIALS);
} }
if u.fragment().is_some() { if u.fragment().is_some() {
return Err("a #fragment is not allowed"); return Err(r::URL_FRAGMENT);
} }
let host = match u.host() { let host = match u.host() {
None => return Err("it has no host"), None => return Err(r::URL_NO_HOST),
Some(url::Host::Ipv4(ip)) => UpstreamHost::Ip(IpAddr::V4(ip)), Some(url::Host::Ipv4(ip)) => UpstreamHost::Ip(IpAddr::V4(ip)),
Some(url::Host::Ipv6(ip)) => UpstreamHost::Ip(IpAddr::V6(ip)), Some(url::Host::Ipv6(ip)) => UpstreamHost::Ip(IpAddr::V6(ip)),
Some(url::Host::Domain(d)) => { Some(url::Host::Domain(d)) => {
if check_hostname(d).is_err() { if check_hostname(d).is_err() {
return Err("the host name is not valid"); return Err(r::URL_HOST_NAME);
} }
UpstreamHost::Name(d.to_owned()) UpstreamHost::Name(d.to_owned())
} }
}; };
let port = u.port_or_known_default().ok_or("it has no port")?; let port = u.port_or_known_default().ok_or(r::URL_NO_PORT)?;
if port == 0 { if port == 0 {
return Err("port 0 is not usable"); return Err(r::URL_PORT_ZERO);
} }
let mut path = u.path().to_owned(); let mut path = u.path().to_owned();
if !allow_path { if !allow_path {
if path != "/" && !path.is_empty() { if path != "/" && !path.is_empty() {
return Err("a path is not allowed; requests keep their own path"); return Err(r::URL_PATH);
} }
if u.query().is_some() { if u.query().is_some() {
return Err("a ?query is not allowed"); return Err(r::URL_QUERY);
} }
} else { } else {
if let Some(q) = u.query() { if let Some(q) = u.query() {
@@ -718,8 +780,50 @@ fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static
path.push_str(q); path.push_str(q);
} }
if path.contains(['{', '}']) { if path.contains(['{', '}']) {
return Err("'{' and '}' are not allowed"); return Err(r::URL_BRACES);
} }
} }
Ok((Upstream { scheme, host, port }, path)) Ok((Upstream { scheme, host, port }, path))
} }
/// A URL as an error may show it: everything before the last `@` (after the scheme) is
/// replaced by `…`, so a user name or password, even one containing `/`, `?` or `#`, never
/// reaches a message, a log or the API. A URL with no `@` is shown as it is.
pub(crate) fn shown_url(raw: &str) -> String {
let (scheme, rest) = match raw.find("://") {
Some(i) => (&raw[..i + 3], &raw[i + 3..]),
None => ("", raw),
};
match rest.rfind('@') {
Some(at) => format!("{scheme}\u{2026}@{}", &rest[at + 1..]),
None => raw.to_owned(),
}
}
#[cfg(test)]
mod shown_tests {
use super::shown_url;
#[test]
fn userinfo_is_hidden() {
assert_eq!(
shown_url("http://user:hunter2@10.0.0.1:80/x"),
"http://\u{2026}@10.0.0.1:80/x"
);
assert_eq!(shown_url("user:hunter2@host:80"), "\u{2026}@host:80");
assert_eq!(shown_url("http://10.0.0.1:80"), "http://10.0.0.1:80");
assert_eq!(shown_url("http://h/a@b"), "http://\u{2026}@b");
assert_eq!(
shown_url("http://admin:hunter/2@10.0.0.1:80"),
"http://\u{2026}@10.0.0.1:80"
);
assert_eq!(
shown_url("http://admin:hunter?2@10.0.0.1:80"),
"http://\u{2026}@10.0.0.1:80"
);
assert_eq!(
shown_url("http://admin:hunter#2@10.0.0.1:80"),
"http://\u{2026}@10.0.0.1:80"
);
}
}
+90
View File
@@ -72,6 +72,8 @@ fn options() -> CompileOptions {
access_log: "/var/log/ianitor/access.log".into(), access_log: "/var/log/ianitor/access.log".into(),
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(), caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None, 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)); 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] #[test]
fn outputs_reference_secrets_by_name_only() { fn outputs_reference_secrets_by_name_only() {
let edge = compile::edge(&model(false), &options()).unwrap(); 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" "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" hostname = "status.example.org"
upstreams = ["http://[::1]:3001"] upstreams = ["http://[::1]:3001"]
device_certs = true
+46
View File
@@ -145,6 +145,23 @@
{ {
"handler": "subroute", "handler": "subroute",
"routes": [ "routes": [
{
"handle": [
{
"handler": "static_response",
"status_code": 403
}
],
"match": [
{
"vars": {
"{http.request.tls.client.fingerprint}": [
""
]
}
}
]
},
{ {
"handle": [ "handle": [
{ {
@@ -465,6 +482,35 @@
} }
], ],
"tls_connection_policies": [ "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": { "certificate_selection": {
"any_tag": [ "any_tag": [
+14 -4
View File
@@ -1,5 +1,5 @@
{ {
"version": 1, "version": 3,
"http_listen": "0.0.0.0:80", "http_listen": "0.0.0.0:80",
"https_listen": "0.0.0.0:443", "https_listen": "0.0.0.0:443",
"https_port": 443, "https_port": 443,
@@ -30,6 +30,10 @@
"Remote-Name" "Remote-Name"
] ]
}, },
"device_certs": {
"ca": "/var/lib/ianitor/certs/domi-devices-ca.pem",
"allow": "/var/lib/ianitor/certs/domi-devices.pem"
},
"hosts": [ "hosts": [
{ {
"hostname": "photos.example.org", "hostname": "photos.example.org",
@@ -82,7 +86,9 @@
"path": "/api/v1/status", "path": "/api/v1/status",
"interval_secs": 15 "interval_secs": 15
}, },
"access_log": true "access_log": true,
"share_links": false,
"device_certs": false
}, },
{ {
"hostname": "status.example.org", "hostname": "status.example.org",
@@ -101,7 +107,9 @@
"request_headers": [], "request_headers": [],
"response_headers": [], "response_headers": [],
"health_check": null, "health_check": null,
"access_log": false "access_log": false,
"share_links": false,
"device_certs": true
}, },
{ {
"hostname": "wiki.home.test", "hostname": "wiki.home.test",
@@ -131,7 +139,9 @@
], ],
"response_headers": [], "response_headers": [],
"health_check": null, "health_check": null,
"access_log": false "access_log": 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());
}
}
+276
View File
@@ -0,0 +1,276 @@
// 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 routes repository holds exactly `ianitor.toml` and `hosts/<hostname>.toml`, and the
//! loader requires the exact path (ROADMAP §10: the check used to look at the base name only).
//! Validation errors carry a stable code, a field path and params for the UI (docs/ui-api.md §3.1).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use ianitor_core::routes::{EntryKind, RoutePath, check_path, check_tree};
use ianitor_core::{SourceFile, ValidationError, load};
#[test]
fn only_the_site_file_and_host_files_are_allowed() {
assert_eq!(
check_path("ianitor.toml", EntryKind::File).unwrap(),
RoutePath::Site
);
assert_eq!(
check_path("hosts/wiki.home.test.toml", EntryKind::File).unwrap(),
RoutePath::Host {
hostname: "wiki.home.test".into()
}
);
for bad in [
"README.md",
".gitattributes",
"hosts.toml",
"other/wiki.home.test.toml",
"hosts/sub/wiki.home.test.toml",
"hosts/wiki.home.test.toml/x",
"hosts/Wiki.home.test.toml",
"hosts/wiki.home.test.TOML",
"hosts/wiki.home.test",
"hosts/.toml",
"hosts/*.home.test.toml",
"hosts/wiki..test.toml",
"hosts/10.0.0.1.toml",
"hosts/wiki home.toml",
"hosts\\wiki.home.test.toml",
"hosts/wiki\\x.toml",
"IANITOR.toml",
"./ianitor.toml",
] {
let e = check_path(bad, EntryKind::File).unwrap_err();
assert!(
matches!(e, ValidationError::UnexpectedFile { ref file, .. } if file == bad),
"{bad}: {e:?}"
);
assert_eq!(e.code(), "repo.unexpected_file");
}
}
#[test]
fn links_executables_and_submodules_are_refused() {
for kind in [
EntryKind::Symlink,
EntryKind::Submodule,
EntryKind::Executable,
] {
assert!(check_path("hosts/a.test.toml", kind).is_err(), "{kind:?}");
assert!(check_path("ianitor.toml", kind).is_err(), "{kind:?}");
}
}
#[test]
fn a_tree_needs_the_site_file_and_reports_every_stray_file() {
let ok = [
("ianitor.toml", EntryKind::File),
("hosts/a.test.toml", EntryKind::File),
];
assert!(check_tree(ok).is_ok());
let errs = check_tree([
("hosts/a.test.toml", EntryKind::File),
("notes.txt", EntryKind::File),
("hosts/b/c.toml", EntryKind::File),
])
.unwrap_err();
assert_eq!(errs.len(), 3, "{errs:?}");
}
#[test]
fn the_loader_requires_the_exact_path() {
let site = SourceFile {
name: "ianitor.toml",
contents: "",
};
let body = "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n";
for name in [
"app.test.toml",
"other/app.test.toml",
"hosts/x/app.test.toml",
"hosts\\app.test.toml",
"./hosts/app.test.toml",
] {
let errs = load(
&site,
&[SourceFile {
name,
contents: body,
}],
)
.unwrap_err();
assert!(
errs.errors()
.iter()
.any(|e| matches!(e, ValidationError::FileNameMismatch { .. })),
"{name}: {errs:?}"
);
}
assert!(
load(
&site,
&[SourceFile {
name: "hosts/app.test.toml",
contents: body
}]
)
.is_ok()
);
}
fn errors_for(body: &str) -> Vec<ValidationError> {
let site = SourceFile {
name: "ianitor.toml",
contents: "secrets = [\"api_key\"]\n",
};
load(
&site,
&[SourceFile {
name: "hosts/app.test.toml",
contents: body,
}],
)
.unwrap_err()
.into_errors()
}
#[test]
fn errors_have_codes_fields_and_params_for_the_ui() {
let cases: &[(&str, &str, Option<&str>)] = &[
(
"upstreams = [\"http://127.0.0.1:1\"]\n",
"host.hostname.missing",
Some("hostname"),
),
(
"hostname = \"app.test\"\n",
"host.upstreams.missing",
Some("upstreams"),
),
(
"hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
"host.hostname.uppercase",
Some("hostname"),
),
(
"hostname = \"app test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
"host.hostname.spaces",
Some("hostname"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"ftp://x\"]\n",
"host.upstream.scheme",
Some("upstreams[1]"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1/x\"]\n",
"host.upstream.path",
Some("upstreams[0]"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"http://127.0.0.1:1\"]\n",
"host.upstream.duplicate",
Some("upstreams[1]"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"https://127.0.0.1:2\"]\n",
"host.upstream.mixed_schemes",
Some("upstreams"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ncolour = 1\n",
"host.field.unknown",
Some("colour"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"set\"\nname = \"Host\"\nvalue = \"x\"\n",
"host.header.protected",
Some("request_headers[1].name"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n",
"host.header.secret_response",
Some("response_headers[0]"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"nope\"\n",
"host.header.secret_unknown",
Some("request_headers[0].secret"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[health_check]\npath = \"/x\"\ninterval_secs = 0\n",
"host.health.interval",
Some("health_check.interval_secs"),
),
(
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\nauth = \"forward-auth\"\n",
"host.auth.not_configured",
Some("auth"),
),
];
for (body, code, field) in cases {
let errs = errors_for(body);
let e = errs
.iter()
.find(|e| e.code() == *code)
.unwrap_or_else(|| panic!("no {code} for {body:?}: {errs:?}"));
assert_eq!(e.field().as_deref(), *field, "{code}");
assert_eq!(e.params()["file"], "hosts/app.test.toml");
}
}
#[test]
fn params_carry_suggestions() {
let errs = errors_for("hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n");
let e = errs
.iter()
.find(|e| e.code() == "host.hostname.uppercase")
.unwrap();
assert_eq!(e.params()["suggestion"], "app.test");
let errs = errors_for("hostname = \"app.test\"\nupstreams = [\"http://10.0.0.2:3000/app\"]\n");
let e = errs
.iter()
.find(|e| e.code() == "host.upstream.path")
.unwrap();
assert_eq!(e.params()["suggestion"], "http://10.0.0.2:3000");
assert_eq!(e.params()["url"], "http://10.0.0.2:3000/app");
}
#[test]
fn a_password_in_an_upstream_url_is_never_repeated() {
let errs = errors_for(
"hostname = \"app.test\"\nupstreams = [\"http://admin:hunter2@10.0.0.2:3000\", \"ftp://u:hunter2@x\", \"http://admin:hunter2@10.0.0.2:3000\"]\n",
);
assert!(!errs.is_empty());
for e in &errs {
let all = format!("{e} {:?} {:?}", e.params(), e.field());
assert!(!all.contains("hunter2"), "{all}");
}
let e = errs
.iter()
.find(|e| e.code() == "host.upstream.credentials")
.unwrap();
assert_eq!(e.params()["url"], "http://\u{2026}@10.0.0.2:3000");
}
#[test]
fn credentials_with_slash_query_or_hash_are_never_repeated() {
for url in [
"http://admin:hunter/2@10.0.0.1:80",
"http://admin:hunter?2@10.0.0.1:80",
"http://admin:hunter#2@10.0.0.1:80",
"ftp://admin:hunter2@10.0.0.1",
] {
let errs = errors_for(&format!(
"hostname = \"app.test\"\nupstreams = [\"{url}\"]\n"
));
assert!(!errs.is_empty(), "{url} accepted");
for e in &errs {
let all = format!("{e} {:?}", e.params());
assert!(!all.contains("hunter"), "{url}: {all}");
}
}
}
+37 -49
View File
@@ -68,6 +68,7 @@ fn minimal_host_gets_documented_defaults() {
assert_eq!(h.auth, AuthMode::None); assert_eq!(h.auth, AuthMode::None);
assert!(h.websockets, "websockets default on, like Caddy"); assert!(h.websockets, "websockets default on, like Caddy");
assert!(!h.share_links); assert!(!h.share_links);
assert!(!h.device_certs, "device certificates are opt-in");
assert_eq!(h.access_log, AccessLog::Off); assert_eq!(h.access_log, AccessLog::Off);
assert!(h.health_check.is_none()); assert!(h.health_check.is_none());
assert!(h.request_headers.is_empty() && h.response_headers.is_empty()); assert!(h.request_headers.is_empty() && h.response_headers.is_empty());
@@ -85,6 +86,7 @@ auth = "forward-auth"
websockets = false websockets = false
share_links = true share_links = true
access_log = "truncated" access_log = "truncated"
device_certs = true
[health_check] [health_check]
path = "/healthz" path = "/healthz"
@@ -110,6 +112,7 @@ value = "max-age=31536000"
assert_eq!(h.auth, AuthMode::ForwardAuth); assert_eq!(h.auth, AuthMode::ForwardAuth);
assert!(!h.websockets); assert!(!h.websockets);
assert!(h.share_links); assert!(h.share_links);
assert!(h.device_certs);
assert_eq!(h.access_log, AccessLog::Truncated); assert_eq!(h.access_log, AccessLog::Truncated);
let hc = h.health_check.as_ref().unwrap(); let hc = h.health_check.as_ref().unwrap();
assert_eq!(hc.path, "/healthz"); assert_eq!(hc.path, "/healthz");
@@ -148,11 +151,11 @@ value = "max-age=31536000"
#[test] #[test]
fn hosts_are_sorted_by_hostname_whatever_the_file_order() { fn hosts_are_sorted_by_hostname_whatever_the_file_order() {
let a = SourceFile { let a = SourceFile {
name: "b.test.toml", name: "hosts/b.test.toml",
contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
}; };
let b = SourceFile { let b = SourceFile {
name: "a.test.toml", name: "hosts/a.test.toml",
contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
}; };
let m1 = load(&site(), &[a, b]).unwrap(); let m1 = load(&site(), &[a, b]).unwrap();
@@ -175,7 +178,7 @@ fn empty_site_file_is_allowed() {
contents: "", contents: "",
}, },
&[SourceFile { &[SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}], }],
); );
@@ -236,7 +239,7 @@ fn rejects_unknown_field_in_site_file() {
contents: "secrets = []\nsecret_values = { a = \"b\" }\n", contents: "secrets = []\nsecret_values = { a = \"b\" }\n",
}, },
&[SourceFile { &[SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}], }],
); );
@@ -348,10 +351,11 @@ fn accepts_good_hostnames() {
} }
#[test] #[test]
fn rejects_duplicate_hostnames_across_files() { fn a_second_file_for_the_same_host_is_refused_by_its_path() {
let r = load( // With the exact `hosts/<hostname>.toml` rule, two files can never hold one hostname:
&site(), // the second one is in the wrong place, whatever the file order.
&[ for order in [false, true] {
let mut files = vec![
SourceFile { SourceFile {
name: "hosts/app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
@@ -360,38 +364,19 @@ fn rejects_duplicate_hostnames_across_files() {
name: "other/app.test.toml", name: "other/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}, },
], ];
); if order {
let errs = r.unwrap_err(); files.reverse();
}
let errs = load(&site(), &files).unwrap_err();
assert_eq!( assert_eq!(
errs.errors(), errs.errors(),
[ValidationError::DuplicateHostname { [ValidationError::FileNameMismatch {
hostname: "app.test".into(), file: "other/app.test.toml".into(),
first: "hosts/app.test.toml".into(), hostname: "app.test".into()
second: "other/app.test.toml".into()
}] }]
); );
} }
#[test]
fn duplicate_detection_is_independent_of_file_order() {
let r = load(
&site(),
&[
SourceFile {
name: "other/app.test.toml",
contents: MINIMAL,
},
SourceFile {
name: "hosts/app.test.toml",
contents: MINIMAL,
},
],
);
let errs = r.unwrap_err();
assert!(
matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/app.test.toml" && second == "other/app.test.toml")
);
} }
#[test] #[test]
@@ -400,11 +385,11 @@ fn rejects_duplicate_source_file_names() {
&site(), &site(),
&[ &[
SourceFile { SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}, },
SourceFile { SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}, },
], ],
@@ -440,7 +425,9 @@ fn rejects_bad_upstream_urls() {
] { ] {
let e = single_error(&format!("hostname = \"app.test\"\nupstreams = [{bad:?}]\n")); let e = single_error(&format!("hostname = \"app.test\"\nupstreams = [{bad:?}]\n"));
assert!( assert!(
matches!(e, ValidationError::BadUpstreamUrl { ref url, .. } if url == bad), // Credentials are never repeated in an error.
matches!(e, ValidationError::BadUpstreamUrl { ref url, .. }
if url == bad || (bad.contains('@') && url == "http://\u{2026}@127.0.0.1:8080")),
"upstream {bad:?} gave {e:?}" "upstream {bad:?} gave {e:?}"
); );
} }
@@ -485,7 +472,8 @@ fn rejects_undefined_secret_reference() {
e, e,
ValidationError::UndefinedSecret { ValidationError::UndefinedSecret {
file: "hosts/app.test.toml".into(), file: "hosts/app.test.toml".into(),
secret: "nope".into() secret: "nope".into(),
field: "request_headers[0].secret".into()
} }
); );
} }
@@ -498,7 +486,7 @@ fn undefined_secret_is_reported_when_site_declares_none() {
contents: "", contents: "",
}, },
&[SourceFile { &[SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: &format!( contents: &format!(
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n" "{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n"
), ),
@@ -532,7 +520,7 @@ fn rejects_bad_secret_names_in_site_file() {
contents: &format!("secrets = [{bad:?}]\n"), contents: &format!("secrets = [{bad:?}]\n"),
}, },
&[SourceFile { &[SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}], }],
); );
@@ -678,7 +666,7 @@ fn forward_auth_requires_site_configuration() {
contents: "", contents: "",
}, },
&[SourceFile { &[SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"), contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"),
}], }],
); );
@@ -704,7 +692,7 @@ fn rejects_bad_forward_auth_site_config() {
contents: &format!("[forward_auth]\nurl = {bad:?}\n"), contents: &format!("[forward_auth]\nurl = {bad:?}\n"),
}, },
&[SourceFile { &[SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}], }],
); );
@@ -743,15 +731,15 @@ fn collects_errors_from_every_file() {
&site(), &site(),
&[ &[
SourceFile { SourceFile {
name: "a.test.toml", name: "hosts/a.test.toml",
contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n", contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n",
}, },
SourceFile { SourceFile {
name: "B.test.toml", name: "hosts/B.test.toml",
contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
}, },
SourceFile { SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}, },
], ],
@@ -830,7 +818,7 @@ fn rejects_wildcards_in_copy_headers() {
contents: "[forward_auth]\nurl = \"http://127.0.0.1:9091/x\"\ncopy_headers = [\"Remote-*\"]\n", contents: "[forward_auth]\nurl = \"http://127.0.0.1:9091/x\"\ncopy_headers = [\"Remote-*\"]\n",
}, },
&[SourceFile { &[SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}], }],
); );
@@ -861,7 +849,7 @@ fn rejects_oversized_route_files() {
contents: &big, contents: &big,
}, },
&[SourceFile { &[SourceFile {
name: "app.test.toml", name: "hosts/app.test.toml",
contents: MINIMAL, contents: MINIMAL,
}], }],
); );
+487
View File
@@ -0,0 +1,487 @@
// 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/.
//! Share-link tokens (ROADMAP §6 phase 2, tests first): a token is refused when expired, for
//! the wrong path, for the wrong host, tampered, without its password or with a wrong one,
//! and no path trick lets it escape its prefix.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::BTreeSet;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use ianitor_core::share::{
Claims, LinkSpec, Rejection, Revocations, ShareId, ShareKey, check_prefix, mint, path_within,
peek, session_value, verify_link, verify_session,
};
const NOW: u64 = 1_800_000_000;
const HOST: &str = "photos.home.test";
fn key() -> ShareKey {
ShareKey::new(b"0123456789abcdef0123456789abcdef-test-key").unwrap()
}
fn other_key() -> ShareKey {
ShareKey::new(b"fedcba9876543210fedcba9876543210-test-key").unwrap()
}
fn id(n: u8) -> ShareId {
ShareId([n; 16])
}
fn spec<'a>(prefix: &'a str, password: Option<&'a str>) -> LinkSpec<'a> {
LinkSpec {
id: id(7),
epoch: 3,
expires_at: NOW + 3600,
prefix,
password,
}
}
fn none() -> Revocations {
Revocations {
epoch: 3,
deny: BTreeSet::new(),
}
}
fn token(prefix: &str, password: Option<&str>) -> String {
mint(&key(), HOST, &spec(prefix, password)).unwrap()
}
#[test]
fn a_fresh_token_is_accepted_and_says_what_it_covers() {
let t = token("/albums/summer", None);
assert!(t.starts_with("ish1."), "{t}");
let c = verify_link(&key(), HOST, &t, None, NOW, &none()).unwrap();
assert_eq!(
c,
Claims {
id: id(7),
epoch: 3,
expires_at: NOW + 3600,
password: false,
prefix: "/albums/summer".into()
}
);
}
#[test]
fn an_expired_token_is_refused_as_expired() {
let t = token("/", None);
assert_eq!(
verify_link(&key(), HOST, &t, None, NOW + 3600, &none()),
Err(Rejection::Expired {
expires_at: NOW + 3600
})
);
assert_eq!(
verify_link(&key(), HOST, &t, None, NOW + 99_999, &none()),
Err(Rejection::Expired {
expires_at: NOW + 3600
})
);
}
#[test]
fn a_token_for_another_host_is_refused() {
let t = token("/", None);
for host in [
"other.home.test",
"PHOTOS.home.test",
"photos.home.test.",
"photos.home",
] {
assert_eq!(
verify_link(&key(), host, &t, None, NOW, &none()),
Err(Rejection::Invalid),
"{host}"
);
}
}
#[test]
fn a_token_made_with_another_key_is_refused() {
let t = mint(&other_key(), HOST, &spec("/", None)).unwrap();
assert_eq!(
verify_link(&key(), HOST, &t, None, NOW, &none()),
Err(Rejection::Invalid)
);
}
#[test]
fn every_single_bit_flip_is_refused() {
let t = token("/albums", None);
let raw = URL_SAFE_NO_PAD
.decode(t.strip_prefix("ish1.").unwrap())
.unwrap();
for i in 0..raw.len() {
for bit in 0..8 {
let mut r = raw.clone();
r[i] ^= 1 << bit;
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&r));
let got = verify_link(&key(), HOST, &forged, None, NOW, &none());
assert!(
matches!(
got,
Err(Rejection::Invalid | Rejection::Malformed | Rejection::PasswordRequired)
),
"byte {i} bit {bit}: {got:?}"
);
}
}
}
#[test]
fn a_longer_expiry_or_wider_prefix_cannot_be_spliced_in() {
let t = token("/albums/summer", None);
let raw = URL_SAFE_NO_PAD
.decode(t.strip_prefix("ish1.").unwrap())
.unwrap();
let (payload, mac) = raw.split_at(raw.len() - 32);
// Same MAC, prefix cut down to "/albums".
let mut p = payload[..30].to_vec();
p.extend_from_slice(b"/albums");
p.extend_from_slice(mac);
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p));
assert_eq!(
verify_link(&key(), HOST, &forged, None, NOW, &none()),
Err(Rejection::Invalid)
);
// Same MAC, expiry pushed out.
let mut p = payload.to_vec();
p[21..29].copy_from_slice(&(NOW + 10 * 3600).to_be_bytes());
p.extend_from_slice(mac);
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p));
assert_eq!(
verify_link(&key(), HOST, &forged, None, NOW, &none()),
Err(Rejection::Invalid)
);
}
#[test]
fn garbage_is_malformed_never_a_panic() {
for bad in [
"",
"ish1.",
"ish1.!!!!",
"ish2.AAAA",
"iss1.AAAA",
"ish1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
&"ish1.".repeat(400),
"ish1.\u{0}",
] {
assert_eq!(
verify_link(&key(), HOST, bad, None, NOW, &none()),
Err(Rejection::Malformed),
"{bad:?}"
);
}
}
#[test]
fn a_password_link_needs_its_password() {
let t = token("/", Some("correct horse"));
assert!(peek(&t).unwrap().password);
assert_eq!(
verify_link(&key(), HOST, &t, None, NOW, &none()),
Err(Rejection::PasswordRequired)
);
for wrong in ["", "correct hors", "correct horse ", "Correct horse", "x"] {
assert_eq!(
verify_link(&key(), HOST, &t, Some(wrong), NOW, &none()),
Err(Rejection::Invalid),
"{wrong:?}"
);
}
let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap();
assert!(c.password);
}
#[test]
fn the_token_carries_no_password_hash() {
// Two links that differ only in the password have the same payload; only the MAC differs.
let a = token("/", Some("password-one"));
let b = token("/", Some("password-two"));
let ra = URL_SAFE_NO_PAD
.decode(a.strip_prefix("ish1.").unwrap())
.unwrap();
let rb = URL_SAFE_NO_PAD
.decode(b.strip_prefix("ish1.").unwrap())
.unwrap();
assert_eq!(ra.len(), rb.len());
assert_eq!(ra[..ra.len() - 32], rb[..rb.len() - 32]);
assert_ne!(ra[ra.len() - 32..], rb[rb.len() - 32..]);
}
#[test]
fn a_dropped_password_flag_does_not_open_the_link() {
let t = token("/", Some("correct horse"));
let mut raw = URL_SAFE_NO_PAD
.decode(t.strip_prefix("ish1.").unwrap())
.unwrap();
raw[29] = 0;
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&raw));
assert_eq!(
verify_link(&key(), HOST, &forged, None, NOW, &none()),
Err(Rejection::Invalid)
);
}
#[test]
fn passwords_are_8_to_128_characters() {
assert!(mint(&key(), HOST, &spec("/", Some("short"))).is_err());
assert!(mint(&key(), HOST, &spec("/", Some(&"x".repeat(129)))).is_err());
assert!(mint(&key(), HOST, &spec("/", Some("12345678"))).is_ok());
}
#[test]
fn stopped_links_and_older_epochs_are_revoked() {
let t = token("/", None);
let mut r = none();
r.deny.insert(id(7));
assert_eq!(
verify_link(&key(), HOST, &t, None, NOW, &r),
Err(Rejection::Revoked)
);
let r = Revocations {
epoch: 4,
deny: BTreeSet::new(),
};
assert_eq!(
verify_link(&key(), HOST, &t, None, NOW, &r),
Err(Rejection::Revoked)
);
// Another link on the deny list does not matter.
let mut r = none();
r.deny.insert(id(8));
assert!(verify_link(&key(), HOST, &t, None, NOW, &r).is_ok());
}
#[test]
fn session_cookies_and_link_tokens_are_not_interchangeable() {
let t = token("/albums", Some("correct horse"));
let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap();
let s = session_value(&key(), HOST, &c);
assert!(s.starts_with("iss1."));
assert_eq!(verify_session(&key(), HOST, &s, NOW, &none()).unwrap(), c);
// A cookie is not a link, a link is not a cookie, even with the prefix swapped.
assert!(verify_link(&key(), HOST, &s, None, NOW, &none()).is_err());
assert!(verify_session(&key(), HOST, &t, NOW, &none()).is_err());
let swapped = s.replacen("iss1.", "ish1.", 1);
assert!(verify_link(&key(), HOST, &swapped, Some("correct horse"), NOW, &none()).is_err());
let swapped = t.replacen("ish1.", "iss1.", 1);
assert!(verify_session(&key(), HOST, &swapped, NOW, &none()).is_err());
// Cookies are host-bound, expire and are revoked like links.
assert_eq!(
verify_session(&key(), "other.home.test", &s, NOW, &none()),
Err(Rejection::Invalid)
);
assert!(matches!(
verify_session(&key(), HOST, &s, NOW + 3600, &none()),
Err(Rejection::Expired { .. })
));
let mut r = none();
r.deny.insert(id(7));
assert_eq!(
verify_session(&key(), HOST, &s, NOW, &r),
Err(Rejection::Revoked)
);
}
#[test]
fn short_keys_are_refused() {
assert!(ShareKey::new(b"short").is_err());
assert!(ShareKey::new(&[0u8; 31]).is_err());
assert!(ShareKey::new(&[0u8; 32]).is_ok());
assert!(!format!("{:?}", key()).contains("0123"));
}
#[test]
fn prefixes_are_normalised_or_refused() {
assert_eq!(check_prefix("/").unwrap(), "/");
assert_eq!(check_prefix("/a/").unwrap(), "/a");
assert_eq!(
check_prefix("/albums/summer-2026").unwrap(),
"/albums/summer-2026"
);
for bad in [
"", "a", "//", "/a//b", "/a/../b", "/..", "/.", "/a/./b", "/a%2fb", "/a\\b", "/a b",
"/a;b", "/ä", "/a?b", "/a#b",
] {
assert!(check_prefix(bad).is_err(), "{bad:?} accepted");
}
assert!(check_prefix(&format!("/{}", "a".repeat(256))).is_err());
// A prefix that is not in normal form is not minted.
assert!(mint(&key(), HOST, &spec("/a/", None)).is_err());
}
#[test]
fn ids_round_trip_as_hex() {
let i = ShareId([0xab; 16]);
assert_eq!(i.to_hex(), "ab".repeat(16));
assert_eq!(ShareId::from_hex(&i.to_hex()), Some(i));
for bad in [
"",
"ab",
&"AB".repeat(16),
&"zz".repeat(16),
&"a".repeat(33),
] {
assert_eq!(ShareId::from_hex(bad), None, "{bad:?}");
}
}
// ------------------------------------------------------------------ prefix escapes
#[test]
fn paths_under_the_prefix_are_within() {
for (prefix, path) in [
("/a", "/a"),
("/a", "/a/"),
("/a", "/a/b"),
("/a", "/a/b/c.jpg"),
("/a", "/a/b%20c"),
("/a", "/a/%E2%9C%93"),
("/", "/"),
("/", "/anything/at/all"),
("/a/b", "/a/b/c"),
("/a", "/a/b;v=1"),
("/a", "/a/.well"),
("/a", "/a/%C3%A9t%C3%A9.jpg"),
("/a", "/a/%e2%9c%93"),
("/a", "/a/a%20b"),
// QC fix round 3: ordinary names with look-alike dots or spaces inside.
("/a", "/a/Wait%E2%80%A6.pdf"),
("/a", "/a/%E3%80%80photo"),
("/a", "/a/my%C2%A0file.pdf"),
("/a", "/a/dokumenty/p%C5%99ehled"),
("/a", "/a/my%20file.pdf"),
("/a", "/a/a+b"),
("/a", "/a/caf%C3%A9"),
("/a", "/a/cafe%CC%81"),
("/a", "/a/%E3%80%80photo%E3%80%80album"),
("/a", "/a/e%CC%81"),
("/a", "/a/%E2%80%93"),
("/a", "/a/%E6%97%85%E8%A1%8C"),
("/a", "/a/.well-known/x"),
("/a", "/a/%C2%BD.txt"),
("/a", "/a/x%3Fy"),
] {
assert!(path_within(prefix, path), "{prefix} should cover {path}");
}
}
#[test]
fn no_path_trick_escapes_the_prefix() {
let cases = [
("/a", "/ab"),
("/a", "/abc/d"),
("/a", "/A"),
("/a", "/A/b"),
("/a/b", "/a"),
("/a/b", "/a/bc"),
("/a", "/b"),
("/a", "/a/../b"),
("/a", "/a/.."),
("/a", "/a/./../b"),
("/a", "/a/%2e%2e/b"),
("/a", "/a/%2E%2E/b"),
("/a", "/a/.%2e/b"),
("/a", "/a/%2e./b"),
("/a", "/a/%252e%252e/b"),
("/a", "/a/%25252e/b"),
("/a", "/a%2f..%2fb"),
("/a", "/a%2F..%2Fb"),
("/a", "/a/..%2fb"),
("/a", "/a//b"),
("/a", "//a/b"),
("/a", "/a\\..\\b"),
("/a", "/a/..\\b"),
("/a", "/a%5c..%5cb"),
("/a", "/a/..;/b"),
("/a", "/a/.;/b"),
("/a", "/a/%00/b"),
("/a", "/a/b c"),
("/a", "/a/\tb"),
("/a", "a/b"),
("/a", ""),
("/a", "/a/ä"),
("/", "/../etc/passwd"),
("/", "//evil"),
("/", "/%2e%2e/x"),
// QC fix round 1: overlong UTF-8, IIS %u, fullwidth dots, Windows-trimmed and
// encoded-semicolon dot segments.
("/a", "/a/%c0%ae%c0%ae/b"),
("/a", "/a/%C0%AE%C0%AE/secret"),
("/a", "/a/..%c0%afb"),
("/a", "/a/%e0%80%ae%e0%80%ae/b"),
("/a", "/a/%f0%80%80%ae/b"),
("/a", "/a/%u002e%u002e/b"),
("/a", "/a/%u002E%u002E/b"),
("/a", "/a/..%u2215b"),
("/a", "/a/%ef%bc%8e%ef%bc%8e/b"),
("/a", "/a/..%ef%bc%8fb"),
("/a", "/a/..%e2%88%95b"),
("/a", "/a/..%20/b"),
("/a", "/a/.%20/b"),
("/a", "/a/..%09/b"),
("/a", "/a/..%3b/b"),
("/a", "/a/..%3B/b"),
("/a", "/a/..%3bx/b"),
("/a", "/a/.;x/b"),
("/a", "/a;/../b"),
("/a", "/a/%2E./b"),
// QC fix round 2: NFKC look-alikes and dots before an encoded byte.
("/a", "/a/%e2%80%a5/b"),
("/a", "/a/%E2%80%A5/b"),
("/a", "/a/%ef%b8%b0/b"),
("/a", "/a/..%ef%b9%a8secret"),
("/a", "/a/..%3f/b"),
("/a", "/a/..%3F"),
("/a", "/a/..%23/b"),
("/a", "/a/%e3%80%80/b"),
("/a", "/a/%zz/b"),
("/a", "/a/%e2%9c"),
// QC fix round 3: a segment that is only an ellipsis or a look-alike space, slash
// look-alikes, and a broken escape that from_str_radix would take.
("/a", "/a/%E2%80%A6/b"),
("/a", "/a/%E2%80%A6"),
("/a", "/a/%E3%80%80/b"),
("/a", "/a/%C2%A0%C2%A0/b"),
("/a", "/a/..%e2%88%95b"),
("/a", "/a/..%e2%81%84b"),
("/a", "/a/..%e2%a7%b8b"),
("/a", "/a/x%e2%88%95y"),
("/a", "/a/x%e2%81%84y"),
("/a", "/a/%+f/b"),
("/a", "/a/%-1/b"),
// QC fix round 4: dot-only segments hidden by invisible characters.
("/a", "/a/%e2%80%8b../b"),
("/a", "/a/%ef%bb%bf../b"),
("/a", "/a/%c2%ad../b"),
("/a", "/a/%cc%81../b"),
("/a", "/a/%e2%80%a4.%e2%80%8b/b"),
("/a", "/a/%e2%81%a0%e2%80%a5/b"),
("/a", "/a/..%cc%81/b"),
("/a", "/a/%e3%80%80../b"),
("/a", "/a/%ef%bc%8e%ef%bc%8e/b"),
("/a", "/a/%e2%80%a5%3bx/b"),
("/a", "/a/%ef%bc%85/b"),
("/a", "/a/x%ef%bc%8fy"),
("/a", "/a/%e2%80%a4%09/b"),
("/a", "/a/%ef%b9%a8"),
("/a", "/a/%e2%88%96"),
("/a", "/a/%e2%80%8b/b"),
];
for (prefix, path) in cases {
assert!(
!path_within(prefix, path),
"{prefix} must not cover {path:?}"
);
}
}
+7
View File
@@ -27,9 +27,16 @@ arc-swap = "1.7"
instant-acme = { version = "0.8.5", default-features = false, features = ["ring", "hyper-rustls", "rcgen"] } instant-acme = { version = "0.8.5", default-features = false, features = ["ring", "hyper-rustls", "rcgen"] }
x509-parser = "0.18" x509-parser = "0.18"
thiserror.workspace = true thiserror.workspace = true
ring.workspace = true
hyper.workspace = true
hyper-util.workspace = true
http-body-util.workspace = true
form_urlencoded = "1.2"
[dev-dependencies] [dev-dependencies]
ianitor-testkit.workspace = true ianitor-testkit.workspace = true
ring.workspace = true
rcgen.workspace = true
[lints] [lints]
workspace = true workspace = true
+78 -20
View File
@@ -21,13 +21,14 @@ use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService; use pingora::services::background::BackgroundService;
use crate::logging::now_secs; use crate::logging::now_secs;
use crate::runtime::Runtime; use crate::shared::{CertState, Shared};
use crate::tls::{CertStore, certified_key, not_after}; use crate::tls::{certified_key, not_after};
const RENEW_BEFORE_SECS: f64 = 30.0 * 86_400.0; const RENEW_BEFORE_SECS: f64 = 30.0 * 86_400.0;
const CHECK_EVERY: Duration = Duration::from_secs(12 * 3600); const CHECK_EVERY: Duration = Duration::from_secs(12 * 3600);
const FIRST_RETRY: Duration = Duration::from_secs(30); const FIRST_RETRY: Duration = Duration::from_secs(30);
const MAX_RETRY: Duration = Duration::from_secs(3600); const MAX_RETRY: Duration = Duration::from_secs(3600);
const MIN_GAP: Duration = Duration::from_secs(5);
/// HTTP-01 tokens → key authorizations, shared with the HTTP listener. /// HTTP-01 tokens → key authorizations, shared with the HTTP listener.
#[derive(Default)] #[derive(Default)]
@@ -52,8 +53,7 @@ impl Challenges {
} }
pub struct AcmeService { pub struct AcmeService {
pub rt: Arc<Runtime>, pub shared: Arc<Shared>,
pub certs: Arc<CertStore>,
pub challenges: Arc<Challenges>, pub challenges: Arc<Challenges>,
/// Extra trust root for the ACME directory (tests against Pebble only). /// Extra trust root for the ACME directory (tests against Pebble only).
pub ca_root: Option<PathBuf>, pub ca_root: Option<PathBuf>,
@@ -84,7 +84,7 @@ fn fnv(data: &[u8]) -> String {
impl AcmeService { impl AcmeService {
fn dir(&self) -> PathBuf { fn dir(&self) -> PathBuf {
self.rt.acme_dir() self.shared.current().acme_dir()
} }
fn paths(&self, host: &str) -> (PathBuf, PathBuf) { fn paths(&self, host: &str) -> (PathBuf, PathBuf) {
@@ -102,7 +102,8 @@ impl AcmeService {
let expiry = not_after(&cert_pem)?; let expiry = not_after(&cert_pem)?;
match certified_key(&cert_pem, &key_pem) { match certified_key(&cert_pem, &key_pem) {
Ok(ck) => { Ok(ck) => {
self.certs.insert(host, ck); self.shared.certs.insert(host, ck);
self.ok(host, expiry);
Some(expiry) Some(expiry)
} }
Err(e) => { Err(e) => {
@@ -207,18 +208,30 @@ impl AcmeService {
let (crt, key) = self.paths(host); let (crt, key) = self.paths(host);
write_private(&key, key_pem.as_bytes())?; write_private(&key, key_pem.as_bytes())?;
write_private(&crt, chain_pem.as_bytes())?; write_private(&crt, chain_pem.as_bytes())?;
self.certs.insert(host, ck); self.shared.certs.insert(host, ck);
self.ok(host, expiry);
log::info!(target: "ianitor::acme", "{host}: certificate issued, valid until {expiry}"); log::info!(target: "ianitor::acme", "{host}: certificate issued, valid until {expiry}");
Ok(expiry) Ok(expiry)
} }
/// One pass over every ACME host. Returns false if any host failed. /// One pass over every ACME host. Returns false if any host failed.
fn ok(&self, host: &str, expiry: i64) {
self.shared.set_cert_state(
host,
CertState {
state: "ok",
not_after: Some(expiry),
error: None,
},
);
}
async fn round(&self, expiries: &mut HashMap<String, i64>) -> bool { async fn round(&self, expiries: &mut HashMap<String, i64>) -> bool {
let Some(acme) = &self.rt.cfg.acme else { let rt = self.shared.current();
let Some(acme) = &rt.cfg.acme else {
return true; return true;
}; };
let due: Vec<String> = self let due: Vec<String> = rt
.rt
.acme_hosts() .acme_hosts()
.into_iter() .into_iter()
.filter(|h| { .filter(|h| {
@@ -230,10 +243,25 @@ impl AcmeService {
if due.is_empty() { if due.is_empty() {
return true; return true;
} }
for h in &due {
if !expiries.contains_key(h) {
self.shared.set_cert_state(
h,
CertState {
state: "pending",
not_after: None,
error: None,
},
);
}
}
let account = match self.account(&acme.directory, acme.email.as_deref()).await { let account = match self.account(&acme.directory, acme.email.as_deref()).await {
Ok(a) => a, Ok(a) => a,
Err(e) => { Err(e) => {
log::error!(target: "ianitor::acme", "{e}"); log::error!(target: "ianitor::acme", "{e}");
for h in &due {
self.failed(h, expiries.get(h).copied(), &e);
}
return false; return false;
} }
}; };
@@ -245,34 +273,60 @@ impl AcmeService {
} }
Err(e) => { Err(e) => {
log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}"); log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}");
self.failed(&host, expiries.get(&host).copied(), &e);
ok = false; ok = false;
} }
} }
} }
ok ok
} }
/// A host that still has a valid certificate stays `ok` while renewal retries.
fn failed(&self, host: &str, expiry: Option<i64>, error: &str) {
let still_valid = expiry.is_some_and(|e| (e as f64) > now_secs());
self.shared.set_cert_state(
host,
CertState {
state: if still_valid { "ok" } else { "failed" },
not_after: expiry,
error: Some(error.chars().take(300).collect()),
},
);
}
} }
#[async_trait] #[async_trait]
impl BackgroundService for AcmeService { impl BackgroundService for AcmeService {
async fn start(&self, mut shutdown: ShutdownWatch) { async fn start(&self, mut shutdown: ShutdownWatch) {
if self.rt.acme_hosts().is_empty() { let mut expiries = HashMap::new();
return; let mut retry = FIRST_RETRY;
let mut last: Option<std::time::Instant> = None;
loop {
// Reloads can come many times a second; ACME rounds at most every 5 s.
if let Some(l) = last
&& l.elapsed() < MIN_GAP
{
tokio::select! {
_ = tokio::time::sleep(MIN_GAP - l.elapsed()) => {}
_ = shutdown.changed() => return,
} }
}
last = Some(std::time::Instant::now());
let hosts = self.shared.current().acme_hosts();
let mut wait = CHECK_EVERY;
if !hosts.is_empty() {
let dir = self.dir(); let dir = self.dir();
if let Err(e) = std::fs::create_dir_all(&dir) { if let Err(e) = std::fs::create_dir_all(&dir) {
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display()); log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
return; } else {
} for h in hosts {
let mut expiries = HashMap::new(); if !expiries.contains_key(&h)
for h in self.rt.acme_hosts() { && let Some(e) = self.load_stored(&h)
if let Some(e) = self.load_stored(&h) { {
expiries.insert(h, e); expiries.insert(h, e);
} }
} }
let mut retry = FIRST_RETRY; wait = if self.round(&mut expiries).await {
loop {
let wait = if self.round(&mut expiries).await {
retry = FIRST_RETRY; retry = FIRST_RETRY;
CHECK_EVERY CHECK_EVERY
} else { } else {
@@ -280,8 +334,12 @@ impl BackgroundService for AcmeService {
retry = (retry * 2).min(MAX_RETRY); retry = (retry * 2).min(MAX_RETRY);
w w
}; };
}
}
// Woken early by a reload (new hosts) or a "try again" from control.
tokio::select! { tokio::select! {
_ = tokio::time::sleep(wait) => {} _ = tokio::time::sleep(wait) => {}
_ = self.shared.acme_wake.notified() => {}
_ = shutdown.changed() => return, _ = shutdown.changed() => return,
} }
} }
+345
View File
@@ -0,0 +1,345 @@
// 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 admin socket: a Unix socket (mode 0660, so only edge's user and group, i.e. control,
//! can connect; never a TCP port) speaking small JSON over HTTP/1.1.
//!
//! | Request | Does |
//! |:--|:--|
//! | `GET /v1/status` | config hash, trial, revocations, health per host and upstream, certificates |
//! | `POST /v1/reload` | reload the config file (refused while a trial runs) |
//! | `POST /v1/trial {confirm_within_secs, watch_hosts?, watch_every_secs?}` | serve the trial file until confirmed |
//! | `POST /v1/confirm {config_sha256}` | keep the running trial |
//! | `POST /v1/abort` | back to the config before the trial (idempotent) |
//! | `POST /v1/share-revocations/reload` | re-read the share-link revocation file |
//! | `POST /v1/acme/retry` | try Let's Encrypt again now |
//!
//! Bodies are at most 4 KiB with no unknown fields. Answers never carry a secret.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use bytes::Bytes;
use http_body_util::{BodyExt, Full, Limited};
use hyper::body::Incoming;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService;
use serde::Deserialize;
use serde_json::{Value, json};
use crate::shared::{AdminError, Shared, WatchSpec};
const MAX_BODY: usize = 4096;
/// Longest trial the admin socket accepts.
const MAX_TRIAL_SECS: u64 = 3600;
pub struct AdminSocket {
pub shared: Arc<Shared>,
pub path: PathBuf,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TrialBody {
confirm_within_secs: u64,
#[serde(default)]
watch_hosts: Vec<String>,
watch_every_secs: Option<u64>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfirmBody {
config_sha256: String,
}
type Resp = Response<Full<Bytes>>;
fn reply(status: StatusCode, v: Value) -> Resp {
let mut r = Response::new(Full::new(Bytes::from(v.to_string())));
*r.status_mut() = status;
r.headers_mut().insert(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static("application/json"),
);
r
}
fn error(status: StatusCode, message: impl std::fmt::Display) -> Resp {
reply(status, json!({ "error": message.to_string() }))
}
fn admin_error(e: AdminError) -> Resp {
match e {
AdminError::Refused(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
AdminError::Conflict(m) => error(StatusCode::CONFLICT, m),
}
}
/// The status document.
pub fn status(shared: &Shared) -> Value {
let rt = shared.current();
let mut hosts: Vec<&String> = rt.hosts.keys().collect();
hosts.sort();
let hosts: Vec<Value> = hosts
.into_iter()
.filter_map(|name| rt.hosts.get(name))
.map(|h| {
let name = &h.cfg.hostname;
let cert = match &h.cfg.tls {
ianitor_core::edge_config::EdgeTls::Files { .. } => json!({
"state": "ok",
"not_after": rt.file_cert_expiry.get(name),
"error": null,
}),
ianitor_core::edge_config::EdgeTls::Acme => match shared.cert_state(name) {
Some(c) => {
json!({ "state": c.state, "not_after": c.not_after, "error": c.error })
}
None => json!({ "state": "pending", "not_after": null, "error": null }),
},
};
json!({
"hostname": name,
"health_check": h.cfg.health_check.is_some(),
"upstreams": h.upstreams.iter().map(|u| json!({
"address": u.authority,
"healthy": u.healthy.load(std::sync::atomic::Ordering::Relaxed),
"checks": u.health.checks(),
})).collect::<Vec<_>>(),
"certificate": cert,
})
})
.collect();
let rev = shared.revocations();
json!({
"generation": shared.generation(),
"config_sha256": rt.sha256,
"started_at": shared.started_at,
"trial": shared.trial_info().map(|(sha, left, prev)| json!({
"config_sha256": sha,
"seconds_left": left,
"previous_sha256": prev,
})),
"share_revocations": {
"loaded": rev.loaded,
"epoch": rev.revocations.epoch,
"stopped": rev.revocations.deny.len(),
"error": rev.error,
},
"hosts": hosts,
})
}
async fn body<T: for<'de> Deserialize<'de>>(
req: Request<Incoming>,
) -> Result<Option<T>, Box<Resp>> {
let bytes = Limited::new(req.into_body(), MAX_BODY)
.collect()
.await
.map_err(|_| {
error(
StatusCode::PAYLOAD_TOO_LARGE,
"the body is larger than 4 KiB",
)
})?
.to_bytes();
if bytes.is_empty() {
return Ok(None);
}
serde_json::from_slice(&bytes)
.map(Some)
.map_err(|e| Box::new(error(StatusCode::BAD_REQUEST, format!("bad body: {e}"))))
}
async fn handle(shared: Arc<Shared>, req: Request<Incoming>) -> Resp {
let method = req.method().clone();
let path = req.uri().path().to_owned();
match (method.as_str(), path.as_str()) {
("GET", "/v1/status") => reply(StatusCode::OK, status(&shared)),
("POST", "/v1/reload") => {
let r = tokio::task::spawn_blocking({
let s = shared.clone();
move || s.reload()
})
.await;
match r {
Ok(Ok(rt)) => reply(
StatusCode::OK,
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
),
Ok(Err(e)) => admin_error(e),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
}
}
("POST", "/v1/trial") => {
let b: TrialBody = match body(req).await {
Ok(Some(b)) => b,
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
Err(r) => return *r,
};
if !(1..=MAX_TRIAL_SECS).contains(&b.confirm_within_secs) {
return error(
StatusCode::BAD_REQUEST,
"confirm_within_secs must be between 1 and 3600",
);
}
let every = b.watch_every_secs.unwrap_or(5);
if !(1..=60).contains(&every) || b.watch_hosts.len() > 1000 {
return error(StatusCode::BAD_REQUEST, "watch_every_secs must be 1 to 60");
}
let watch = (!b.watch_hosts.is_empty()).then(|| WatchSpec {
hosts: b.watch_hosts,
every: Duration::from_secs(every),
});
let within = Duration::from_secs(b.confirm_within_secs);
let r = tokio::task::spawn_blocking({
let s = shared.clone();
move || s.start_trial(within, watch)
})
.await;
match r {
Ok(Ok((id, rt))) => {
let s = shared.clone();
tokio::spawn(async move {
if let Some(deadline) = s.trial_deadline(id) {
tokio::time::sleep_until(deadline.into()).await;
s.expire_trial(id);
}
});
reply(
StatusCode::OK,
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
)
}
Ok(Err(e)) => admin_error(e),
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
}
}
("POST", "/v1/confirm") => {
let b: ConfirmBody = match body(req).await {
Ok(Some(b)) => b,
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
Err(r) => return *r,
};
match shared.confirm(&b.config_sha256) {
Ok(()) => reply(StatusCode::OK, json!({ "confirmed": true })),
Err(e) => admin_error(e),
}
}
("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();
reply(
StatusCode::OK,
json!({ "epoch": r.revocations.epoch, "stopped": r.revocations.deny.len() }),
)
}
Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
},
("POST", "/v1/acme/retry") => {
shared.acme_wake.notify_one();
reply(StatusCode::OK, json!({ "retrying": true }))
}
(_, "/v1/status" | "/v1/reload" | "/v1/trial" | "/v1/confirm" | "/v1/abort") => {
error(StatusCode::METHOD_NOT_ALLOWED, "method not allowed")
}
_ => error(StatusCode::NOT_FOUND, "no such admin request"),
}
}
fn bind(path: &Path) -> std::io::Result<tokio::net::UnixListener> {
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
// A socket left over from a previous run is removed; anything else at the path is not.
if let Ok(meta) = std::fs::symlink_metadata(path) {
if meta.file_type().is_socket() {
std::fs::remove_file(path)?;
} else {
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
format!("{} exists and is not a socket", path.display()),
));
}
}
// Bind inside a fresh 0700 directory, set the mode, then move the socket into place, so
// there is no moment in which the socket exists with the process umask's permissions.
use std::os::unix::fs::DirBuilderExt;
let parent = path.parent().unwrap_or(Path::new("."));
let private = parent.join(format!(".ianitor-admin-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&private);
std::fs::DirBuilder::new().mode(0o700).create(&private)?;
let staged = private.join("admin.sock");
let bound = tokio::net::UnixListener::bind(&staged).and_then(|l| {
std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o660))?;
std::fs::rename(&staged, path)?;
Ok(l)
});
let _ = std::fs::remove_dir_all(&private);
bound
}
#[async_trait]
impl BackgroundService for AdminSocket {
async fn start(&self, mut shutdown: ShutdownWatch) {
let listener = match bind(&self.path) {
Ok(l) => l,
Err(e) => {
log::error!(target: "ianitor::admin", "cannot listen on {}: {e}; control cannot reach edge", self.path.display());
return;
}
};
log::info!(target: "ianitor::admin", "admin socket at {}", self.path.display());
loop {
tokio::select! {
_ = shutdown.changed() => break,
a = listener.accept() => {
let Ok((stream, _)) = a else { continue };
let shared = self.shared.clone();
tokio::spawn(async move {
let svc = service_fn(move |req| {
let shared = shared.clone();
async move { Ok::<_, std::convert::Infallible>(handle(shared, req).await) }
});
let _ = http1::Builder::new()
.serve_connection(TokioIo::new(stream), svc)
.await;
});
}
}
}
let _ = std::fs::remove_file(&self.path);
}
}
/// Re-reads the share-link revocation file when it changes (every 5 s), so a stopped link
/// stops even if control's reload request was lost.
pub struct RevocationPoller {
pub shared: Arc<Shared>,
}
#[async_trait]
impl BackgroundService for RevocationPoller {
async fn start(&self, mut shutdown: ShutdownWatch) {
loop {
tokio::select! {
_ = shutdown.changed() => return,
_ = tokio::time::sleep(Duration::from_secs(5)) => {
self.shared.poll_revocations();
self.shared.poll_device_trust();
}
}
}
}
}
+182 -43
View File
@@ -4,57 +4,153 @@
//! Active health checks, like Caddy's `health_checks.active`: `GET <path>` with the upstream //! Active health checks, like Caddy's `health_checks.active`: `GET <path>` with the upstream
//! address as Host, healthy on 2xx, 5 s timeout, one result flips the state. The first round //! address as Host, healthy on 2xx, 5 s timeout, one result flips the state. The first round
//! runs at startup; upstreams start healthy. //! runs when a config is loaded; upstreams start healthy.
//!
//! Every result is also recorded (time, latency, why it failed) for the admin socket.
//! During a trial, the watched hosts are probed at least every `every` seconds; a watched
//! host without a health check gets `GET /` with its own hostname as Host, and any answer
//! below 500 counts as alive (docs/ui-api.md G3). Those watch probes never change routing.
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
use std::time::Duration; use std::time::{Duration, Instant};
use async_trait::async_trait; use async_trait::async_trait;
use pingora::connectors::http::Connector; use pingora::connectors::http::Connector;
use pingora::http::RequestHeader; use pingora::http::RequestHeader;
use pingora::server::ShutdownWatch; use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService; use pingora::services::background::BackgroundService;
use pingora::{Error, ErrorType};
use crate::fetch::fetch; use crate::fetch::fetch;
use crate::runtime::{HostRt, Runtime, UpstreamRt}; use crate::logging::now_secs;
use crate::runtime::{Check, HostRt, UpstreamRt};
use crate::shared::Shared;
const TIMEOUT: Duration = Duration::from_secs(5); const TIMEOUT: Duration = Duration::from_secs(5);
pub struct HealthChecks { pub struct HealthChecks {
pub rt: Arc<Runtime>, pub shared: Arc<Shared>,
} }
async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool { /// Why a probe failed, in the words of docs/ui-api.md §3.3.
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else { pub fn failure_kind(e: &Error) -> &'static str {
return false; match e.etype() {
ErrorType::ConnectRefused | ErrorType::ConnectError | ErrorType::ConnectionClosed => {
"refused"
}
ErrorType::ConnectTimedout
| ErrorType::ReadTimedout
| ErrorType::WriteTimedout
| ErrorType::TLSHandshakeTimedout => "timeout",
ErrorType::ConnectNoRoute => "name",
ErrorType::TLSHandshakeFailure | ErrorType::InvalidCert | ErrorType::HandshakeError => {
"tls"
}
_ => "bad_answer",
}
}
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",
}
}
/// One probe. `watch` probes count any answer below 500 as alive.
async fn probe(
connector: &Connector,
u: &UpstreamRt,
path: &str,
host: &str,
watch: bool,
) -> Check {
let started = Instant::now();
let at = now_secs() as u64;
let source = if watch { "watch" } else { "health_check" };
let fail = |kind: &'static str, status: Option<u16>, latency: Option<u64>| Check {
seq: 0,
at,
ok: false,
source,
kind: Some(kind),
status,
latency_ms: latency,
}; };
if req let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
.insert_header(http::header::HOST, u.authority.as_str()) return fail("bad_answer", None, None);
.is_err() };
{ if req.insert_header(http::header::HOST, host).is_err() {
return false; return fail("bad_answer", None, None);
} }
match fetch(connector, u, req, 64 * 1024, TIMEOUT).await { match fetch(connector, u, req, 64 * 1024, TIMEOUT).await {
Ok(f) => f.header.status.is_success(), Ok(f) => {
Err(_) => false, let status = f.header.status.as_u16();
let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
let ok = if watch {
(100..500).contains(&status)
} else {
f.header.status.is_success()
};
if ok {
Check {
seq: 0,
at,
ok: true,
source,
kind: None,
status: Some(status),
latency_ms: Some(latency),
}
} else {
fail(status_kind(status), Some(status), Some(latency))
}
}
Err(e) => fail(failure_kind(&e), None, None),
} }
} }
/// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a /// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a
/// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of /// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of
/// ending health checks. /// ending health checks.
async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>) { async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>, watch: bool) {
for i in 0..host.upstreams.len() { for i in 0..host.upstreams.len() {
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone()); let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
let ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await { let probe_host = if watch {
Ok(ok) => ok, host.cfg.hostname.clone()
} else {
host.upstreams[i].authority.clone()
};
let check = match tokio::spawn(async move {
probe(&c, &h.upstreams[i], &p, &probe_host, watch).await
})
.await
{
Ok(c) => c,
Err(e) => { Err(e) => {
log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority); log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority);
false Check {
seq: 0,
at: now_secs() as u64,
ok: false,
source: if watch { "watch" } else { "health_check" },
kind: Some("bad_answer"),
status: None,
latency_ms: None,
}
} }
}; };
let u = &host.upstreams[i]; let u = &host.upstreams[i];
let ok = check.ok;
u.health.record(check);
if watch {
// Watch probes only report; routing follows the host's own health check.
continue;
}
if u.healthy.swap(ok, Ordering::Relaxed) != ok { if u.healthy.swap(ok, Ordering::Relaxed) != ok {
if ok { if ok {
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority); log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
@@ -65,50 +161,93 @@ async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>) {
} }
} }
async fn watch(host: Arc<HostRt>, path: String, every: Duration) { async fn watcher(host: Arc<HostRt>, path: String, every: Duration, watch: bool) {
let connector = Arc::new(Connector::new(None)); let connector = Arc::new(Connector::new(None));
loop { loop {
round(&host, &path, &connector).await; round(&host, &path, &connector, watch).await;
tokio::time::sleep(every).await; tokio::time::sleep(every).await;
} }
} }
struct Job {
host: Arc<HostRt>,
path: String,
every: Duration,
watch: bool,
}
fn jobs(shared: &Shared) -> Vec<Job> {
let rt = shared.current();
let spec = shared.watch_spec();
let watched = |h: &str| {
spec.as_ref()
.is_some_and(|s| s.hosts.iter().any(|w| w == h))
};
let every = spec.as_ref().map(|s| s.every);
let mut out = Vec::new();
for h in rt.hosts.values() {
let name = &h.cfg.hostname;
match &h.cfg.health_check {
Some(hc) => {
let mut interval = Duration::from_secs(u64::from(hc.interval_secs.max(1)));
if watched(name)
&& let Some(e) = every
{
interval = interval.min(e);
}
out.push(Job {
host: h.clone(),
path: hc.path.clone(),
every: interval,
watch: false,
});
}
None if watched(name) => out.push(Job {
host: h.clone(),
path: "/".into(),
every: every.unwrap_or(Duration::from_secs(5)),
watch: true,
}),
None => {}
}
}
out
}
#[async_trait] #[async_trait]
impl BackgroundService for HealthChecks { impl BackgroundService for HealthChecks {
async fn start(&self, mut shutdown: ShutdownWatch) { async fn start(&self, mut shutdown: ShutdownWatch) {
let checked: Vec<(Arc<HostRt>, String, Duration)> = self let mut changes = self.shared.subscribe();
.rt loop {
.hosts let jobs = jobs(&self.shared);
.values()
.filter_map(|h| {
h.cfg.health_check.as_ref().map(|hc| {
(
h.clone(),
hc.path.clone(),
Duration::from_secs(u64::from(hc.interval_secs.max(1))),
)
})
})
.collect();
let mut tasks = tokio::task::JoinSet::new(); let mut tasks = tokio::task::JoinSet::new();
let mut which = std::collections::HashMap::new(); let mut which = std::collections::HashMap::new();
for (i, (h, p, every)) in checked.iter().enumerate() { for (i, j) in jobs.iter().enumerate() {
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); let id = tasks
.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch))
.id();
which.insert(id, i);
} }
// A watcher never returns; if one ends anyway, say so and start it again. // Run until the config or the watch changes; a watcher never returns, and if one
loop { // ends anyway, say so and start it again.
let stop = loop {
tokio::select! { tokio::select! {
_ = shutdown.changed() => break, _ = shutdown.changed() => break true,
r = changes.changed() => break r.is_err(),
Some(done) = tasks.join_next_with_id() => { Some(done) = tasks.join_next_with_id() => {
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() }; let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
if let Some(i) = which.remove(&id) { if let Some(i) = which.remove(&id) {
let (h, p, every) = &checked[i]; let j = &jobs[i];
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname); log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", j.host.cfg.hostname);
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); which.insert(tasks.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch)).id(), i);
}
} }
} }
} }
};
tasks.abort_all(); tasks.abort_all();
if stop {
return;
}
}
} }
} }
+6 -5
View File
@@ -19,10 +19,10 @@ use pingora::server::ShutdownWatch;
use crate::acme::Challenges; use crate::acme::Challenges;
use crate::logging::{AccessRecord, now_secs, truncate_ip}; use crate::logging::{AccessRecord, now_secs, truncate_ip};
use crate::proxy::{host_header, hostname}; use crate::proxy::{host_header, hostname};
use crate::runtime::Runtime; use crate::shared::Shared;
pub struct HttpApp { pub struct HttpApp {
pub rt: Arc<Runtime>, pub shared: Arc<Shared>,
pub challenges: Arc<Challenges>, pub challenges: Arc<Challenges>,
} }
@@ -75,6 +75,7 @@ impl HttpServerApp for HttpApp {
impl HttpApp { impl HttpApp {
async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> { async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> {
let start = Instant::now(); let start = Instant::now();
let rt = self.shared.current();
let req = session.req_header(); let req = session.req_header();
let hh = host_header(req); let hh = host_header(req);
let name = hostname(&hh); let name = hostname(&hh);
@@ -92,11 +93,11 @@ impl HttpApp {
return r; return r;
} }
let Some(host) = self.rt.host(&name) else { let Some(host) = rt.host(&name) else {
return empty(StatusCode::NOT_FOUND); return empty(StatusCode::NOT_FOUND);
}; };
let uri = req.uri.path_and_query().map_or("/", |p| p.as_str()); let uri = req.uri.path_and_query().map_or("/", |p| p.as_str());
let port = self.rt.cfg.https_port; let port = rt.cfg.https_port;
let location = if port == 443 { let location = if port == 443 {
format!("https://{name}{uri}") format!("https://{name}{uri}")
} else { } else {
@@ -110,7 +111,7 @@ impl HttpApp {
Err(_) => return empty(StatusCode::BAD_REQUEST), Err(_) => return empty(StatusCode::BAD_REQUEST),
} }
if host.cfg.access_log if host.cfg.access_log
&& let Some(log) = &self.rt.access_log && let Some(log) = &rt.access_log
{ {
log.write(&AccessRecord { log.write(&AccessRecord {
ts: now_secs(), ts: now_secs(),
+90 -16
View File
@@ -5,23 +5,29 @@
//! Ianitor edge: the Pingora data plane. It reads the config compiled by `ianitor-core` //! Ianitor edge: the Pingora data plane. It reads the config compiled by `ianitor-core`
//! and serves it; it never decides policy. //! and serves it; it never decides policy.
//! //!
//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, websockets, header rules, //! Services: HTTPS reverse proxy (SNI certificates, forward-auth, share links, websockets,
//! round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and redirects), //! header rules, round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and
//! health checks, ACME issuance and renewal. //! redirects), health checks, ACME issuance and renewal, and the admin socket through which
//! control reloads the config in process (see `shared`).
pub mod acme; pub mod acme;
#[cfg(unix)]
pub mod admin;
pub mod error; pub mod error;
pub mod fetch; pub mod fetch;
pub mod forward_auth; pub mod forward_auth;
pub mod health; pub mod health;
pub mod http_app; pub mod http_app;
pub mod logging; pub mod logging;
pub mod pages;
pub mod proxy; pub mod proxy;
pub mod runtime; pub mod runtime;
pub mod secrets; pub mod secrets;
pub mod share;
pub mod shared;
pub mod tls; pub mod tls;
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use pingora::connectors::http::Connector; use pingora::connectors::http::Connector;
@@ -34,24 +40,67 @@ use pingora::services::listening::Service;
pub use error::EdgeError; pub use error::EdgeError;
pub use runtime::Runtime; pub use runtime::Runtime;
pub use shared::Shared;
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct Options { pub struct Options {
/// The compiled edge config (`ianitor-core` edge compiler output). /// The compiled edge config (`ianitor-core` edge compiler output).
pub config: PathBuf, pub config: PathBuf,
/// The trial config control writes before an apply; default `<config>.trial`.
pub trial_config: Option<PathBuf>,
/// Admin socket for control (Unix only); none when `None`.
pub admin_socket: Option<PathBuf>,
/// The share-link revocation file control writes; without it, share links are refused.
pub share_revocations: Option<PathBuf>,
/// Extra trust root for the ACME directory's TLS (Pebble in tests). /// Extra trust root for the ACME directory's TLS (Pebble in tests).
pub acme_root: Option<PathBuf>, pub acme_root: Option<PathBuf>,
/// Overrides `$CREDENTIALS_DIRECTORY` (tests running several edges in one process).
pub credentials_dir: Option<PathBuf>,
}
impl Options {
pub fn trial_path(&self) -> PathBuf {
self.trial_config
.clone()
.unwrap_or_else(|| default_trial_path(&self.config))
}
}
/// `<config>.trial`, next to the config.
pub fn default_trial_path(config: &Path) -> PathBuf {
let mut name = config.file_name().unwrap_or_default().to_os_string();
name.push(".trial");
config.with_file_name(name)
}
fn credentials_dir(opts: &Options) -> Option<PathBuf> {
opts.credentials_dir
.clone()
.or_else(|| std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from))
} }
/// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates. /// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates.
pub fn prepare(opts: &Options) -> Result<Arc<Runtime>, EdgeError> { pub fn prepare(opts: &Options) -> Result<Arc<Shared>, EdgeError> {
let cfg = runtime::read_config(&opts.config)?; let creds = credentials_dir(opts);
let creds = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from); let rt = runtime::build_file(&opts.config, creds.as_deref())?;
runtime::build(cfg, creds.as_deref()).map(Arc::new) Ok(shared_for(rt, opts))
}
/// Wrap an already built runtime (tests run edge in process this way).
pub fn shared_for(rt: Runtime, opts: &Options) -> Arc<Shared> {
Shared::new(
rt,
shared::Paths {
config: opts.config.clone(),
trial: opts.trial_path(),
revocations: opts.share_revocations.clone(),
},
credentials_dir(opts),
)
} }
/// Assemble the Pingora server with all services. Listeners bind when it runs. /// Assemble the Pingora server with all services. Listeners bind when it runs.
pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> { pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError> {
pingora::tls::install_default_crypto_provider(); pingora::tls::install_default_crypto_provider();
let conf = ServerConf { let conf = ServerConf {
threads: 2, threads: 2,
@@ -63,26 +112,32 @@ pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
server.bootstrap(); server.bootstrap();
let challenges = Arc::new(acme::Challenges::default()); let challenges = Arc::new(acme::Challenges::default());
let rt = shared.current();
let mut https = http_proxy_service( let mut https = http_proxy_service(
&server.configuration, &server.configuration,
proxy::EdgeProxy { proxy::EdgeProxy {
rt: rt.clone(), shared: shared.clone(),
connector: Connector::new(None), connector: Connector::new(None),
}, },
); );
let mut tls = TlsSettings::intermediate("", "").map_err(|e| EdgeError::Listen { let mut tls =
TlsSettings::with_callbacks(Box::new(tls::SniRecorder)).map_err(|e| EdgeError::Listen {
address: rt.cfg.https_listen.clone(), address: rt.cfg.https_listen.clone(),
reason: e.to_string(), reason: e.to_string(),
})?; })?;
tls.set_cert_resolver(rt.certs.clone()); tls.set_cert_resolver(shared.certs.clone());
tls.set_client_cert_verifier(shared.devices.clone());
tls.enable_h2(); tls.enable_h2();
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls); 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( let mut http = Service::new(
"ianitor http".to_owned(), "ianitor http".to_owned(),
http_app::HttpApp { http_app::HttpApp {
rt: rt.clone(), shared: shared.clone(),
challenges: challenges.clone(), challenges: challenges.clone(),
}, },
); );
@@ -92,17 +147,36 @@ pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
server.add_service(http); server.add_service(http);
server.add_service(background_service( server.add_service(background_service(
"ianitor health checks", "ianitor health checks",
health::HealthChecks { rt: rt.clone() }, health::HealthChecks {
shared: shared.clone(),
},
)); ));
server.add_service(background_service( server.add_service(background_service(
"ianitor acme", "ianitor acme",
acme::AcmeService { acme::AcmeService {
rt: rt.clone(), shared: shared.clone(),
certs: rt.certs.clone(),
challenges, challenges,
ca_root: opts.acme_root.clone(), ca_root: opts.acme_root.clone(),
}, },
)); ));
#[cfg(unix)]
{
server.add_service(background_service(
"ianitor share revocations",
admin::RevocationPoller {
shared: shared.clone(),
},
));
if let Some(path) = &opts.admin_socket {
server.add_service(background_service(
"ianitor admin socket",
admin::AdminSocket {
shared: shared.clone(),
path: path.clone(),
},
));
}
}
Ok(server) Ok(server)
} }
+10 -5
View File
@@ -2,7 +2,8 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this // 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/. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! `ianitor-edge --config <edge.json> [--check] [--acme-root <ca.pem>]` //! `ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] [--trial-config <path>]
//! [--share-revocations <path>] [--acme-root <ca.pem>]`
//! //!
//! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG` //! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG`
//! (error, warn, info, debug, trace; libraries are capped at info). //! (error, warn, info, debug, trace; libraries are capped at info).
@@ -21,10 +22,14 @@ fn parse_args() -> Result<(Options, bool), EdgeError> {
match a.to_str() { match a.to_str() {
Some("--config") => config = args.next().map(PathBuf::from), Some("--config") => config = args.next().map(PathBuf::from),
Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from), Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from),
Some("--admin-socket") => opts.admin_socket = args.next().map(PathBuf::from),
Some("--trial-config") => opts.trial_config = args.next().map(PathBuf::from),
Some("--share-revocations") => opts.share_revocations = args.next().map(PathBuf::from),
Some("--check") => check = true, Some("--check") => check = true,
Some("--help" | "-h") => { Some("--help" | "-h") => {
println!( println!(
"usage: ianitor-edge --config <edge.json> [--check] [--acme-root <ca.pem>]" "usage: ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] \
[--trial-config <path>] [--share-revocations <path>] [--acme-root <ca.pem>]"
); );
std::process::exit(0); std::process::exit(0);
} }
@@ -44,12 +49,12 @@ fn parse_args() -> Result<(Options, bool), EdgeError> {
fn main() -> ExitCode { fn main() -> ExitCode {
ianitor_edge::logging::init(std::env::var("IANITOR_LOG").ok().as_deref()); ianitor_edge::logging::init(std::env::var("IANITOR_LOG").ok().as_deref());
let started = parse_args().and_then(|(opts, check)| { let started = parse_args().and_then(|(opts, check)| {
let rt = ianitor_edge::prepare(&opts)?; let shared = ianitor_edge::prepare(&opts)?;
log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), rt.hosts.len()); log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), shared.current().hosts.len());
if check { if check {
return Ok(None); return Ok(None);
} }
ianitor_edge::server(rt, &opts).map(Some) ianitor_edge::server(shared, &opts).map(Some)
}); });
match started { match started {
Ok(None) => ExitCode::SUCCESS, Ok(None) => ExitCode::SUCCESS,
+211
View File
@@ -0,0 +1,211 @@
// 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 share-link visitor pages (docs/ui-api.md §4): one self-contained HTML page each, inline
//! CSS, no JavaScript, no external requests, under 8 KB. Only the hostname and a date come
//! from the request side, both escaped; the token is echoed only into the password form's
//! hidden field (it is already in the visitor's address bar at that point), escaped too.
use ianitor_core::share::PASSWORD_PATH;
use ianitor_core::time::long_date;
pub enum Problem {
WrongPassword,
TooMany,
}
pub enum Page<'a> {
Password {
host: &'a str,
token: &'a str,
until: u64,
problem: Option<Problem>,
},
Expired {
host: &'a str,
until: u64,
},
Invalid {
host: &'a str,
},
}
impl Page<'_> {
pub fn status(&self) -> u16 {
match self {
Page::Password {
problem: Some(Problem::TooMany),
..
} => 429,
Page::Password { .. } => 401,
Page::Expired { .. } => 410,
Page::Invalid { .. } => 403,
}
}
}
pub fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
c if c.is_control() => {}
c => out.push(c),
}
}
out
}
const STYLE: &str = "\
*{box-sizing:border-box}\
body{margin:0;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;\
background:#0c0b0f;color:#f1edf3;font-family:system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;padding:16px}\
.card{width:100%;max-width:420px;padding:32px;background:#18151d;border:1px solid #3c3445;border-radius:18px}\
@media (max-width:480px){.card{padding:24px}}\
.host{color:#cfc6d4;font-size:.95rem;font-weight:600;margin:0 0 16px;overflow-wrap:anywhere}\
svg{display:block;margin:0 0 12px}\
h1{font-size:1.5rem;font-weight:700;color:#f1edf3;margin:0 0 8px}\
p{font-size:1rem;line-height:1.5;color:#cfc6d4;margin:0 0 16px}\
label{display:block;color:#cfc6d4;font-size:.9rem;margin:0 0 6px}\
input[type=password]{width:100%;height:48px;background:#0c0b0f;border:1px solid #7d7189;border-radius:10px;\
color:#f1edf3;font-size:1rem;padding:0 12px}\
input[type=password]:focus{outline:none;border-color:#e0a3dc;box-shadow:0 0 0 4px rgba(224,163,220,.16)}\
.err{color:#e2683a;font-size:.92rem;margin:8px 0 0;display:flex;gap:6px;align-items:center}\
button{margin-top:16px;width:100%;height:48px;border-radius:12px;border:1px solid #c77cc1;color:#fff;font-weight:700;\
font-size:1rem;background:linear-gradient(#8d3b89,#76306f 55%,#5c2257)}\
button:focus{outline:2px solid #f2c9ee;outline-offset:2px}\
button:disabled{opacity:.5}\
.small{font-size:.92rem;margin:16px 0 0}\
a{color:#e0a3dc;display:inline-flex;align-items:center;min-height:44px}\
footer{color:#a99eb1;font-size:.72rem;letter-spacing:.2em;text-transform:uppercase;margin-top:16px}";
fn icon(kind: &str) -> String {
let (colour, body) = match kind {
// lock
"lock" => (
"#e0a3dc",
"<rect x=\"8\" y=\"18\" width=\"24\" height=\"16\" rx=\"3\"/><path d=\"M13 18v-5a7 7 0 0 1 14 0v5\"/>",
),
// clock
"clock" => (
"#d99a35",
"<circle cx=\"20\" cy=\"20\" r=\"14\"/><path d=\"M20 12v8l5 4\"/>",
),
// broken link
_ => (
"#d99a35",
"<path d=\"M17 23l-3 3a5 5 0 0 1-7-7l3-3\"/><path d=\"M23 17l3-3a5 5 0 0 0-7-7l-3 3\"/><path d=\"M8 8l3 3M29 29l3 3M28 12h4M8 28H12\"/>",
),
};
format!(
"<svg width=\"40\" height=\"40\" viewBox=\"0 0 40 40\" fill=\"none\" stroke=\"{colour}\" stroke-width=\"2.2\" \
stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">{body}</svg>"
)
}
const RING: &str = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\" fill=\"none\" stroke=\"#e2683a\" stroke-width=\"2\" aria-hidden=\"true\"><circle cx=\"7\" cy=\"7\" r=\"5\"/></svg>";
fn shell(host: &str, inner: &str, title: &str) -> String {
format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
<meta name=\"referrer\" content=\"no-referrer\"><meta name=\"robots\" content=\"noindex\">\
<title>{title}</title><style>{STYLE}</style></head><body><main class=\"card\">\
<p class=\"host\">{}</p>{inner}</main><footer>Ianitor Domi</footer></body></html>",
escape(host)
)
}
pub fn render(p: &Page<'_>) -> String {
match p {
Page::Password {
host,
token,
until,
problem,
} => {
let h = escape(host);
let (msg, disabled) = match problem {
Some(Problem::WrongPassword) => (
format!(
"<p class=\"err\" role=\"alert\">{RING}That password is not right. Check it with the person who sent the link.</p>"
),
"",
),
Some(Problem::TooMany) => (
format!(
"<p class=\"err\" role=\"alert\">{RING}Too many tries. Wait a minute, then try again.</p>"
),
" disabled",
),
None => (String::new(), ""),
};
let inner = format!(
"{}<h1>This link is protected</h1>\
<p>Someone shared {h} with you. Enter the password they gave you.</p>\
<form method=\"post\" action=\"{PASSWORD_PATH}\">\
<input type=\"hidden\" name=\"t\" value=\"{}\">\
<label for=\"pw\">Password</label>\
<input id=\"pw\" type=\"password\" name=\"password\" autocomplete=\"current-password\" autofocus required>\
{msg}<button type=\"submit\"{disabled}>Open</button></form>\
<p class=\"small\">The link works until {}.</p>",
icon("lock"),
escape(token),
long_date(*until)
);
shell(host, &inner, "This link is protected")
}
Page::Expired { host, until } => {
let inner = format!(
"{}<h1>This link has expired</h1>\
<p>It worked until {}. Ask the person who sent it for a new one.</p>\
<a href=\"/\">Have an account? Sign in</a>",
icon("clock"),
long_date(*until)
);
shell(host, &inner, "This link has expired")
}
Page::Invalid { host } => {
let inner = format!(
"{}<h1>This link no longer works</h1>\
<p>It may have been stopped, or not copied in full. Ask the person who sent it for a new one.</p>\
<a href=\"/\">Have an account? Sign in</a>",
icon("broken")
);
shell(host, &inner, "This link no longer works")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pages_are_small_and_escaped() {
for p in [
Page::Password {
host: "<b>x</b>",
token: "\"><script>",
until: 1_794_666_000,
problem: Some(Problem::WrongPassword),
},
Page::Expired {
host: "a.test",
until: 0,
},
Page::Invalid { host: "a.test" },
] {
let html = render(&p);
assert!(html.len() < 8 * 1024, "{}", html.len());
assert!(!html.contains("<script"));
assert!(!html.contains("<b>x"));
assert!(!html.contains("http://") && !html.contains("https://"));
}
}
}
+159 -14
View File
@@ -22,13 +22,17 @@ use crate::fetch;
use crate::forward_auth::{self, Outcome}; use crate::forward_auth::{self, Outcome};
use crate::logging::{AccessRecord, now_secs, truncate_ip}; use crate::logging::{AccessRecord, now_secs, truncate_ip};
use crate::runtime::{HostRt, Op, Runtime}; use crate::runtime::{HostRt, Op, Runtime};
use crate::share::{self, Decision};
use crate::shared::Shared;
pub struct EdgeProxy { pub struct EdgeProxy {
pub rt: Arc<Runtime>, pub shared: Arc<Shared>,
pub connector: Connector, pub connector: Connector,
} }
pub struct Ctx { pub struct Ctx {
/// The runtime current when the request started; used for the whole request.
rt: Option<Arc<Runtime>>,
host: Option<Arc<HostRt>>, host: Option<Arc<HostRt>>,
/// Chosen upstream and its resolved addresses; connect failures move to the next address. /// Chosen upstream and its resolved addresses; connect failures move to the next address.
upstream: Option<usize>, upstream: Option<usize>,
@@ -71,11 +75,46 @@ pub fn hostname(host_header: &str) -> String {
name.to_ascii_lowercase() name.to_ascii_lowercase()
} }
pub fn client_ip(session: &Session) -> Option<IpAddr> { /// 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 session
.client_addr() .client_addr()
.and_then(|a| a.as_inet()) .and_then(|a| a.as_inet())
.map(|a| a.ip()) .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. /// A response with an empty body, like Caddy's `static_response` and error responses.
@@ -113,6 +152,7 @@ impl ProxyHttp for EdgeProxy {
fn new_ctx(&self) -> Ctx { fn new_ctx(&self) -> Ctx {
Ctx { Ctx {
rt: None,
host: None, host: None,
upstream: None, upstream: None,
addrs: Vec::new(), addrs: Vec::new(),
@@ -123,15 +163,65 @@ impl ProxyHttp for EdgeProxy {
} }
async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result<bool> { async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result<bool> {
let rt = self.shared.current();
ctx.rt = Some(rt.clone());
ctx.host_header = host_header(session.req_header()); ctx.host_header = host_header(session.req_header());
let Some(host) = self.rt.host(&hostname(&ctx.host_header)).cloned() else { 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?; respond_empty(session, 404).await?;
return Ok(true); return Ok(true);
}; };
ctx.host = Some(host.clone()); 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, &rt.trusted_proxies);
let revs = self.shared.revocations();
match share::handle(
session,
&host.cfg.hostname,
rt.share_key.as_deref(),
&revs,
&self.shared.throttle,
ip,
)
.await?
{
Decision::Answered => return Ok(true),
Decision::Allowed => shared_access = true,
Decision::Continue => {}
}
}
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 { if host.cfg.forward_auth {
let fa = self.rt.forward_auth.as_ref().ok_or_else(|| { let fa = rt.forward_auth.as_ref().ok_or_else(|| {
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured") Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
})?; })?;
// Client-sent identity headers never survive, whatever copy_headers says. // Client-sent identity headers never survive, whatever copy_headers says.
@@ -139,7 +229,11 @@ impl ProxyHttp for EdgeProxy {
for name in &fa.strip_headers { for name in &fa.strip_headers {
req.remove_header(name); req.remove_header(name);
} }
let ip = client_ip(session).map(|i| i.to_string()); if shared_access {
// 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, &rt.trusted_proxies).map(|i| i.to_string());
let outcome = match forward_auth::check( let outcome = match forward_auth::check(
&self.connector, &self.connector,
fa, fa,
@@ -180,11 +274,7 @@ impl ProxyHttp for EdgeProxy {
} }
} }
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) { self.after_auth(session, &host).await
respond_empty(session, 403).await?;
return Ok(true);
}
Ok(false)
} }
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> { async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
@@ -267,7 +357,12 @@ impl ProxyHttp for EdgeProxy {
} }
req.insert_header(header::HOST, ctx.host_header.as_str())?; req.insert_header(header::HOST, ctx.host_header.as_str())?;
// Forwarding headers are always edge's own; client-supplied values are replaced. // 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())?, Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
None => { None => {
req.remove_header("X-Forwarded-For"); req.remove_header("X-Forwarded-For");
@@ -350,7 +445,7 @@ impl ProxyHttp for EdgeProxy {
if !host.cfg.access_log { if !host.cfg.access_log {
return; return;
} }
let Some(log) = &self.rt.access_log else { let Some(log) = ctx.rt.as_ref().and_then(|rt| rt.access_log.as_ref()) else {
return; return;
}; };
let req = session.req_header(); let req = session.req_header();
@@ -360,7 +455,13 @@ impl ProxyHttp for EdgeProxy {
method: req.method.as_str(), method: req.method.as_str(),
path: req.uri.path(), path: req.uri.path(),
status: session.response_written().map_or(0, |r| r.status.as_u16()), 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), duration_ms: u64::try_from(ctx.start.elapsed().as_millis()).unwrap_or(u64::MAX),
}); });
} }
@@ -372,6 +473,42 @@ impl ProxyHttp for EdgeProxy {
} }
} }
impl EdgeProxy {
/// The steps after the sign-in check: websocket refusal.
async fn after_auth(&self, session: &mut Session, host: &HostRt) -> Result<bool> {
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
respond_empty(session, 403).await?;
return Ok(true);
}
Ok(false)
}
}
/// 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 { pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle) !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
} }
@@ -380,6 +517,14 @@ pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
mod tests { mod tests {
use super::*; 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] #[test]
fn hostname_strips_port_and_case() { fn hostname_strips_port_and_case() {
assert_eq!(hostname("App.Test:8443"), "app.test"); assert_eq!(hostname("App.Test:8443"), "app.test");
+213 -17
View File
@@ -2,31 +2,81 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this // 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/. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The compiled edge config turned into ready-to-serve state: resolved upstream addresses, //! The compiled edge config turned into ready-to-serve state: parsed upstreams and header
//! parsed header names, secrets loaded, certificates loaded. Built once at startup. //! names, secrets loaded, certificates loaded, the share-link key loaded. Built at startup
//! and again on every reload; a reload swaps the whole [`Runtime`] at once (see `shared`).
use std::collections::{BTreeSet, HashMap}; use std::collections::{BTreeSet, HashMap, VecDeque};
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
use http::{HeaderName, HeaderValue}; use http::{HeaderName, HeaderValue};
use ianitor_core::edge_config::{ use ianitor_core::edge_config::{
EDGE_CONFIG_VERSION, EdgeConfig, EdgeHeaderOp, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue, EDGE_CONFIG_VERSION, EdgeConfig, EdgeHeaderOp, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
}; };
use ianitor_core::share::{KEY_CREDENTIAL, ShareKey};
use rustls::sign::CertifiedKey;
use serde::Serialize;
use crate::error::EdgeError; use crate::error::EdgeError;
use crate::logging::AccessLog; use crate::logging::AccessLog;
use crate::secrets::Secrets; use crate::secrets::Secrets;
use crate::tls::{CertStore, certified_key}; use crate::tls::{certified_key, not_after};
pub enum Op { pub enum Op {
Set(HeaderName, HeaderValue), Set(HeaderName, HeaderValue),
Remove(HeaderName), Remove(HeaderName),
} }
/// One health probe result, as reported on the admin socket.
#[derive(Debug, Clone, Serialize)]
pub struct Check {
/// Increases by one per probe of this upstream.
pub seq: u64,
/// Unix seconds.
pub at: u64,
pub ok: bool,
/// `health_check` (the host's own check) or `watch` (`GET /` during a trial).
pub source: &'static str,
/// `refused`, `timeout`, `name`, `tls`, `server_error`, `not_found`, `redirect`,
/// `sign_in` or `bad_answer`; `None` when `ok`.
pub kind: Option<&'static str>,
pub status: Option<u16>,
pub latency_ms: Option<u64>,
}
/// The last few probe results of one upstream.
#[derive(Default)]
pub struct HealthRecord {
inner: Mutex<(u64, VecDeque<Check>)>,
}
/// How many results are kept per upstream.
pub const KEPT_CHECKS: usize = 5;
impl HealthRecord {
pub fn record(&self, mut c: Check) {
if let Ok(mut g) = self.inner.lock() {
g.0 += 1;
c.seq = g.0;
g.1.push_back(c);
while g.1.len() > KEPT_CHECKS {
g.1.pop_front();
}
}
}
pub fn checks(&self) -> Vec<Check> {
self.inner
.lock()
.map(|g| g.1.iter().cloned().collect())
.unwrap_or_default()
}
}
pub struct UpstreamRt { pub struct UpstreamRt {
/// Host name or IP literal (IPv6 without brackets). /// Host name or IP literal (IPv6 without brackets).
pub host: String, pub host: String,
@@ -36,6 +86,7 @@ pub struct UpstreamRt {
pub tls: bool, pub tls: bool,
pub sni: String, pub sni: String,
pub healthy: AtomicBool, pub healthy: AtomicBool,
pub health: HealthRecord,
} }
pub struct HostRt { pub struct HostRt {
@@ -46,6 +97,9 @@ pub struct HostRt {
pub response_ops: Vec<Op>, pub response_ops: Vec<Op>,
/// Values of the secrets this host injects; a response header containing one is dropped. /// Values of the secrets this host injects; a response header containing one is dropped.
pub secret_values: Vec<Vec<u8>>, 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 { pub struct ForwardAuthRt {
@@ -61,7 +115,19 @@ pub struct Runtime {
pub hosts: HashMap<String, Arc<HostRt>>, pub hosts: HashMap<String, Arc<HostRt>>,
pub forward_auth: Option<ForwardAuthRt>, pub forward_auth: Option<ForwardAuthRt>,
pub access_log: Option<AccessLog>, pub access_log: Option<AccessLog>,
pub certs: Arc<CertStore>, /// Domi certificates (`tls = "domi"`), by hostname.
pub file_certs: HashMap<String, Arc<CertifiedKey>>,
/// `notAfter` (Unix seconds) of each Domi certificate.
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,
} }
impl Runtime { impl Runtime {
@@ -83,12 +149,45 @@ impl Runtime {
} }
} }
pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> { pub fn sha256_hex(data: &[u8]) -> String {
let text = std::fs::read_to_string(path).map_err(|source| EdgeError::Read { ring::digest::digest(&ring::digest::SHA256, data)
.as_ref()
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
/// Largest config file read.
const MAX_CONFIG_BYTES: u64 = 16 << 20;
/// Read and parse a config file; returns the parsed config and the SHA-256 of its bytes.
pub fn read_config_file(path: &Path) -> Result<(EdgeConfig, String), EdgeError> {
let read_err = |source| EdgeError::Read {
path: path.to_owned(), path: path.to_owned(),
source, source,
};
let meta = std::fs::metadata(path).map_err(read_err)?;
if meta.len() > MAX_CONFIG_BYTES {
return Err(EdgeError::Config {
path: path.to_owned(),
message: "the file is larger than 16 MiB".into(),
});
}
let bytes = std::fs::read(path).map_err(read_err)?;
let text = std::str::from_utf8(&bytes).map_err(|_| EdgeError::Config {
path: path.to_owned(),
message: "the file is not UTF-8".into(),
})?; })?;
let cfg: EdgeConfig = serde_json::from_str(&text).map_err(|e| EdgeError::Config { let cfg = parse_config(path, text)?;
Ok((cfg, sha256_hex(&bytes)))
}
pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
read_config_file(path).map(|(c, _)| c)
}
fn parse_config(path: &Path, text: &str) -> Result<EdgeConfig, EdgeError> {
let cfg: EdgeConfig = serde_json::from_str(text).map_err(|e| EdgeError::Config {
path: path.to_owned(), path: path.to_owned(),
message: e.to_string(), message: e.to_string(),
})?; })?;
@@ -125,6 +224,7 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
tls: u.tls, tls: u.tls,
sni: u.sni.clone(), sni: u.sni.clone(),
healthy: AtomicBool::new(true), healthy: AtomicBool::new(true),
health: HealthRecord::default(),
}) })
} }
@@ -221,10 +321,18 @@ fn ops(
.collect() .collect()
} }
/// Load secrets and certificates and resolve upstreams. Fails on the first problem; edge never /// Read, parse and build a config file. Fails on the first problem; edge never serves a
/// starts half-configured. /// half-built config.
pub fn build_file(path: &Path, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
let (cfg, sha) = read_config_file(path)?;
let mut rt = build(cfg, credentials_dir)?;
rt.sha256 = sha;
Ok(rt)
}
/// Load secrets, certificates and the share-link key. Fails on the first problem.
pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> { pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
let names: BTreeSet<String> = cfg let mut names: BTreeSet<String> = cfg
.hosts .hosts
.iter() .iter()
.flat_map(|h| h.request_headers.iter().chain(&h.response_headers)) .flat_map(|h| h.request_headers.iter().chain(&h.response_headers))
@@ -236,9 +344,23 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
_ => None, _ => None,
}) })
.collect(); .collect();
let wants_share = cfg.hosts.iter().any(|h| h.share_links);
if wants_share {
names.insert(KEY_CREDENTIAL.to_owned());
}
let secrets = Secrets::load(&names, credentials_dir)?; let secrets = Secrets::load(&names, credentials_dir)?;
let share_key = match secrets.get(KEY_CREDENTIAL) {
Some(s) if wants_share => Some(Arc::new(ShareKey::new(s.as_bytes()).map_err(|_| {
EdgeError::Secret {
name: KEY_CREDENTIAL.into(),
reason: "the share-link key must be at least 32 characters",
}
})?)),
_ => None,
};
let certs = Arc::new(CertStore::default()); let mut file_certs = HashMap::new();
let mut file_cert_expiry = HashMap::new();
let mut hosts = HashMap::new(); let mut hosts = HashMap::new();
for h in &cfg.hosts { for h in &cfg.hosts {
if let EdgeTls::Files { cert, key } = &h.tls { if let EdgeTls::Files { cert, key } = &h.tls {
@@ -248,16 +370,22 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
source, source,
}) })
}; };
let pair = let cert_pem = read(cert)?;
certified_key(&read(cert)?, &read(key)?).map_err(|reason| EdgeError::Cert { let pair = certified_key(&cert_pem, &read(key)?).map_err(|reason| EdgeError::Cert {
host: h.hostname.clone(), host: h.hostname.clone(),
reason, reason,
})?; })?;
certs.insert(&h.hostname, pair); if let Some(exp) = not_after(&cert_pem) {
file_cert_expiry.insert(h.hostname.clone(), exp);
}
file_certs.insert(h.hostname.clone(), Arc::new(pair));
} }
let mut secret_values = Vec::new(); let mut secret_values = Vec::new();
let request_ops = ops(&h.request_headers, &secrets, &mut secret_values)?; let request_ops = ops(&h.request_headers, &secrets, &mut secret_values)?;
let response_ops = ops(&h.response_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 let upstreams = h
.upstreams .upstreams
.iter() .iter()
@@ -278,10 +406,43 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
request_ops, request_ops,
response_ops, response_ops,
secret_values, 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 { let forward_auth = match &cfg.forward_auth {
Some(fa) => Some(ForwardAuthRt { Some(fa) => Some(ForwardAuthRt {
upstream: upstream(&fa.upstream)?, upstream: upstream(&fa.upstream)?,
@@ -311,13 +472,28 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
} else { } else {
None 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 { Ok(Runtime {
cfg, cfg,
trusted_proxies,
hosts, hosts,
forward_auth, forward_auth,
access_log, access_log,
certs, file_certs,
file_cert_expiry,
share_key,
device_trust,
sha256: String::new(),
}) })
} }
@@ -361,4 +537,24 @@ mod resolve_tests {
.await; .await;
assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound); assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound);
} }
#[test]
fn health_records_keep_the_last_five() {
let r = HealthRecord::default();
for i in 0..8 {
r.record(Check {
seq: 0,
at: i,
ok: i % 2 == 0,
source: "health_check",
kind: None,
status: None,
latency_ms: None,
});
}
let c = r.checks();
assert_eq!(c.len(), KEPT_CHECKS);
assert_eq!(c.first().unwrap().seq, 4);
assert_eq!(c.last().unwrap().seq, 8);
}
} }

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