Compare commits

...

20 Commits

Author SHA1 Message Date
mnovak 8e3a3c01e4 [docs] CLAUDE.md: never touch C: or D:; everything goes on F: 2026-11-10 23:44:40 +01:00
mnovak 0e9c2a7bc9 [repo] Merge: feature/release-kit (Release notes and screenshots of the web UI on a v* tag's Gitea release, PR #7) 2026-11-09 17:47:08 +01:00
mnovak dcdff4d414 [docs] Roadmap: phase 4 started with the release kit; handover 2026-11-09 17:46:34 +01:00
mnovak b9ab5006a8 [fabrica] Release: the release pipeline on a v* tag (version check, web tests, fabrica notes, the shots, approval, publish under SHA256SUMS signed by domi-release) and the highlights of 0.1.0 2026-11-09 17:42:29 +01:00
mnovak 7a32eeb411 [web] Shots: the release's screenshots of the built UI against the demo control plane, in headless Edge over DevTools (aula-*.png, aula.json) 2026-11-09 17:42:06 +01:00
mnovak c2c6454302 [tests] Release screenshots, tests first: the demo control plane draws every shot from invented data only (.test names, documentation addresses) 2026-11-09 17:42:05 +01:00
mnovak d035fd3165 [docs] Release: notes and screenshots of the web UI on the Gitea release of a v* tag, under the signed SHA256SUMS (docs/release.md) 2026-11-09 17:42:05 +01:00
mnovak 7b906de79f [repo] Merge: feature/fabrica-app (Ianitor declares itself to Fabrica: app.yaml and the deploy pipeline, PR #6) 2026-11-08 22:49:42 +01:00
mnovak 6ba3fa4b17 [deploy] Fabrica: app.yaml with a server part and the deploy pipeline for the ianitor flake input, so Fabrica's Apps screen shows Ianitor 2026-11-08 22:48:59 +01:00
mnovak 5df34bfae6 [repo] Merge: Phase 3 web UI, Domi CA, NixOS module (PR #5) 2026-11-08 12:57:57 +01:00
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
57 changed files with 3515 additions and 333 deletions
+2
View File
@@ -0,0 +1,2 @@
# Local Fabrica runs: records, logs and artifacts (Fabrica core docs/FORMATS.md)
runs/
+11
View File
@@ -0,0 +1,11 @@
# Ianitor Domi declares itself to Fabrica (Fabrica core docs/FORMATS.md, "Fabrica: the app"): a server part only,
# the reverse proxy with its control plane and web UI, deployed by .fabrica/artifex/deploy.yaml through the server's
# fabrica-deploy@ianitor. Fabrica's Apps screen shows one card for it: Deploy, then the Custos card. The colour is
# the murex accent (packages/ui/src/tokens.css, --accent).
name: Ianitor
icon: globe
color: "#e0a3dc"
parts:
server:
pipeline: deploy
input: ianitor
+15
View File
@@ -0,0 +1,15 @@
# Ianitor Domi onto the server (Fabrica docs/04_deploy.md): `fabrica deploy ianitor`, or Fabrica's Apps → Ianitor →
# Deploy. The NixOS runner starts fabrica-deploy@ianitor: the server's clone is fast-forwarded, the flake input
# `ianitor` updated (inputs.ianitor.nixosModules.ianitor, docs/deploy/configuration-server.patch), the system
# switched, the health check asked, and the switch rolled back if it does not answer. After a deploy run
# deploy/test-access.sh from a LAN machine (CLAUDE.md).
name: deploy
on:
manual: true
runner: nixos
steps:
- id: approve
approve: "Deploy Ianitor ${{ commit }} to the server?"
- id: switch
needs: [approve]
deploy: ianitor
+44
View File
@@ -0,0 +1,44 @@
# Ianitor Domi: the Gitea release of a v* tag (docs/release.md). Ianitor ships no binary (the server builds it with
# Nix and the deploy pipeline switches it in), so a release is its notes and screenshots of the web UI, published under
# a SHA256SUMS signed by domi-release through Custos; release-notes.md is also the release's text on Gitea.
# The Windows runner (the Fabrica app on Mark's PC) runs it: `fabrica`, node and pnpm are on every step's PATH.
# No Gitea webhook to the hub yet: a pushed tag is started on demand (the hub's POST /api/runs, ref v<version>).
# `notes` is Fabrica's release notes since the previous v* tag (Fabrica docs/12_release_kit.md); `shots` takes the
# same files as `fabrica aula shots` (core docs/FORMATS.md, "Fabrica: the Aula page") from the built web UI against
# the demo control plane with invented data, in headless Edge. No landing page while app.yaml has no `aula: true`.
name: release
on:
tag: "v*"
manual: true
runner: windows
steps:
- id: version
run: node scripts/check-version.mjs ${{ version }}
- id: install
run: pnpm install --frozen-lockfile
- id: check
needs: [install]
run: pnpm --filter web check
- id: test
needs: [install]
run: pnpm --filter web test
- id: notes
run: fabrica notes
artifacts: ["target/notes/release-notes.md", "target/notes/release-notes.json"]
- id: shots
needs: [check, test]
run: node apps/web/scripts/shots.mjs
artifacts: ["target/aula/aula-*.png", "target/aula/aula.json"]
- id: approve
needs: [version, notes, shots]
approve: "Publish Ianitor ${{ tag }}: its notes and screenshots?"
- id: publish
needs: [approve]
publish:
gitea-release: true
files:
- "**/release-notes.md"
- "**/release-notes.json"
- "**/aula-*.png"
- "**/aula.json"
sums: domi-release
+18
View File
@@ -0,0 +1,18 @@
The first release of Ianitor Domi: a reverse proxy for a home server, built on Cloudflare's Pingora, with Caddy as a
tested fallback, a small Domi certificate authority, and a web UI where every change takes three clicks or fewer.
- **Hosts in plain words.** Add a host, say where its traffic goes, pick a Domi or Let's Encrypt certificate and
whether visitors sign in first (Authelia forward-auth). Each host is checked for health and shows healthy,
degraded or down.
- **Changes that undo themselves.** Every change is compiled, tried, and watched for 60 seconds; if a host stops
answering, it is reverted on its own. Routes live in a git repository, one file per host, with Undo and a
history you can restore any kept version from.
- **Two engines.** Pingora serves; Caddy is built from the same routes, compared host by host, and can take over at
runtime in about two seconds.
- **The Domi CA.** Certificates for hosts reached only from home, and device certificates (mTLS) for phones,
computers and Domi apps, from an intermediate whose root stays offline.
- **Share links**, signed and time-limited, for a single host.
- **NixOS-native.** A flake with the module and VM tests; deployed through Fabrica.
The changes below are the merges since the first commit; PR 3 to 5 are the control plane (phase 2), the decisions
on the open points, and the web UI, the Domi CA and the NixOS module (phase 3).
+7
View File
@@ -13,11 +13,14 @@ 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.
deploy/nixos NixOS module + VM tests. deploy/nixos NixOS module + VM tests.
scripts the release's version check. Releases (notes, screenshots): docs/release.md.
## Commands ## Commands
cargo test --workspace # quote test counts per crate; an exit code alone is not green cargo test --workspace # quote test counts per crate; an exit code alone is not green
cargo run -p ianitor-control -- --dev cargo run -p ianitor-control -- --dev
pnpm --filter web dev # 127.0.0.1 only, never --host pnpm --filter web dev # 127.0.0.1 only, never --host
node apps/web/scripts/shots.mjs # the release's screenshots (demo data, headless Edge) -> target/aula (docs/release.md)
node scripts/check-version.mjs X.Y.Z # Cargo.toml and both package.json carry the version
nix build .#ianitor nix build .#ianitor
nix flake check # includes NixOS VM tests (Linux + KVM) nix flake check # includes NixOS VM tests (Linux + KVM)
@@ -31,6 +34,10 @@ One-time per clone: git config core.hooksPath .githooks (self-test: bash .gith
- Never in git: target/, node_modules/, dist/, binaries, private keys, files over 5 MB. A pre-commit hook enforces it. - Never in git: target/, node_modules/, dist/, binaries, private keys, files over 5 MB. A pre-commit hook enforces it.
- $GITEA_TOKEN never echoed or written anywhere. Secrets come only from Custos or systemd credentials, never the Nix store. - $GITEA_TOKEN never echoed or written anywhere. Secrets come only from Custos or systemd credentials, never the Nix store.
- ianitor-control and every dev server listen on 127.0.0.1 only; only ianitor-edge binds public ports. - ianitor-control and every dev server listen on 127.0.0.1 only; only ianitor-edge binds public ports.
- Disks (Mark's machine): never write, move or delete anything on C:, and nothing on D: either. Everything goes on F:
(build output, clones, caches, temp files, tools, WSL swap), under F:\C-Drive-Migration when it replaces a C: path.
The only file kept on C: is C:\Users\chode\.wslconfig (WSL reads it only there; it points swap to F:). Every agent's
brief repeats this rule.
- Route files, API bodies, CSRs, headers and share tokens are hostile input: typed Result, no unwrap() on input paths, no swallowed errors. - Route files, API bodies, CSRs, headers and share tokens are hostile input: typed Result, no unwrap() on input paths, no swallowed errors.
- Every route change goes through the core compiler and the differential tests. - Every route change goes through the core compiler and the differential tests.
- Tests first only where the risk is: parsing, CA, share tokens, forward-auth, apply/rollback, secret injection. - Tests first only where the risk is: parsing, CA, share tokens, forward-auth, apply/rollback, secret injection.
+2 -1
View File
@@ -9,7 +9,8 @@
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings", "check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
"test": "vitest run" "test": "vitest run",
"shots": "node scripts/shots.mjs"
}, },
"dependencies": { "dependencies": {
"@ianitor/ui": "workspace:*" "@ianitor/ui": "workspace:*"
+418
View File
@@ -0,0 +1,418 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The release's screenshots of the web UI (docs/release.md):
// node apps/web/scripts/shots.mjs [--out <dir>] (default: <repo>/target/aula)
// Builds the UI, serves it on 127.0.0.1 with /api/v1 answered by the demo control plane
// (tests/demo.ts: invented data only), photographs each shot of demo.ts's SHOTS in headless Edge
// or Chrome over DevTools, and writes aula-<name>.png and aula.json in the format of Fabrica's
// core docs/FORMATS.md ("Fabrica: the Aula page"). On every way out the browser's process tree
// and the server are stopped and the temporary folder is removed.
// Exit codes: 0 done, 1 a problem, 130 cancelled.
import { spawn, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { createServer as createHttpServer } from "node:http";
import { tmpdir } from "node:os";
import { basename, delimiter, dirname, extname, join, normalize, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { build, createServer as createViteServer } from "vite";
const web = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const repo = resolve(web, "../..");
const WAIT_MS = 20_000;
function usage(msg) {
console.error(`shots: ${msg}\nusage: node apps/web/scripts/shots.mjs [--out <dir>]`);
process.exit(1);
}
let out = join(repo, "target", "aula");
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
if (a === "--out" && process.argv[i + 1]) out = resolve(process.argv[++i]);
else usage(`unknown argument ${a}`);
}
const log = (m) => console.log(`shots: ${m}`);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ---------- cleanup on every way out ----------
const cleanups = [];
let cleaning = false;
async function cleanup() {
if (cleaning) return;
cleaning = true;
for (const f of cleanups.reverse()) {
try {
await f();
} catch (e) {
console.error(`shots: cleanup: ${e?.message ?? e}`);
}
}
}
process.on("SIGINT", () => void cleanup().then(() => process.exit(130)));
process.on("SIGTERM", () => void cleanup().then(() => process.exit(130)));
// ---------- the output folder ----------
function clearOutput() {
mkdirSync(out, { recursive: true });
for (const n of readdirSync(out)) {
if (n === "aula.json" || (n.startsWith("aula-") && n.endsWith(".png"))) rmSync(join(out, n), { force: true });
}
}
/** Width and height from the PNG's IHDR, not assumed. */
function pngSize(png) {
const sig = "89504e470d0a1a0a";
if (png.length < 24 || png.subarray(0, 8).toString("hex") !== sig || png.subarray(12, 16).toString("latin1") !== "IHDR") {
throw new Error("the browser's capture is not a PNG");
}
return { width: png.readUInt32BE(16), height: png.readUInt32BE(20) };
}
// ---------- the demo control plane and the built UI on 127.0.0.1 ----------
const TYPES = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".txt": "text/plain; charset=utf-8",
};
function serve(dist, api) {
const index = readFileSync(join(dist, "index.html"));
const server = createHttpServer((req, res) => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
if (url.pathname.startsWith("/api/v1/") || url.pathname === "/api/v1") {
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
let body = {};
try {
body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {};
} catch {
body = {};
}
const a = api(req.method ?? "GET", url.pathname.slice("/api/v1".length) + url.search, body);
res.writeHead(a.status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
res.end(a.text ?? undefined);
});
return;
}
// The built files; any other path is the app's own route, answered with index.html.
const file = normalize(join(dist, decodeURIComponent(url.pathname)));
if (file.startsWith(dist + sep) && existsSync(file) && statSync(file).isFile()) {
res.writeHead(200, { "Content-Type": TYPES[extname(file)] ?? "application/octet-stream" });
res.end(readFileSync(file));
return;
}
res.writeHead(200, { "Content-Type": TYPES[".html"], "Cache-Control": "no-store" });
res.end(index);
});
return new Promise((ok, fail) => {
server.once("error", fail);
server.listen(0, "127.0.0.1", () => ok(server));
});
}
// ---------- the browser ----------
function findBrowser() {
const named = process.env.IANITOR_SHOTS_BROWSER;
if (named) {
if (!existsSync(named)) throw new Error(`IANITOR_SHOTS_BROWSER: ${named} does not exist`);
return named;
}
const candidates = [];
if (process.platform === "win32") {
for (const base of [process.env["ProgramFiles(x86)"], process.env.ProgramFiles, process.env.LOCALAPPDATA].filter(Boolean)) {
candidates.push(join(base, "Microsoft", "Edge", "Application", "msedge.exe"), join(base, "Google", "Chrome", "Application", "chrome.exe"));
}
} else {
for (const dir of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {
for (const n of ["chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "microsoft-edge"]) candidates.push(join(dir, n));
}
candidates.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
}
const found = candidates.find((c) => existsSync(c));
if (!found) throw new Error("no Microsoft Edge or Chrome found; set IANITOR_SHOTS_BROWSER to a Chromium browser");
return found;
}
/** Only what a program needs to run, the user folders in the temporary folder, nothing of the runner's. */
function cleanEnv(home) {
const keep = /^(SystemRoot|SystemDrive|windir|ComSpec|PATH|PATHEXT|OS|PROCESSOR_.*|NUMBER_OF_PROCESSORS|ProgramFiles.*|ProgramW6432|CommonProgramFiles.*|CommonProgramW6432|ProgramData|ALLUSERSPROFILE|PUBLIC|LANG|TZ)$/i;
const env = {};
for (const [k, v] of Object.entries(process.env)) if (keep.test(k) && v !== undefined) env[k] = v;
for (const d of ["home", "appdata", "local", "temp"]) mkdirSync(join(home, d), { recursive: true });
Object.assign(env, {
HOME: join(home, "home"),
USERPROFILE: join(home, "home"),
APPDATA: join(home, "appdata"),
LOCALAPPDATA: join(home, "local"),
TEMP: join(home, "temp"),
TMP: join(home, "temp"),
TMPDIR: join(home, "temp"),
});
return env;
}
/** Edge may start its browser again as a new process, outside the tree: on Windows, anything still
* running with a profile in the temporary folder is stopped by its command line. */
function sweep(exe, tmp) {
if (process.platform !== "win32") return;
const script = "Get-CimInstance Win32_Process -Filter \"Name='$env:SHOTS_EXE'\" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($env:SHOTS_TMP) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }";
spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
stdio: "ignore",
windowsHide: true,
env: { ...cleanEnv(join(tmp, "sweep")), SHOTS_EXE: basename(exe), SHOTS_TMP: tmp },
});
}
function killTree(child) {
if (!child.pid || child.exitCode !== null) return;
if (process.platform === "win32") {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
} else {
try {
process.kill(-child.pid, "SIGKILL");
} catch {
child.kill("SIGKILL");
}
}
}
/** Starts the browser; one that has not opened DevTools after 20 s is killed and started again, twice. */
async function startBrowser(exe, tmp, size) {
for (let attempt = 1; ; attempt++) {
try {
return await launch(exe, join(tmp, `profile-${attempt}`), join(tmp, `user-${attempt}`), size);
} catch (e) {
if (attempt === 3 || e.fatal) throw e;
log(`${e.message}; starting it again`);
}
}
}
async function launch(exe, profile, user, size) {
mkdirSync(profile, { recursive: true });
const args = [
"--headless=new",
"--remote-debugging-port=0",
"--remote-debugging-address=127.0.0.1",
`--user-data-dir=${profile}`,
"--no-first-run",
"--no-default-browser-check",
"--disable-extensions",
"--disable-sync",
"--disable-background-networking",
"--disable-component-update",
"--disable-default-apps",
"--disable-features=Translate,OptimizationHints,MediaRouter,msSmartScreenProtection",
"--hide-scrollbars",
"--mute-audio",
"--force-color-profile=srgb",
"--force-device-scale-factor=1",
`--window-size=${size.width},${size.height}`,
"about:blank",
];
const child = spawn(exe, args, { env: cleanEnv(user), stdio: ["ignore", "ignore", "pipe"], windowsHide: true, detached: process.platform !== "win32" });
const stop = async () => {
killTree(child);
for (let i = 0; i < 50 && child.exitCode === null && child.signalCode === null; i++) await sleep(100);
};
cleanups.push(stop);
let stderr = "";
child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-2000)));
const fail = async (msg, fatal = false) => {
await stop();
const tail = stderr.trim().split(/\r?\n/).slice(-3).join(" | ");
throw Object.assign(new Error(`${msg}${tail ? `; it said: ${tail}` : ""}`), { fatal });
};
let exited = null;
child.on("exit", (code) => (exited = code ?? -1));
child.on("error", (e) => (exited = e.message));
const portFile = join(profile, "DevToolsActivePort");
const deadline = Date.now() + 20_000;
let seen = "no DevToolsActivePort yet";
for (;;) {
if (exited !== null) await fail(`the browser exited before it was ready (${exited})`, typeof exited === "string");
if (existsSync(portFile)) {
const port = Number(readFileSync(portFile, "utf8").split(/\r?\n/)[0]);
if (port > 0) {
try {
const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = list.find((t) => t.type === "page" && t.webSocketDebuggerUrl);
if (page) return page.webSocketDebuggerUrl;
seen = `no page among ${list.length} targets on port ${port}`;
await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" }).catch(() => {});
} catch (e) {
seen = `port ${port}: ${e.cause?.message ?? e.message}`;
}
}
}
if (Date.now() > deadline) await fail(`the browser's DevTools did not answer within 20 s (${seen})`);
await sleep(200);
}
}
/** A minimal DevTools client over Node's WebSocket. */
async function devtools(url) {
const ws = new WebSocket(url);
await new Promise((ok, fail) => {
ws.onopen = ok;
ws.onerror = () => fail(new Error("cannot open the browser's DevTools socket"));
});
let id = 0;
const pending = new Map();
ws.onmessage = (m) => {
const msg = JSON.parse(String(m.data));
const p = msg.id !== undefined && pending.get(msg.id);
if (!p) return;
pending.delete(msg.id);
if (msg.error) p.fail(new Error(`${p.method}: ${msg.error.message}`));
else p.ok(msg.result);
};
ws.onclose = () => {
for (const p of pending.values()) p.fail(new Error("the browser closed its DevTools socket"));
pending.clear();
};
cleanups.push(() => ws.close());
const send = (method, params = {}) =>
new Promise((ok, fail) => {
const n = ++id;
pending.set(n, { ok, fail, method });
ws.send(JSON.stringify({ id: n, method, params }));
});
/** The value of an expression in the page; a page being replaced answers again later. */
const evaluate = async (expression) => {
const r = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
return r.result.value;
};
return { send, evaluate };
}
async function until(what, test) {
const deadline = Date.now() + WAIT_MS;
let last = null;
while (Date.now() < deadline) {
try {
if (await test()) return;
} catch (e) {
last = e;
}
await sleep(100);
}
throw new Error(`waited ${WAIT_MS / 1000} s for ${what}${last ? ` (${last.message})` : ""}`);
}
// ---------- the shots ----------
async function main() {
clearOutput();
const tmp = mkdtempSync(join(tmpdir(), "ianitor-shots-"));
cleanups.push(async () => {
for (let i = 0; i < 20; i++) {
try {
rmSync(tmp, { recursive: true, force: true });
return;
} catch {
await sleep(250);
}
}
console.error(`shots: could not remove ${tmp}`);
});
// The demo's shots and answers, from the TypeScript the tests use.
const loader = await createViteServer({
root: web,
configFile: false,
logLevel: "error",
appType: "custom",
server: { middlewareMode: true, hmr: false, ws: false },
optimizeDeps: { noDiscovery: true, include: [] },
});
let demo;
try {
demo = await loader.ssrLoadModule("/tests/demo.ts");
} finally {
await loader.close();
}
const { SHOTS, SIZE, demoApi } = demo;
log("building the web UI");
const dist = join(tmp, "dist");
await build({ root: web, logLevel: "warn", build: { outDir: dist, emptyOutDir: true } });
const server = await serve(dist, demoApi());
cleanups.push(() => new Promise((r) => server.close(() => r())));
server.closeAllConnections && cleanups.push(() => server.closeAllConnections());
const base = `http://127.0.0.1:${server.address().port}`;
log(`demo control plane and UI on ${base}`);
const exe = findBrowser();
log(`browser: ${exe}`);
cleanups.push(() => sweep(exe, tmp));
const page = await devtools(await startBrowser(exe, tmp, SIZE));
await page.send("Page.enable");
await page.send("Emulation.setDeviceMetricsOverride", { width: SIZE.width, height: SIZE.height, deviceScaleFactor: 1, mobile: false });
const taken = [];
for (const shot of SHOTS) {
const url = base + shot.path;
try {
// A fresh load per shot: mark the old page, so a page that has not been replaced yet does not count.
await page.evaluate("window.__ianitorShotsOld = true").catch(() => {});
await page.send("Page.navigate", { url });
await until(`${url} to load`, () => page.evaluate("!window.__ianitorShotsOld && document.readyState === 'complete'"));
for (const sel of shot.click ?? []) {
const q = JSON.stringify(sel);
await until(`${sel} to click`, () => page.evaluate(`(() => { const e = document.querySelector(${q}); if (!e) return false; e.click(); return true; })()`));
}
const w = JSON.stringify(shot.wait);
await until(shot.wait, () => page.evaluate(`!!document.querySelector(${w})`));
await page.evaluate("document.fonts.ready.then(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true)))))");
await sleep(400);
} catch (e) {
try {
const failed = await page.send("Page.captureScreenshot", { format: "png" });
writeFileSync(join(out, `aula-${shot.name}-failed.png`), Buffer.from(failed.data, "base64"));
} catch {
/* nothing to save */
}
throw new Error(`shot ${shot.name}: ${e.message}; the page was ${url}; what it showed is aula-${shot.name}-failed.png`);
}
const png = Buffer.from((await page.send("Page.captureScreenshot", { format: "png" })).data, "base64");
const { width, height } = pngSize(png);
const file = `aula-${shot.name}.png`;
writeFileSync(join(out, file), png);
taken.push({ name: shot.name, title: shot.title, file, width, height, sha256: createHash("sha256").update(png).digest("hex") });
log(`${file} ${width}x${height}`);
}
writeFileSync(join(out, "aula.json"), `${JSON.stringify({ v: 1, shots: taken })}\n`);
log(`${taken.length} shots and aula.json in ${out}`);
}
let code = 0;
try {
await main();
} catch (e) {
console.error(`shots: ${e?.message ?? e}`);
code = 1;
} finally {
await cleanup();
}
process.exit(code);
+16 -2
View File
@@ -7,6 +7,8 @@
import { onMount } from "svelte"; import { onMount } from "svelte";
import { Button, Dialog, Icon } from "@ianitor/ui"; import { Button, Dialog, Icon } from "@ianitor/ui";
import type { IconName } 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 TopBanners from "./components/TopBanners.svelte";
import { app, navigate, refresh, startPolling } from "./lib/app.svelte"; import { app, navigate, refresh, startPolling } from "./lib/app.svelte";
import { remembered } from "./lib/applies"; import { remembered } from "./lib/applies";
@@ -72,7 +74,12 @@
function signIn() { function signIn() {
const w = window.open("/signed-in", "ianitor-sign-in"); const w = window.open("/signed-in", "ianitor-sign-in");
if (!w) location.href = `/signed-in?back=${encodeURIComponent(app.path)}`; 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() { async function signedInAgain() {
@@ -99,7 +106,7 @@
{#if app.overview?.site?.auth_logout_url}<a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a>{/if} {#if app.overview?.site?.auth_logout_url}<a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a>{/if}
</div> </div>
</nav> </nav>
<header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span></header> <header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span>{#if app.phone}<EngineChip />{/if}</header>
<main id="main" tabindex="-1"> <main id="main" tabindex="-1">
<TopBanners /> <TopBanners />
{#if route.view === "hosts"} {#if route.view === "hosts"}
@@ -121,6 +128,13 @@
</nav> </nav>
</div> </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"> <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} {#each app.toasts as t (t.id)}<div class="ia-toast"><Icon name="check" />{t.text}</div>{/each}
</div> </div>
+34 -9
View File
@@ -4,10 +4,10 @@
<script lang="ts"> <script lang="ts">
// Handoff §7.4 and §7.5: the last-change bar with Undo (1 click), and the reverted / not // 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. // applied banner that stands in for its first line.
import { Banner, Button, Icon, Progress } from "@ianitor/ui"; import { Banner, Button, Details, Icon, Progress } from "@ianitor/ui";
import { ApiError, call, del, newKey, post, sentence } from "../lib/api"; import { ApiError, call, del, newKey, post, sentence } from "../lib/api";
import { app, refresh, secondsLeft, toast } from "../lib/app.svelte"; import { app, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { firstSentence, when } from "../lib/format"; import { atTime, firstSentence, when } from "../lib/format";
import type { ApplyView } from "../lib/types"; import type { ApplyView } from "../lib/types";
let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props(); let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props();
@@ -21,7 +21,7 @@
let pushing = $state(false); let pushing = $state(false);
const dismissKey = $derived(last ? `apply:${last.id}` : ""); const dismissKey = $derived(last ? `apply:${last.id}` : "");
function runningHeading(summary: string, a: ApplyView | null): string { function runningHeading(summary: string, a: { kind: string; hosts: string[]; summary: string } | null): string {
if (!a) return summary; if (!a) return summary;
const h = a.hosts[0] ?? ""; const h = a.hosts[0] ?? "";
switch (a.kind) { switch (a.kind) {
@@ -29,6 +29,8 @@
case "remove": return `Removing ${h}`; case "remove": return `Removing ${h}`;
case "edit": return `Changing ${h}`; case "edit": return `Changing ${h}`;
case "share_links": return `Turning on share links for ${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; default: return summary;
} }
} }
@@ -85,7 +87,29 @@
}); });
const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed"); const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed");
const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null); const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null);
const watchLeft = $derived(last?.watch ? secondsLeft(last.watch.ends_at) : 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> </script>
{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)} {#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)}
@@ -93,8 +117,9 @@
<Banner tone="notice" ondismiss={() => (app.dismissed = [...app.dismissed, dismissKey])}> <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} {#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 parts[1]}Reason: {parts[1]}{/if}
{#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")}<Details detail={last.reason.detail} />{/if}
{#snippet actions()} {#snippet actions()}
{#if last.attempted_host}<Button variant="outline" onclick={() => onedit(last, last.reason?.field ?? undefined)}>Edit and try again</Button>{/if} {#if offer}<Button variant="outline" onclick={() => onedit(last, offer?.field)}>{offer.label}</Button>{/if}
{/snippet} {/snippet}
</Banner> </Banner>
{/if} {/if}
@@ -104,8 +129,8 @@
{#if active} {#if active}
<div class="grow"> <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> <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, last && last.id === active.id ? last : null)}</span></div> <span>{runningHeading(active.summary, active.kind ? active : null)}</span></div>
<div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : `${watchLeft ?? active.seconds_left ?? 0} s left`}</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} {#if active.state === "watching" && watchLeft != null}
{@const total = o?.site?.watch_seconds ?? 60} {@const total = o?.site?.watch_seconds ?? 60}
<Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" /> <Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" />
@@ -116,7 +141,7 @@
<div class="grow"> <div class="grow">
{#if last.state === "kept"} {#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><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 ? "Kept, but not yet saved to Gitea. Ianitor tries again by itself." : keptLine}</div> <div class="ia-sub" class:warn={pushFailed}>{pushFailed ? pushLine : keptLine}</div>
{:else if undo?.target} {:else if undo?.target}
<div>Undo: {undo.target.summary}</div> <div>Undo: {undo.target.summary}</div>
{/if} {/if}
@@ -125,7 +150,7 @@
{#if undoReason}<div class="ia-sub" id="undo-reason">{undoReason}</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} {#if !undo?.target}<div class="ia-sub">Nothing to undo yet.</div>{/if}
</div> </div>
{#if pushFailed}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if} {#if canPushNow}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if}
{#if undo?.target} {#if undo?.target}
<Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available} <Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available}
describedby={undoReason ? "undo-reason" : undefined} describedby={undoReason ? "undo-reason" : undefined}
+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>
+25 -11
View File
@@ -4,11 +4,11 @@
<script lang="ts"> <script lang="ts">
// Handoff §9: the engine popover. Click 1 is the chip, click 2 "Switch to Caddy" (the popover // 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. // is the confirmation). The switch runs in control; this polls GET /engine until it ends.
import { onDestroy } from "svelte"; import { onDestroy, onMount } from "svelte";
import { Banner, Button, Dialog, Icon, Progress } from "@ianitor/ui"; import { Banner, Button, Details, Dialog, Icon, Progress } from "@ianitor/ui";
import { call, get, newKey, sentence } from "../lib/api"; import { call, get, newKey, sentence } from "../lib/api";
import { app, refresh } from "../lib/app.svelte"; import { app, refresh } from "../lib/app.svelte";
import { when } from "../lib/format"; import { whenInline } from "../lib/format";
import type { EngineView } from "../lib/types"; import type { EngineView } from "../lib/types";
let { onclose }: { onclose: () => void } = $props(); let { onclose }: { onclose: () => void } = $props();
@@ -23,7 +23,17 @@
let timer: ReturnType<typeof setTimeout> | undefined; let timer: ReturnType<typeof setTimeout> | undefined;
onDestroy(() => clearTimeout(timer)); onDestroy(() => clearTimeout(timer));
const activeLinks = $derived(app.overview?.hosts.filter((h) => h.share_links).length ?? 0); 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 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); 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);
@@ -62,17 +72,21 @@
} }
</script> </script>
<Dialog title="Serving with {name}" kind="popover" modal={false} {onclose}> <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> <p class="ia-label">Engine</p>
{#if e?.state === "stopped"} {#if e?.state === "stopped"}
<p><strong>{name} is not answering.</strong> Visitors may not reach any host. Switching to {other} is the quickest way back.</p> <p>Visitors may not reach any host. Switching to {other} is the quickest way back.</p>
{:else} {:else}
<p class="ia-text2"> <p class="ia-text2">
{#if e?.since}Since {when(e.since, app.now)}. {/if} {#if e?.since}Since {whenInline(e.since, app.now)}. {/if}
{#if running === "pingora"} {#if running === "pingora"}
{#if notReady}Caddy is not ready: its settings have not been built yet.{:else}Caddy is ready with the same routes: built {when(e?.fallback_ready?.built_at, app.now)}{e?.fallback_ready?.current ? "" : " (it is rebuilt from the current routes when you switch)"}.{/if} {#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} {:else}Pingora is ready with the same routes.{/if}
</p> </p>
{#if running === "pingora" && !notReady && fr?.differences.length}
<Details detail={fr.differences.join("\n")} />
{/if}
{/if} {/if}
<div class="ia-card"> <div class="ia-card">
<p><strong>What happens</strong></p> <p><strong>What happens</strong></p>
@@ -81,10 +95,10 @@
<li>Open connections close; videos and uploads in progress restart.</li> <li>Open connections close; videos and uploads in progress restart.</li>
<li>Hosts and certificates stay the same.</li> <li>Hosts and certificates stay the same.</li>
{#if running === "pingora"} {#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} Hosts with share links: {activeLinks}.{/if}</li> <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 wait while Caddy serves; switch back to make them.</li> <li>Changes keep working: Ianitor tries each one on Caddy and undoes it if a host stops answering.</li>
{:else} {:else}
<li>Share links work again, and changes can be made again.</li> <li>Share links work again.</li>
{/if} {/if}
<li>This page may lose contact for a few seconds.</li> <li>This page may lose contact for a few seconds.</li>
</ul> </ul>
+2 -2
View File
@@ -89,7 +89,7 @@
} }
const blocked = $derived(changesBlocked()); const blocked = $derived(changesBlocked());
const shareReason = $derived(!app.overview?.site?.share_links_available ? (underCaddy ? "Share links are paused while Caddy serves." : "Share links are not set up on this server.") : null); 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> </script>
<div class="ia-list" role="table" aria-label="Hosts"> <div class="ia-list" role="table" aria-label="Hosts">
@@ -111,7 +111,7 @@
<span class="ia-sub phone">{w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}</span> <span class="ia-sub phone">{w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}</span>
</span> </span>
<span role="cell" class="desktop"> <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>{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> <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 === "pending"}<span class="ia-sub" style="display:block">Waiting for Let's Encrypt to issue the certificate.</span>{/if}
{#if h.certificate.state === "failed"} {#if h.certificate.state === "failed"}
+3 -1
View File
@@ -52,7 +52,9 @@
function pick(it: Item) { function pick(it: Item) {
if (it.reason) return; if (it.reason) return;
close(false); // 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(); it.run();
} }
+46 -7
View File
@@ -8,7 +8,7 @@
import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui"; import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui";
import ApplyProgress from "./ApplyProgress.svelte"; import ApplyProgress from "./ApplyProgress.svelte";
import { ApiError, call, del, get, newKey, sentence } from "../lib/api"; import { ApiError, call, del, get, newKey, sentence } from "../lib/api";
import { app, changesBlocked, refresh, toast } from "../lib/app.svelte"; import { app, changesBlocked, refresh, restoreLastKept, toast } from "../lib/app.svelte";
import { FINAL, follow } from "../lib/applies"; import { FINAL, follow } from "../lib/applies";
import { firstSentence } from "../lib/format"; import { firstSentence } from "../lib/format";
import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types"; import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types";
@@ -62,6 +62,8 @@
// ---- the apply // ---- the apply
let apply = $state<ApplyView | null>(null); let apply = $state<ApplyView | null>(null);
let restoring = $state(false);
let restoreProblem = $state<string | null>(null);
let phase = $state<"form" | "progress">("form"); let phase = $state<"form" | "progress">("form");
let stop: (() => void) | undefined; let stop: (() => void) | undefined;
let closeTimer: ReturnType<typeof setTimeout> | undefined; let closeTimer: ReturnType<typeof setTimeout> | undefined;
@@ -128,16 +130,43 @@
rev = app.overview?.rev ?? null; rev = app.overview?.rev ?? null;
if (!signinOk) host.auth = "none"; if (!signinOk) host.auth = "none";
} }
loading = false; // A form saved before this tab went to sign in comes back (App.svelte, signIn).
if (focusField) { try {
if (focusField.startsWith("health_check")) more = true; const raw = sessionStorage.getItem(DRAFT);
setTimeout(() => document.getElementById(fieldId(focusField))?.focus(), 0); 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(() => { onDestroy(() => {
stop?.(); stop?.();
clearTimeout(closeTimer); clearTimeout(closeTimer);
if (typeof window !== "undefined") window.removeEventListener("ianitor:save-draft", saveDraft);
}); });
function fieldId(f: string): string { function fieldId(f: string): string {
@@ -226,6 +255,7 @@
function onApply(a: ApplyView) { function onApply(a: ApplyView) {
apply = a; apply = a;
if (a.state === "kept") { if (a.state === "kept") {
if (a.kind !== "remove") app.focusHost = a.hosts[0] ?? null;
closeTimer = setTimeout(() => onclose(), 1500); closeTimer = setTimeout(() => onclose(), 1500);
} }
} }
@@ -291,6 +321,10 @@
return `Removing ${h}`; return `Removing ${h}`;
case "share_links": case "share_links":
return `Turning on share links for ${h}`; return `Turning on share links for ${h}`;
case "undo":
return `Undoing: ${apply.summary.replace(/^Undid: /, "")}`;
case "restore":
return apply.summary.replace(/^Restored /, "Restoring ");
default: default:
return `Changing ${h}`; return `Changing ${h}`;
} }
@@ -321,7 +355,7 @@
{#if apply.state === "kept"} {#if apply.state === "kept"}
<Banner tone="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} {#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 ?? ""}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if} {(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> </Banner>
{:else if apply.state === "reverted" || apply.state === "failed"} {:else if apply.state === "reverted" || apply.state === "failed"}
{@const parts = firstSentence(apply.reason?.message ?? "")} {@const parts = firstSentence(apply.reason?.message ?? "")}
@@ -337,7 +371,12 @@
{#if apply.reason?.detail}<Details detail={apply.reason.detail} />{/if} {#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> <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"} {: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}</Banner> <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} {/if}
{:else} {:else}
<form id="host-form" onsubmit={submit} novalidate> <form id="host-form" onsubmit={submit} novalidate>
@@ -46,8 +46,7 @@
{@const r = i.renewal} {@const r = i.renewal}
<Banner tone="notice" label="Domi intermediate certificate"> <Banner tone="notice" label="Domi intermediate certificate">
{#snippet title()} {#snippet title()}
<span tabindex="-1">Sign the renewal on the offline computer. Check that it shows the same code:</span> <span tabindex="-1">Sign the renewal on the offline computer. The next page has the files, the command and a fingerprint to check.</span>
<span class="code" aria-label="Match code {r.match_code}">{r.match_code}</span>
{/snippet} {/snippet}
The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if} The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if}
{#snippet actions()} {#snippet actions()}
@@ -58,12 +57,9 @@
{:else if i?.banner} {:else if i?.banner}
<Banner tone={i.state === "due" ? "notice" : "down"} label="Domi intermediate certificate"> <Banner tone={i.state === "due" ? "notice" : "down"} label="Domi intermediate certificate">
{#snippet title()}<strong>{i.banner?.message}</strong>{/snippet} {#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; check the match code on both screens."} {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} {#if problem} {problem}{/if}
{#snippet actions()}<Button variant="outline" onclick={renew} {pending}>{i.state === "missing" ? "Set up" : "Renew"}</Button>{/snippet} {#snippet actions()}<Button variant="outline" onclick={renew} {pending}>{i.state === "missing" ? "Set up" : "Renew"}</Button>{/snippet}
</Banner> </Banner>
{/if} {/if}
<style>
.code { font-family: var(--font-inscription); font-size: 1.4rem; letter-spacing: 0.16em; color: var(--accent-strong); margin-left: 8px; }
</style>
+5 -5
View File
@@ -17,8 +17,9 @@
let { hostname, onclose }: { hostname: string; onclose: () => void } = $props(); let { hostname, onclose }: { hostname: string; onclose: () => void } = $props();
const row = $derived(app.overview?.hosts.find((h) => h.hostname === hostname)); // Known before the Dialog mounts, so its focus lands on Copy link (§2.9), not the title.
let on = $state(false); // 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 link = $state<MintedLink | null>(null);
let minting = $state(false); let minting = $state(false);
let copied = $state(false); let copied = $state(false);
@@ -33,10 +34,9 @@
let usingPassword = $state(false); let usingPassword = $state(false);
let turning = $state<ApplyView | null>(null); let turning = $state<ApplyView | null>(null);
let stopFollow: (() => void) | undefined; let stopFollow: (() => void) | undefined;
let secretBox: HTMLInputElement | undefined = $state(); let secretBox: HTMLTextAreaElement | undefined = $state();
onMount(() => { onMount(() => {
on = !!row?.share_links;
if (on) void mint(); if (on) void mint();
}); });
onDestroy(() => stopFollow?.()); onDestroy(() => stopFollow?.());
@@ -122,7 +122,7 @@
{#if link?.warning}<p class="ia-hint">{link.warning.message}</p>{/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 problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if link} {#if link}
<input bind:this={secretBox} class="ia-secret" readonly value={link.url} aria-label="Share link" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} /> <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} {:else if minting}
<p class="ia-muted">Making the link…</p> <p class="ia-muted">Making the link…</p>
{/if} {/if}
+36 -23
View File
@@ -5,31 +5,42 @@
// Handoff §2.8 order: paused / needs attention, lost contact, health unavailable, the Caddy // Handoff §2.8 order: paused / needs attention, lost contact, health unavailable, the Caddy
// notice, then (on Hosts) the intermediate banner. First on every screen. // notice, then (on Hosts) the intermediate banner. First on every screen.
import { Banner, Button, Details } from "@ianitor/ui"; import { Banner, Button, Details } from "@ianitor/ui";
import { post, sentence } from "../lib/api"; import { app, refresh, restorable as canRestore, restoreLastKept } from "../lib/app.svelte";
import { app, refresh } from "../lib/app.svelte"; import { atTime, whenInline } from "../lib/format";
import { when } from "../lib/format";
import type { ApplyView } from "../lib/types";
const o = $derived(app.overview); const o = $derived(app.overview);
let restoring = $state(false); let restoring = $state(false);
let problem = $state<string | null>(null); let problem = $state<string | null>(null);
const restorable = $derived( const restorable = $derived(canRestore());
!!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target,
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 restoreLastKept() {
if (!o?.undo?.target) return;
restoring = true;
try {
const a = await post<{ apply: ApplyView }>("/restore", { change_id: o.undo.target.change_id, base_rev: o.rev });
app.panel = { kind: "host", resume: a.apply.id };
} catch (e) {
problem = sentence(e);
} finally {
restoring = false;
}
}
async function retry() { async function retry() {
await refresh(); await refresh();
@@ -38,11 +49,13 @@
{#if o?.paused} {#if o?.paused}
<Banner tone="down" live="alert"> <Banner tone="down" live="alert">
{#snippet title()}<span class="ia-status" data-s="down"><span class="word">{restorable ? "needs attention" : "paused"}</span></span> <strong>{o.paused?.message}</strong>{/snippet} {#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 restorable && o.undo?.target}Goes back to "{o.undo.target.summary}" from {when(o.undo.target.kept_at, app.now)}. It is checked like any change.{/if} {#if pause.line2}<span class="line2">{pause.line2}</span>{/if}
{#if problem} {problem}{/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()} {#snippet actions()}
{#if restorable}<Button variant="primary" onclick={restoreLastKept} pending={restoring}>Restore the last kept version</Button>{/if} {#if restorable}<Button variant="primary" onclick={restore} pending={restoring}>Restore the last kept version</Button>{/if}
{/snippet} {/snippet}
</Banner> </Banner>
{/if} {/if}
@@ -50,7 +63,7 @@
{#if app.lostContact} {#if app.lostContact}
<Banner tone="down" live="alert"> <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} {#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 {when(new Date(app.lastUpdated).toISOString(), app.now)}.{/if} 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} {#snippet actions()}<Button onclick={retry}>Try again now</Button>{/snippet}
</Banner> </Banner>
{/if} {/if}
+31 -1
View File
@@ -5,7 +5,7 @@
// Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state, // 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. // the server clock offset and toasts. No business logic: everything shown comes from control.
import { call, setClientEvents } from "./api"; import { call, newKey, sentence, setClientEvents } from "./api";
import type { Overview } from "./types"; import type { Overview } from "./types";
export interface Toast { export interface Toast {
@@ -31,6 +31,10 @@ export const app = $state({
switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null }, switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null },
/** A renewal just installed (handoff §13.5). */ /** A renewal just installed (handoff §13.5). */
renewedUntil: null as null | string, 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). */ /** 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" }, panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" },
}); });
@@ -135,6 +139,12 @@ export function navigate(path: string): void {
app.path = 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") { if (typeof window !== "undefined") {
window.addEventListener("popstate", () => { window.addEventListener("popstate", () => {
app.path = location.pathname + location.search; app.path = location.pathname + location.search;
@@ -148,3 +158,23 @@ export function changesBlocked(): string | null {
if (o?.paused) return "Changes are paused."; if (o?.paused) return "Changes are paused.";
return null; 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;
}
+6 -1
View File
@@ -6,7 +6,7 @@
// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it. // runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it.
import { get } from "./api"; import { get } from "./api";
import { refresh } from "./app.svelte"; import { app, refresh } from "./app.svelte";
import type { ApplyView } from "./types"; import type { ApplyView } from "./types";
export const FINAL = ["kept", "reverted", "failed", "needs_attention"]; export const FINAL = ["kept", "reverted", "failed", "needs_attention"];
@@ -36,6 +36,11 @@ export function follow(id: string, onupdate: (a: ApplyView) => void, every = 100
remember(id); remember(id);
const tick = async () => { const tick = async () => {
if (stopped) return; 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 { try {
const a = await get<ApplyView>(`/applies/${encodeURIComponent(id)}`); const a = await get<ApplyView>(`/applies/${encodeURIComponent(id)}`);
if (stopped) return; if (stopped) return;
+18 -2
View File
@@ -25,6 +25,21 @@ export function when(iso: string | null | undefined, now = Date.now()): string {
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`; 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". */ /** "14 November 2026 at 14:20". */
export function longDate(iso: string | null | undefined, withTime = true): string { export function longDate(iso: string | null | undefined, withTime = true): string {
if (!iso) return ""; if (!iso) return "";
@@ -57,12 +72,13 @@ export function ago(iso: string | null | undefined, now: number): string {
return duration((now - Date.parse(iso)) / 1000) + " ago"; return duration((now - Date.parse(iso)) / 1000) + " ago";
} }
/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1). */ /** "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 }): string { export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }, short = false): string {
const parts = [`${c.healthy} healthy`]; const parts = [`${c.healthy} healthy`];
if (c.degraded) parts.push(`${c.degraded} degraded`); if (c.degraded) parts.push(`${c.degraded} degraded`);
if (c.down) parts.push(`${c.down} down`); if (c.down) parts.push(`${c.down} down`);
if (c.unknown) parts.push(`${c.unknown} not checked`); if (c.unknown) parts.push(`${c.unknown} not checked`);
if (short) return parts.join(", ");
return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`; return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`;
} }
+5 -2
View File
@@ -113,6 +113,7 @@ export interface PkiRequest {
device_id: string | null; device_id: string | null;
name: string | null; name: string | null;
csr_pem: string | null; csr_pem: string | null;
csr_sha256?: string | null;
not_after: string | null; not_after: string | null;
message_code: string; message_code: string;
message: string; message: string;
@@ -136,7 +137,7 @@ export interface EngineView {
since: string | null; since: string | null;
target: string | null; target: string | null;
switchable: boolean; switchable: boolean;
fallback_ready: { built_at: string | null; current: boolean } | null; fallback_ready: { built_at: string | null; current: boolean; compared: number; matched: number; differences: string[] } | null;
last_error: Reason | null; last_error: Reason | null;
notes: Blocked[]; notes: Blocked[];
} }
@@ -154,12 +155,13 @@ export interface Overview {
engine: EngineView; engine: EngineView;
last_apply: ApplyView | null; last_apply: ApplyView | null;
undo: UndoView; undo: UndoView;
active_apply: { id: string; state: string; summary: string; seconds_left: number | null; queued: number } | null; 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; repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null;
intermediate: IntermediateView | 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; 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: Blocked | null;
paused_reason: string | null; paused_reason: string | null;
paused_detail?: string | null;
health_error: Blocked | null; health_error: Blocked | null;
rev: string | null; rev: string | null;
viewer?: { name: string; via: string } | null; viewer?: { name: string; via: string } | null;
@@ -234,6 +236,7 @@ export interface CertsView {
root: { offline: boolean; subject: string; not_after: string; sha256: string }; root: { offline: boolean; subject: string; not_after: string; sha256: string };
devices: DeviceRow[]; devices: DeviceRow[];
device_lifetime_days: number; device_lifetime_days: number;
device_valid_until: string | null;
server_lifetime_days: number; server_lifetime_days: number;
approval: string; approval: string;
requests: PkiRequest[]; requests: PkiRequest[];
+10 -6
View File
@@ -11,7 +11,7 @@
import IntermediateBanner from "../components/IntermediateBanner.svelte"; import IntermediateBanner from "../components/IntermediateBanner.svelte";
import { ApiError, del, get, post, sentence } from "../lib/api"; import { ApiError, del, get, post, sentence } from "../lib/api";
import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte"; import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { shortDate, when } from "../lib/format"; import { atTime, shortDate } from "../lib/format";
import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types"; import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types";
let { newDevice }: { newDevice: boolean } = $props(); let { newDevice }: { newDevice: boolean } = $props();
@@ -120,7 +120,11 @@
} }
const lifetime = $derived(certs?.device_lifetime_days ?? 365); const lifetime = $derived(certs?.device_lifetime_days ?? 365);
const until = $derived(shortDate(new Date(Date.now() + lifetime * 86_400_000).toISOString())); // 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] => { const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => {
switch (certs?.intermediate?.state) { switch (certs?.intermediate?.state) {
case "ok": return ["healthy", "valid"]; case "ok": return ["healthy", "valid"];
@@ -187,18 +191,18 @@
<p class="ia-hint" id="device-name-h">Shown in this list and inside the certificate.</p> <p class="ia-hint" id="device-name-h">Shown in this list and inside the certificate.</p>
</div> </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" }]} /> <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">Valid for {lifetime} days, until {until}. It lets this device into hosts that ask for a Domi device certificate.</p> <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> </form>
{:else if request.state === "waiting"} {:else if request.state === "waiting"}
<p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p> <p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p>
<p>Approve it on the server, and only if it shows the same code:</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> <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} {#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 {Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")}. Nothing is issued until it is approved.</p> <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> <div><Button onclick={cancelRequest}>Cancel request</Button></div>
<span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span> <span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span>
{:else if issuedDevice} {:else if issuedDevice}
<Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved at {when(request?.approved_at, app.now)}.{/snippet}</Banner> <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"> <div class="buttons">
<Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button> <Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button>
<Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button> <Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button>
+1 -2
View File
@@ -9,7 +9,7 @@
import HostPanel from "../components/HostPanel.svelte"; import HostPanel from "../components/HostPanel.svelte";
import { get, post, sentence } from "../lib/api"; import { get, post, sentence } from "../lib/api";
import { app, changesBlocked, navigate } from "../lib/app.svelte"; import { app, changesBlocked, navigate } from "../lib/app.svelte";
import { FIELD_LABEL, fieldValue, longDate, when } from "../lib/format"; import { FIELD_LABEL, fieldValue, when } from "../lib/format";
import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types"; import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types";
let { host, pick }: { host?: string; pick?: string } = $props(); let { host, pick }: { host?: string; pick?: string } = $props();
@@ -163,7 +163,6 @@
{#if editFrom} {#if editFrom}
<HostPanel prefill={editFrom} hostname={undefined} onclose={() => { editFrom = null; void load(); }} /> <HostPanel prefill={editFrom} hostname={undefined} onclose={() => { editFrom = null; void load(); }} />
{/if} {/if}
<span class="sr-only">{longDate(entry?.at)}</span>
<style> <style>
.cols { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; } .cols { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; }
+15 -24
View File
@@ -3,16 +3,17 @@
- file, You can obtain one at https://mozilla.org/MPL/2.0/. --> - file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts"> <script lang="ts">
// Handoff §5: the main screen. // Handoff §5: the main screen.
import { Banner, Button, Icon } from "@ianitor/ui"; import { tick } from "svelte";
import { Banner, Button } from "@ianitor/ui";
import ChangeBar from "../components/ChangeBar.svelte"; import ChangeBar from "../components/ChangeBar.svelte";
import EnginePopover from "../components/EnginePopover.svelte"; import EngineChip from "../components/EngineChip.svelte";
import HostList from "../components/HostList.svelte"; import HostList from "../components/HostList.svelte";
import HostPanel from "../components/HostPanel.svelte"; import HostPanel from "../components/HostPanel.svelte";
import IntermediateBanner from "../components/IntermediateBanner.svelte"; import IntermediateBanner from "../components/IntermediateBanner.svelte";
import ShareDialog from "../components/ShareDialog.svelte"; import ShareDialog from "../components/ShareDialog.svelte";
import { call, newKey, post, sentence } from "../lib/api"; import { call, newKey, post, sentence } from "../lib/api";
import { app, changesBlocked, navigate, refresh, toast } from "../lib/app.svelte"; import { app, changesBlocked, navigate, refresh, toast } from "../lib/app.svelte";
import { countsSentence, when } from "../lib/format"; import { atTime, countsSentence } from "../lib/format";
import type { ApplyView, HostSpec } from "../lib/types"; import type { ApplyView, HostSpec } from "../lib/types";
let { route }: { route: { newHost: boolean; edit?: string } } = $props(); let { route }: { route: { newHost: boolean; edit?: string } } = $props();
@@ -25,12 +26,18 @@
const panelOpen = $derived(route.newHost || !!route.edit || app.panel?.kind === "host"); const panelOpen = $derived(route.newHost || !!route.edit || app.panel?.kind === "host");
const blocked = $derived(changesBlocked()); const blocked = $derived(changesBlocked());
function closePanel() { async function closePanel() {
prefill = null; prefill = null;
focusField = undefined; focusField = undefined;
if (app.panel?.kind === "host") app.panel = null; if (app.panel?.kind === "host") app.panel = null;
if (route.newHost || route.edit) navigate("/"); if (route.newHost || route.edit) navigate("/");
void refresh(); 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) { async function remove(h: string) {
@@ -62,27 +69,15 @@
} }
} }
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> </script>
<div class="head"> <div class="head">
<div> <div>
<h1 class="ia-display">Hosts</h1> <h1 class="ia-display">Hosts</h1>
{#if o}<p class="ia-text2">{countsSentence(o.counts)}</p>{/if} {#if o}<p class={app.phone ? "ia-sub" : "ia-text2"}>{countsSentence(o.counts, app.phone)}</p>{/if}
</div> </div>
<div class="actions"> <div class="actions">
{#if o} {#if !app.phone}<EngineChip />{/if}
<button type="button" class="ia-engine" 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}
<Button variant="primary" icon="plus" label="Add a host" disabled={!!blocked} describedby={blocked ? "add-blocked" : undefined} onclick={() => navigate("/hosts/new")}>Host</Button> <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} {#if blocked}<span class="sr-only" id="add-blocked">{blocked}</span>{/if}
</div> </div>
@@ -115,7 +110,7 @@
<hr class="ia-ornament" /> <hr class="ia-ornament" />
<p class="ia-muted footer"> <p class="ia-muted footer">
Routes live in the {o.repo.name} repository, one file per host. Routes live in the {o.repo.name} repository, one file per host.
{#if o.repo.last_push_at}Last pushed to Gitea at {when(o.repo.last_push_at, app.now)}.{/if} {#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} {#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> <button type="button" class="domi-btn link" onclick={() => navigate("/history")}>See history</button>
</p> </p>
@@ -129,13 +124,9 @@
{#if app.panel?.kind === "share"} {#if app.panel?.kind === "share"}
<ShareDialog hostname={app.panel.hostname} onclose={() => { app.panel = null; void refresh(); }} /> <ShareDialog hostname={app.panel.hostname} onclose={() => { app.panel = null; void refresh(); }} />
{/if} {/if}
{#if app.panel?.kind === "engine"}
<EnginePopover onclose={() => (app.panel = null)} />
{/if}
<style> <style>
.head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 16px; } .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; } .actions { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
.footer { text-align: center; } .footer { text-align: center; }
@media (max-width: 719.98px) { .desktop { display: none; } }
</style> </style>
+24 -6
View File
@@ -16,6 +16,20 @@
let pending = $state(false); let pending = $state(false);
let starting = $state(false); let starting = $state(false);
const base = $derived(r?.file_base ?? `domi-intermediate-${new Date().toISOString().slice(0, 10)}`); 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) { function save(text: string, name: string, type: string) {
const url = URL.createObjectURL(new Blob([text], { type })); const url = URL.createObjectURL(new Blob([text], { type }));
@@ -88,15 +102,19 @@
<p class="ia-label">Step 1</p> <p class="ia-label">Step 1</p>
<h2 class="ia-h3">Download the request</h2> <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> <p class="ia-text2">This file asks the Domi root to sign a new intermediate certificate. It holds no secret.</p>
<p>Check that the offline computer shows the same code: <span class="ia-code small" aria-label="Match code {r.match_code}">{r.match_code}</span></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>
<div class="row"><Button icon="copy" onclick={download}>Download the request (.csr)</Button><Button icon="copy" onclick={downloadExt}>Download the signing settings (.ext)</Button></div>
</section> </section>
<section class="step"> <section class="step">
<p class="ia-label">Step 2</p> <p class="ia-label">Step 2</p>
<h2 class="ia-h3">Sign it on the offline computer</h2> <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, then run:</p> <p class="ia-text2">Copy both files to the offline computer that holds the Domi root.</p>
<pre class="ia-secret ia-cmd">{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`}</pre> <p class="ia-text2">First check that the request is the one this server made. This prints its fingerprint:</p>
<p class="ia-muted">Before signing, check that the request is the one this page shows: <code>openssl req -in {base}.csr -noout -subject</code>. (On a computer with Ianitor installed, <code>ianitor-control ca sign</code> does the same and shows the match code.)</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>
<section class="step"> <section class="step">
<p class="ia-label">Step 3</p> <p class="ia-label">Step 3</p>
@@ -121,5 +139,5 @@
<style> <style>
.row { display: flex; gap: 8px; flex-wrap: wrap; } .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; } .step { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
.small { font-size: 1.4rem; } .fp { word-break: break-all; color: var(--accent-strong); }
</style> </style>
+5 -5
View File
@@ -8,7 +8,7 @@
import { Banner, Button, Dialog, Segmented } from "@ianitor/ui"; import { Banner, Button, Dialog, Segmented } from "@ianitor/ui";
import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api"; import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api";
import { app, navigate, toast } from "../lib/app.svelte"; import { app, navigate, toast } from "../lib/app.svelte";
import { shortDate, when } from "../lib/format"; import { longDate, shortDate, whenInline } from "../lib/format";
import type { CreatedToken, ShareLink, TokenRow } from "../lib/types"; import type { CreatedToken, ShareLink, TokenRow } from "../lib/types";
let { tab }: { tab: string } = $props(); let { tab }: { tab: string } = $props();
@@ -164,7 +164,7 @@
<div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel"> <div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel">
{#if tab === "general"} {#if tab === "general"}
<p class="ia-label">Routes repository</p> <p class="ia-label">Routes repository</p>
<p>{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + when(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</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 class="ia-label">Health watch after apply</p>
<p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p> <p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p>
<p class="ia-label">Signed in</p> <p class="ia-label">Signed in</p>
@@ -186,7 +186,7 @@
<div class="grow"> <div class="grow">
<span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span> <span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span>
<span class="ia-sub" style="display:block"> <span class="ia-sub" style="display:block">
{#if revoked[t.id]}Revoked {when(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${when(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if} {#if revoked[t.id]}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> </span>
</div> </div>
{#if !revoked[t.id] && !t.revoked_at} {#if !revoked[t.id] && !t.revoked_at}
@@ -221,7 +221,7 @@
{#each active as l (l.id)} {#each active as l (l.id)}
<li> <li>
<div class="grow"><strong>{l.hostname}</strong>{l.path_prefix !== "/" ? l.path_prefix : ""} <div class="grow"><strong>{l.hostname}</strong>{l.path_prefix !== "/" ? l.path_prefix : ""}
<span class="ia-sub" style="display:block">Made {when(l.created_at, app.now)} · expires {when(l.expires_at, app.now)}{l.has_password ? " · password" : ""}</span></div> <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> <Button small onclick={() => stop(l)}>Stop this link</Button>
</li> </li>
{/each} {/each}
@@ -255,7 +255,7 @@
<Button variant={tokenCopied ? "quiet" : "primary"} icon="copy" onclick={copyToken} data-autofocus>{tokenCopied ? "Copy again" : "Copy token"}</Button> <Button variant={tokenCopied ? "quiet" : "primary"} icon="copy" onclick={copyToken} data-autofocus>{tokenCopied ? "Copy again" : "Copy token"}</Button>
</div> </div>
{#if tokenCopied}<p role="status">Copied. Paste it into Custos now. Ianitor cannot show it again.</p>{/if} {#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 ${shortDate(made.expires_at)}.` : "Never expires."}</p> <p class="ia-muted">{made.expires_at ? `Expires on ${longDate(made.expires_at, false)}.` : "Never expires."}</p>
{#if askClose} {#if askClose}
<p role="alert">Close without copying? The token cannot be shown again. <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> <Button small onclick={() => (askClose = false)}>Go back</Button> <Button small variant="danger" onclick={() => closeToken(true)}>Close anyway</Button></p>
+97
View File
@@ -0,0 +1,97 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The release's screenshots (docs/release.md): every shot's screen is drawn from the demo control
// plane alone (each click and wait selector found, no call unanswered), and nothing the demo
// serves or the page shows names a real host, address or person.
import { cleanup, render, waitFor } from "@testing-library/svelte";
import { afterEach, describe, expect, it } from "vitest";
import App from "../src/App.svelte";
import { app } from "../src/lib/app.svelte";
import { SHOTS, demoApi } from "./demo";
const ALLOWED_TLDS = new Set(["test", "example", "invalid"]);
const DOC_NETS = ["192.0.2.", "198.51.100.", "203.0.113."];
const FORBIDDEN = ["mark", "marek", "novak", "flowers", "esp32", "hyperv"];
/** What in a text could be real: addresses outside the documentation ranges, names outside .test. */
function realLooking(text: string): string[] {
const found: string[] = [];
for (const m of text.matchAll(/(?<![\w.])\d{1,3}(?:\.\d{1,3}){3}(?![\w.])/g)) {
if (m[0] !== "127.0.0.1" && !DOC_NETS.some((n) => m[0].startsWith(n))) found.push(m[0]);
}
for (const m of text.matchAll(/(?<![\w.-])(?:[a-z0-9-]+\.)+([a-z][a-z0-9-]*)(?![\w-])/gi)) {
if (!ALLOWED_TLDS.has(m[1].toLowerCase())) found.push(m[0]);
}
for (const w of FORBIDDEN) if (new RegExp(`\\b${w}\\b`, "i").test(text)) found.push(w);
return found;
}
let served: { status: number; path: string; text: string | null }[] = [];
function start(path: string) {
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 = [];
served = [];
const api = demoApi();
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 a = api(init?.method ?? "GET", path, init?.body ? JSON.parse(String(init.body)) : {});
served.push({ status: a.status, path, text: a.text });
return new Response(a.text, { status: a.status, headers: { "Content-Type": "application/json" } });
}) as typeof fetch;
render(App);
}
function pageText(): string[] {
const out: string[] = [];
const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
for (let n = walk.nextNode(); n; n = walk.nextNode()) if (n.textContent?.trim()) out.push(n.textContent);
document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("input, textarea").forEach((i) => out.push(i.value));
document.querySelectorAll("[href]").forEach((a) => out.push(a.getAttribute("href") ?? ""));
return out;
}
afterEach(() => cleanup());
describe("realLooking", () => {
it("passes invented names and refuses real-looking ones", () => {
expect(realLooking("wiki.home.test http://192.0.2.10:3000 on 127.0.0.1 for ada")).toEqual([]);
expect(realLooking("http://10.0.0.2:3000")).toEqual(["10.0.0.2"]);
expect(realLooking("gitea.example.cz and Mark's phone")).toEqual(["gitea.example.cz", "mark"]);
expect(realLooking("flowers.stage")).toEqual(["flowers.stage", "flowers"]);
});
});
describe("the release's screenshots from the demo control plane", () => {
for (const shot of SHOTS) {
it(`${shot.name}: drawn from invented data only`, async () => {
start(shot.path);
for (const sel of shot.click ?? []) {
const el = await waitFor(() => {
const e = document.querySelector<HTMLElement>(sel);
expect(e, `click ${sel}`).not.toBeNull();
return e as HTMLElement;
}, { timeout: 5000 });
el.click();
}
await waitFor(() => expect(document.querySelector(shot.wait), `wait ${shot.wait}`).not.toBeNull(), { timeout: 5000 });
expect(served.filter((s) => s.status === 404).map((s) => s.path)).toEqual([]);
// Control's codes (apply.kept, pki.renew_due) are dotted words, not names.
const json = served.map((s) => (s.text ?? "").replace(/"(?:code|message_code|error_code)":"[^"]*"/g, ""));
const seen = [...json, ...pageText()];
expect(seen.flatMap(realLooking)).toEqual([]);
});
}
});
+236
View File
@@ -0,0 +1,236 @@
// 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 demo control plane for the release's screenshots (docs/release.md): control's answers
// (docs/api.md) for a small invented home server, built on the click smoke test's stand-in
// (mockApi.ts), whose routes answer every call the demo does not replace. Everything here is
// invented: hostnames under .test, addresses in the documentation ranges (RFC 5737), people ada
// and felix, made-up commits and fingerprints. demo.test.ts renders every shot from it and fails
// on any other name or address.
import { apply, host, mockRoutes, newMock, respond, type Route } from "./mockApi";
/** One screenshot: the page, the selectors clicked in order, and the selector that means "drawn". */
export interface Shot {
name: string;
title: string;
path: string;
click?: string[];
wait: string;
}
/** The viewport in CSS pixels; the PNGs are this size. */
export const SIZE = { width: 1440, height: 900 } as const;
export const SHOTS: Shot[] = [
{ name: "hosts", title: "Every host, its health and where it sends traffic", path: "/", wait: "[aria-label=Hosts] .ia-row:nth-child(8) .ia-host" },
{ name: "host", title: "Editing a host", path: "/hosts/wiki.home.test/edit", wait: "#host-form input[readonly]" },
{ name: "engine", title: "Pingora serving, Caddy ready as the fallback", path: "/", click: ["[data-engine-chip]"], wait: "dialog.ia-popover[open] .ia-card" },
{ name: "history", title: "History: going back to a kept version", path: "/history/ch_0006", wait: "section.detail ul li:nth-child(2)" },
{ name: "certificates", title: "The Domi CA and the device certificates", path: "/certificates", wait: "ul.devices li:nth-child(5)" },
];
type Json = Record<string, unknown>;
const DAY = 86_400;
const at = (s: number) => new Date(Date.now() + s * 1000).toISOString();
interface Health {
state: string;
latency?: number | null;
upstreams?: Json[];
failure?: Json | null;
}
function demoHost(hostname: string, upstreams: string[], h: Health, over: Json = {}): Json {
const base = host(hostname, false);
return {
...base,
upstreams,
health: {
state: h.state,
last_check_at: h.state === "unknown" ? null : at(-4),
latency_ms: h.latency ?? null,
since: at(-6 * DAY),
failure: h.failure ?? null,
upstreams: h.upstreams ?? [],
},
...over,
};
}
const MUSIC = ["http://192.0.2.20:4533", "http://192.0.2.21:4533"];
function hosts(): Json[] {
return [
demoHost("wiki.home.test", ["http://192.0.2.10:3000"], { state: "healthy", latency: 9 }, { share_links: true }),
demoHost("photos.home.test", ["http://192.0.2.11:2342"], { state: "healthy", latency: 23 }),
demoHost("recipes.home.test", ["http://192.0.2.12:9000"], { state: "healthy", latency: 14 }, { added_at: at(-2 * 3600) }),
demoHost("music.home.test", MUSIC, {
state: "degraded",
latency: 18,
failure: { kind: "refused", upstream: MUSIC[1], count: 3, of: 3 },
upstreams: [
{ url: MUSIC[0], state: "healthy", last_check_at: at(-4), latency_ms: 18, failure_kind: null },
{ url: MUSIC[1], state: "down", last_check_at: at(-4), latency_ms: null, failure_kind: "refused" },
],
}),
demoHost("cameras.home.test", ["https://192.0.2.30:7443"], { state: "healthy", latency: 31 }, { device_certs: true }),
demoHost("status.home.test", ["http://192.0.2.40:3001"], { state: "healthy", latency: 6 }, { tls: "letsencrypt", auth: "none" }),
demoHost("printer.home.test", ["http://192.0.2.50:631"], { state: "unknown" }, { websockets: false }),
];
}
function lastApply(): Json {
return {
...apply("ch_0008", "kept", "Added recipes.home.test", ["recipes.home.test"]),
created_at: at(-2 * 3600 - 70),
finished_at: at(-2 * 3600),
reason: { code: "apply.kept", message: "recipes.home.test is live. Health checks passed for 60 s." },
commit_short: "c41d7e2",
push: { state: "pushed", at: at(-2 * 3600), error_code: null, next_try_at: null },
};
}
function intermediate(): Json {
return { state: "ok", subject: "Demo Intermediate CA", not_after: at(212 * DAY), days_left: 212, renewal: null, banner: null };
}
function overview(): Json {
const list = hosts();
const count = (s: string) => list.filter((h) => (h.health as Json).state === s).length;
return {
counts: { hosts: list.length, healthy: count("healthy"), degraded: count("degraded"), down: count("down"), unknown: count("unknown") },
hosts: list,
engine: {
running: "pingora",
state: "running",
since: at(-6 * DAY),
target: null,
switchable: true,
fallback_ready: {
built_at: at(-2 * 3600),
current: true,
compared: list.length,
matched: list.length,
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: lastApply(),
undo: {
available: true,
target: { change_id: "ch_0008", summary: "Added recipes.home.test", kept_at: at(-2 * 3600), commit_short: "c41d7e2" },
effect: "Removes recipes.home.test",
blocked: null,
},
active_apply: null,
repo: { name: "home-routes", last_push_at: at(-2 * 3600), unpushed: 0, push_error_code: null },
intermediate: intermediate(),
site: { forward_auth_configured: true, acme_configured: true, secrets: ["photos_api_key"], watch_seconds: 60, share_links_available: true, auth_logout_url: "https://auth.home.test/logout" },
paused: null,
paused_reason: null,
health_error: null,
rev: "rev-demo-8",
viewer: { name: "ada", via: "authelia" },
};
}
function spec(hostname: string): Json | null {
const row = hosts().find((h) => h.hostname === hostname);
if (!row) return null;
const wiki = hostname === "wiki.home.test";
return {
hostname,
upstreams: row.upstreams,
tls: row.tls,
auth: row.auth,
websockets: row.websockets,
share_links: row.share_links,
device_certs: row.device_certs,
access_log: wiki ? "truncated" : "off",
health_check: (row.health as Json).state === "unknown" ? null : { path: wiki ? "/healthz" : "/", interval_secs: 30 },
request_headers: [],
response_headers: wiki ? [{ action: "set", name: "X-Frame-Options", value: "SAMEORIGIN" }] : [],
};
}
const HISTORY = [
{ change_id: "ch_0008", summary: "Added recipes.home.test", kind: "add", state: "kept", ago: 2 * 3600, commit_short: "c41d7e2", hosts: ["recipes.home.test"], reason_short: null },
{ change_id: "ch_0007", summary: "Changed music.home.test", kind: "edit", state: "kept", ago: 1 * DAY, commit_short: "8e03b5a", hosts: ["music.home.test"], reason_short: null },
{ change_id: "ch_0006", summary: "Turned share links on for wiki.home.test", kind: "share_links", state: "kept", ago: 2 * DAY, commit_short: "5a9f210", hosts: ["wiki.home.test"], reason_short: null },
{ change_id: "ch_0005", summary: "Changed photos.home.test", kind: "edit", state: "reverted", ago: 3 * DAY, commit_short: null, hosts: ["photos.home.test"], reason_short: "photos.home.test answered 502 during the watch" },
{ change_id: "ch_0004", summary: "Added cameras.home.test", kind: "add", state: "kept", ago: 5 * DAY, commit_short: "0b7c4e9", hosts: ["cameras.home.test"], reason_short: null },
{ change_id: "ch_0003", summary: "Added printer.home.test", kind: "add", state: "kept", ago: 9 * DAY, commit_short: "e2d81f6", hosts: ["printer.home.test"], reason_short: null },
{ change_id: "ch_0002", summary: "Added status.home.test", kind: "add", state: "kept", ago: 12 * DAY, commit_short: "73a6c05", hosts: ["status.home.test"], reason_short: null },
{ change_id: "ch_0001", summary: "Added wiki.home.test", kind: "add", state: "kept", ago: 20 * DAY, commit_short: "1f4b9a3", hosts: ["wiki.home.test"], reason_short: null },
];
function history(): Json {
return { entries: HISTORY.map(({ ago, ...e }) => ({ ...e, at: at(-ago) })), next_before: null };
}
function restorePreview(id: string): Json {
if (id === "ch_0008") return { restorable: false, same_as_current: true, changes: [], blocked: { code: "restore.same", message: "This version is the same as the current one." } };
return {
restorable: true,
same_as_current: false,
changes: [
{ hostname: "recipes.home.test", effect: "removed", fields: [] },
{ hostname: "music.home.test", effect: "changed", fields: [{ field: "upstreams", from: MUSIC.join(", "), to: MUSIC[0] }] },
],
blocked: null,
};
}
function certs(): Json {
const device = (id: string, name: string, kind: string, made: number, until: number, revoked: number | null = null) => ({
id,
name,
kind,
created_at: at(-made * DAY),
not_after: at(until * DAY),
state: revoked === null ? "valid" : "revoked",
revoked_at: revoked === null ? null : at(-revoked * DAY),
});
return {
intermediate: intermediate(),
root: { offline: true, subject: "Demo Root CA", not_after: at(3000 * DAY), sha256: "5c0f9e2a71d84b36a8e1f40c2d9b7e6315a2c8d04f9b1e7a6c3d5f8e0b2a4c61" },
devices: [
device("dv_1", "ada's phone", "phone", 40, 325),
device("dv_2", "felix's laptop", "computer", 61, 304),
device("dv_3", "Kitchen tablet", "phone", 345, 20),
device("dv_4", "Notes app on the desk PC", "app", 12, 353),
device("dv_5", "Old phone", "phone", 200, 165, 30),
],
device_lifetime_days: 365,
device_valid_until: null,
server_lifetime_days: 90,
approval: "manual",
requests: [],
};
}
/** The demo's own answers, first; the smoke test's stand-in answers the rest. */
export function demoRoutes(): Route[] {
return [
["GET", /^\/overview$/, () => [200, overview()]],
["GET", /^\/hosts\/([^/?]+)$/, (mm) => {
const s = spec(decodeURIComponent(mm[1]));
return s ? [200, { host: s, rev: "rev-demo-8" }] : [404, { error: { code: "host.not_found", message: "There is no such host.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "demo" }];
}],
["GET", /^\/history(\?.*)?$/, () => [200, history()]],
["GET", /^\/history\/([^/]+)\/restore-preview$/, (mm) => [200, restorePreview(decodeURIComponent(mm[1]))]],
["GET", /^\/certs$/, () => [200, certs()]],
["GET", /^\/settings$/, () => [200, { repo: { name: "home-routes", last_push_at: at(-2 * 3600) }, watch_seconds: 60 }]],
...mockRoutes(newMock()),
];
}
/** Control's API for the demo: `path` is what follows /api/v1 (with its query). */
export function demoApi(): (method: string, path: string, body: Json) => { status: number; text: string | null } {
const routes = demoRoutes();
return (method, path, body) => respond(routes, method.toUpperCase(), path, body);
}
+35 -1
View File
@@ -146,7 +146,8 @@ describe("ROADMAP §4 flows, clicks counted", () => {
start(); start();
await click(await screen.findByRole("button", { name: "Renew" })); await click(await screen.findByRole("button", { name: "Renew" }));
await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true)); await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true));
await screen.findByLabelText("Match code 47 19 83"); // 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); expect(clicks).toBe(1);
}); });
@@ -176,6 +177,39 @@ describe("focus", () => {
await user.keyboard("recipes.home.test"); await user.keyboard("recipes.home.test");
expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("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", () => { describe("sign-in and contact", () => {
+33 -16
View File
@@ -3,7 +3,8 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/. // 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 // 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. // smoke tests can walk every §4 flow and count its clicks. Its builders and routes are also the
// base of the screenshots' demo control plane (demo.ts, docs/release.md).
type Json = Record<string, unknown>; type Json = Record<string, unknown>;
@@ -22,7 +23,7 @@ export interface Mock {
const now = () => new Date().toISOString(); const now = () => new Date().toISOString();
const later = (s: number) => new Date(Date.now() + s * 1000).toISOString(); const later = (s: number) => new Date(Date.now() + s * 1000).toISOString();
function host(hostname: string, share: boolean) { export function host(hostname: string, share: boolean) {
return { return {
hostname, hostname,
upstreams: ["http://10.0.0.2:3000"], upstreams: ["http://10.0.0.2:3000"],
@@ -37,7 +38,7 @@ function host(hostname: string, share: boolean) {
}; };
} }
function apply(id: string, state: string, summary: string, hosts: string[]) { export function apply(id: string, state: string, summary: string, hosts: string[]) {
return { return {
id, id,
change_id: id, change_id: id,
@@ -58,12 +59,30 @@ function apply(id: string, state: string, summary: string, hosts: string[]) {
}; };
} }
export function installMock(): Mock { /** One API call: method, the path after /api/v1, and its answer as [status, body]. */
const m: Mock = { export type Route = [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]];
export function newMock(): Mock {
return {
calls: [], calls: [],
state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] }, state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] },
}; };
}
/** The first route that matches answers, with server_time added as control does; else control's 404. */
export function respond(routes: Route[], method: string, path: string, body: Json): { status: number; text: string | null } {
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 { status, text: status === 204 ? null : JSON.stringify(withTime) };
}
}
return { status: 404, text: 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" }) };
}
export function mockRoutes(m: Mock): Route[] {
const overview = (): Json => ({ const overview = (): Json => ({
counts: { hosts: 2 + m.state.hostsAdded.length, healthy: 2, degraded: 0, down: 0, unknown: 0 }, 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))], hosts: [host("wiki.home.test", true), host("photos.home.test", false), ...m.state.hostsAdded.map((h) => host(h, false))],
@@ -73,7 +92,7 @@ export function installMock(): Mock {
since: now(), since: now(),
target: null, target: null,
switchable: true, switchable: true,
fallback_ready: { built_at: now(), current: 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, last_error: null,
notes: [], notes: [],
}, },
@@ -108,7 +127,7 @@ export function installMock(): Mock {
server_time: now(), server_time: now(),
}); });
const routes: [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]][] = [ return [
["GET", /^\/overview$/, () => [200, overview()]], ["GET", /^\/overview$/, () => [200, overview()]],
["POST", /^\/hosts\/validate/, () => [200, { message: "This host can be applied." }]], ["POST", /^\/hosts\/validate/, () => [200, { message: "This host can be applied." }]],
["POST", /^\/hosts$/, (_, b) => { ["POST", /^\/hosts$/, (_, b) => {
@@ -152,6 +171,11 @@ export function installMock(): Mock {
["POST", /^\/tokens$/, (_, b) => [201, { id: "tk_1", name: b.name, token: "ian_tk1_secretvalue", expires_at: later(365 * 86400) }]], ["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 }]], ["GET", /^\/share-links$/, () => [200, { items: [], epoch: 0 }]],
]; ];
}
export function installMock(): Mock {
const m = newMock();
const routes = mockRoutes(m);
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url; const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url;
@@ -159,15 +183,8 @@ export function installMock(): Mock {
const method = (init?.method ?? "GET").toUpperCase(); const method = (init?.method ?? "GET").toUpperCase();
const body = init?.body ? JSON.parse(String(init.body)) : {}; const body = init?.body ? JSON.parse(String(init.body)) : {};
m.calls.push({ method, path, body }); m.calls.push({ method, path, body });
for (const [mm, re, f] of routes) { const a = respond(routes, method, path, body);
const match = path.match(re); return new Response(a.text, { status: a.status, headers: { "Content-Type": "application/json" } });
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; }) as typeof fetch;
return m; return m;
+1
View File
@@ -281,6 +281,7 @@ pub async fn overview(
intermediate: super::pki::intermediate_view(c), intermediate: super::pki::intermediate_view(c),
site, site,
paused_reason: c.effective_pause().map(|p| p.code), paused_reason: c.effective_pause().map(|p| p.code),
paused_detail: c.effective_pause().and_then(|p| p.detail),
paused: c.effective_pause().map(|p| Blocked { paused: c.effective_pause().map(|p| Blocked {
code: "control.paused".into(), code: "control.paused".into(),
message: message("control.paused", &messages::params([("reason", p.message)])), message: message("control.paused", &messages::params([("reason", p.message)])),
+2
View File
@@ -544,6 +544,8 @@ pub struct Overview {
/// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`, /// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`,
/// `repo.unreadable`, …), so the UI can offer the right action. /// `repo.unreadable`, …), so the UI can offer the right action.
pub paused_reason: Option<String>, 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`). /// Set when control cannot read health from edge (`health.unavailable`).
pub health_error: Option<Blocked>, pub health_error: Option<Blocked>,
pub rev: Option<String>, pub rev: Option<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);
}
}
+230 -22
View File
@@ -4,7 +4,9 @@
//! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep //! 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 //! working under Caddy): loading a config through Caddy's admin API on its Unix socket
//! (`POST /load`, the whole JSON), and probing a host *through* Caddy for the health watch. //! (`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::net::SocketAddr;
use std::path::Path; use std::path::Path;
@@ -13,20 +15,14 @@ use std::time::{Duration, Instant};
const TIMEOUT: Duration = Duration::from_secs(10); const TIMEOUT: Duration = Duration::from_secs(10);
/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the /// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked).
/// old one). async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec<u8>), String> {
pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
#[cfg(unix)] #[cfg(unix)]
{ {
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
let head = format!(
"POST /load HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n",
config.len()
);
let exchange = async { let exchange = async {
let mut s = tokio::net::UnixStream::connect(socket).await?; let mut s = tokio::net::UnixStream::connect(socket).await?;
s.write_all(head.as_bytes()).await?; s.write_all(request).await?;
s.write_all(config).await?;
let mut buf = Vec::new(); let mut buf = Vec::new();
s.read_to_end(&mut buf).await?; s.read_to_end(&mut buf).await?;
Ok::<_, std::io::Error>(buf) Ok::<_, std::io::Error>(buf)
@@ -35,29 +31,69 @@ pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
.await .await
.map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())? .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}"))?; .map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?;
let text = String::from_utf8_lossy(&buf); let split = buf
let status: u16 = text .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(' ') .split(' ')
.nth(1) .nth(1)
.and_then(|s| s.parse().ok()) .and_then(|s| s.parse().ok())
.ok_or("no answer from Caddy's admin API")?; .ok_or("no answer from Caddy's admin API")?;
if (200..300).contains(&status) { Ok((status, buf[split + 4..].to_vec()))
Ok(())
} else {
let body = text.split("\r\n\r\n").nth(1).unwrap_or("").trim();
Err(format!(
"Caddy refused the config ({status}): {}",
body.chars().take(400).collect::<String>()
))
}
} }
#[cfg(not(unix))] #[cfg(not(unix))]
{ {
let _ = (socket, config); let _ = (socket, request);
Err("Caddy's admin socket needs Unix".into()) 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. /// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum Probe { pub enum Probe {
@@ -156,3 +192,175 @@ pub async fn probe(addr: SocketAddr, host: &str, path: &str) -> Probe {
)), )),
} }
} }
/// 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),
}
}
}
}
+18 -5
View File
@@ -164,6 +164,9 @@ pub struct Control {
pub(crate) apply_lock: tokio::sync::Mutex<()>, pub(crate) apply_lock: tokio::sync::Mutex<()>,
/// Held while an engine is switched or told to reload its device or certificate files. /// Held while an engine is switched or told to reload its device or certificate files.
pub(crate) engine_lock: tokio::sync::Mutex<()>, pub(crate) engine_lock: tokio::sync::Mutex<()>,
/// Serialises reading the device records and writing the device files (never held
/// across an apply or a switch).
pub(crate) devices_lock: tokio::sync::Mutex<()>,
/// Why the device files are not (yet) in force, until a retry succeeds. /// Why the device files are not (yet) in force, until a retry succeeds.
pub devices_problem: Mutex<Option<String>>, pub devices_problem: Mutex<Option<String>>,
} }
@@ -275,6 +278,7 @@ impl Control {
pause_saved: std::sync::atomic::AtomicBool::new(true), pause_saved: std::sync::atomic::AtomicBool::new(true),
apply_lock: tokio::sync::Mutex::new(()), apply_lock: tokio::sync::Mutex::new(()),
engine_lock: tokio::sync::Mutex::new(()), engine_lock: tokio::sync::Mutex::new(()),
devices_lock: tokio::sync::Mutex::new(()),
devices_problem: Mutex::new(None), devices_problem: Mutex::new(None),
cfg, cfg,
}); });
@@ -1541,8 +1545,12 @@ impl Control {
remove_if_exists(&p).map_err(|e| e.to_string())?; remove_if_exists(&p).map_err(|e| e.to_string())?;
} }
if caddy { if caddy {
// Caddy must run caddy.json again, the last good config. // Caddy must run caddy.json again, the last good config (with the device files as
// they are now); then no trial is out any more. Under the engine lock, so a device
// change that saw the trial and left the reload to this point is not lost.
let _engine = self.engine_lock.lock().await;
self.caddy_reload().await?; self.caddy_reload().await?;
crate::caddy_guard::disarm(&self.cfg.state_dir);
return Ok(rev); return Ok(rev);
} }
// Edge must now run edge.json, the last good config. If it confirmed the trial after // Edge must now run edge.json, the last good config. If it confirmed the trial after
@@ -1703,10 +1711,15 @@ impl Control {
self.unpause(); self.unpause();
self.sync_files().await; self.sync_files().await;
} }
if self.engine_running() == "caddy" if self.engine_running() == "caddy" {
&& let Err(e) = self.caddy_reload().await match self.caddy_reload().await {
{ Ok(()) => crate::caddy_guard::disarm(&self.cfg.state_dir),
log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}"); Err(e) => {
log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}")
}
}
} else {
crate::caddy_guard::disarm(&self.cfg.state_dir);
} }
if let Err(e) = self.shares.ensure_revocation_file() { if let Err(e) = self.shares.ensure_revocation_file() {
log::error!(target: "ianitor::share", "{e}"); log::error!(target: "ianitor::share", "{e}");
+308 -112
View File
@@ -3,13 +3,44 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/. // 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 //! 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 //! pipeline and journal as with edge; only the trial, the watch and the revert differ:
//! trial is loaded into Caddy through its admin socket, the touched hosts are probed through //!
//! Caddy, and a revert loads caddy.json (the last good config) again. //! - 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 super::*;
use crate::caddy_guard;
use crate::caddy_link::{self, Probe}; 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 { impl Control {
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`). /// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> { pub fn caddy_socket(&self) -> Option<std::path::PathBuf> {
@@ -20,14 +51,87 @@ impl Control {
.map(std::path::PathBuf::from) .map(std::path::PathBuf::from)
} }
/// Load caddy.json (the last good config) into the running Caddy. /// 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> { pub async fn caddy_reload(&self) -> Result<(), String> {
let sock = self let sock = self
.caddy_socket() .caddy_socket()
.ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?; .ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?;
let text = std::fs::read(&self.cfg.caddy.config) let text = std::fs::read(&self.cfg.caddy.config)
.map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?; .map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?;
caddy_link::load(&sock, &text).await 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( pub(super) async fn run_under_caddy(
@@ -56,27 +160,10 @@ impl Control {
.filter(|h| plan.target.host(h).is_some()) .filter(|h| plan.target.host(h).is_some())
.cloned() .cloned()
.collect(); .collect();
let addr = self.cfg.caddy_compile().https_listen; let addr = local(self.cfg.caddy_compile().https_listen);
let path_of = |h: &str| -> (String, bool) { let rules = self.caddy_rules(plan);
plan.model // A host whose upstreams already failed before the change is no reason to revert
.hosts() // (edge: `down_hosts`). Judged by the upstreams, as edge does.
.iter()
.find(|x| x.hostname.as_str() == h)
.and_then(|x| x.health_check.as_ref())
.map(|hc| (hc.path.clone(), true))
.unwrap_or_else(|| ("/".to_owned(), false))
};
let good = |p: &Probe, has_check: bool| match p {
Probe::Status(s) => {
if has_check {
(200..300).contains(s)
} else {
*s < 500
}
}
Probe::NoAnswer(_) => false,
};
// A host that already failed through Caddy before the change is no reason to revert.
let existed: BTreeSet<String> = self let existed: BTreeSet<String> = self
.repo .repo
.tree(&j.base) .tree(&j.base)
@@ -90,16 +177,33 @@ impl Control {
.unwrap_or_default(); .unwrap_or_default();
let mut was_down = BTreeSet::new(); let mut was_down = BTreeSet::new();
for h in &existed { for h in &existed {
let (path, check) = path_of(h); if let Some(r) = rules.get(h)
if !good(&caddy_link::probe(addr, h, &path).await, check) { && !Self::probe_host(h, r).await.iter().any(|(_, p)| p.ok)
{
was_down.insert(h.clone()); was_down.insert(h.clone());
} }
} }
if let Err(e) = caddy_link::load(&sock, caddy_text.as_bytes()).await { let window = self.cfg.watch_secs;
return self // The deadline goes out before the trial does (crate::caddy_guard).
.revert(id, &j, fail("apply.failed.reload", e), "failed") let deadline = now() + window + self.cfg.trial_margin_secs + 5;
.await; // 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(); j.stage = "trial_loaded".into();
if let Err(e) = self.journal(&j) { if let Err(e) = self.journal(&j) {
@@ -115,7 +219,6 @@ impl Control {
.filter(|h| !was_down.contains(*h)) .filter(|h| !was_down.contains(*h))
.cloned() .cloned()
.collect(); .collect();
let window = self.cfg.watch_secs;
let mut kept_reason = if watch_hosts.is_empty() { let mut kept_reason = if watch_hosts.is_empty() {
reason( reason(
"apply.kept.removed", "apply.kept.removed",
@@ -130,10 +233,10 @@ impl Control {
]), ]),
) )
}; };
let ends = now() + window;
if judged.is_empty() { if judged.is_empty() {
self.update(id, |r| r.step("watch", "skipped")); self.update(id, |r| r.step("watch", "skipped"));
} else { } else {
let ends = now() + window;
self.update(id, |r| { self.update(id, |r| {
r.state = "watching".into(); r.state = "watching".into();
r.step("watch", "running"); r.step("watch", "running");
@@ -148,86 +251,19 @@ impl Control {
.collect(), .collect(),
}); });
}); });
// hostname -> (passed, failed, failed in a row, last probe) }
let mut stats: BTreeMap<String, (u32, u32, u32, Option<Probe>)> = judged 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() .iter()
.map(|h| (h.clone(), (0, 0, 0, None))) .filter(|h| rules.get(*h).is_some_and(|r| !r.has_check))
.cloned()
.collect(); .collect();
let no_check: Vec<String> = judged.iter().filter(|h| !path_of(h).1).cloned().collect();
loop {
for h in &judged {
let (path, check) = path_of(h);
let p = caddy_link::probe(addr, h, &path).await;
let ok = good(&p, check);
if let Some(s) = stats.get_mut(h) {
if ok {
s.0 += 1;
s.2 = 0;
} else {
s.1 += 1;
s.2 += 1;
}
s.3 = Some(p);
}
}
self.update(id, |r| {
if let Some(w) = &mut r.watch {
for wh in &mut w.hosts {
if let Some(s) = stats.get(&wh.hostname) {
wh.passed = s.0;
wh.failed = s.1;
wh.total = s.0 + s.1;
}
}
}
});
let over = now() >= ends;
let failing = stats
.iter()
.find(|(_, s)| s.2 >= 3 || (over && s.2 > 0))
.map(|(h, s)| (h.clone(), s.clone()));
if let Some((h, s)) = failing {
let upstream = plan
.model
.hosts()
.iter()
.find(|x| x.hostname.as_str() == h)
.and_then(|x| x.upstreams.first())
.map(|u| u.to_string())
.unwrap_or_default();
let mut p = messages::params([
("hostname", h.clone()),
("verb", plan.verb.into()),
("upstream", upstream.clone()),
("count", s.1.to_string()),
("of", (s.0 + s.1).to_string()),
("seconds", window.to_string()),
]);
let (code, detail) = match &s.3 {
Some(Probe::Status(st)) => {
p.insert("status".into(), st.to_string());
(
"apply.reverted.server_error",
format!("through Caddy: HTTP {st}"),
)
}
Some(Probe::NoAnswer(e)) => {
("apply.reverted.no_answer", format!("through Caddy: {e}"))
}
None => ("apply.reverted.no_answer", String::new()),
};
let mut r = reason(code, p);
r.hostname = Some(h.clone());
r.upstream = Some(upstream);
r.field = Some("upstreams[0]".into());
r.detail = Some(detail);
return self.revert(id, &j, r, "reverted").await;
}
if over {
break;
}
tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await;
}
if !no_check.is_empty() && no_check.len() == judged.len() { if !no_check.is_empty() && no_check.len() == judged.len() {
kept_reason = reason( kept_reason = reason(
"apply.kept.no_watch", "apply.kept.no_watch",
@@ -237,6 +273,10 @@ impl Control {
self.update(id, |r| r.step("watch", "done")); self.update(id, |r| r.step("watch", "done"));
} }
crash::point("watched"); 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(); j.stage = "confirmed".into();
if let Err(e) = self.journal(&j) { if let Err(e) = self.journal(&j) {
let mut r = reason("internal", Params::new()); let mut r = reason("internal", Params::new());
@@ -244,7 +284,22 @@ impl Control {
return self.revert(id, &j, r, "failed").await; return self.revert(id, &j, r, "failed").await;
} }
crash::point("confirmed"); 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() { if let Err(e) = self.promote() {
drop(engine);
log::error!(target: "ianitor::apply", "cannot write the config files: {e}"); log::error!(target: "ianitor::apply", "cannot write the config files: {e}");
let mut p = reason("control.files_unwritten", Params::new()); let mut p = reason("control.files_unwritten", Params::new());
p.detail = Some(e.to_string()); p.detail = Some(e.to_string());
@@ -258,6 +313,12 @@ impl Control {
return; return;
} }
crash::point("promoted"); 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(); let push_step = self.push_step();
self.update(id, |r| r.step("push", push_step)); self.update(id, |r| r.step("push", push_step));
self.finish(id, "kept", Some(kept_reason), Vec::new()); self.finish(id, "kept", Some(kept_reason), Vec::new());
@@ -267,4 +328,139 @@ impl Control {
} }
self.push_wake.notify_one(); 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(())
}
} }
+1
View File
@@ -7,6 +7,7 @@
//! edge keeps serving the last good config. //! edge keeps serving the last good config.
pub mod api; pub mod api;
pub mod caddy_guard;
pub mod caddy_link; pub mod caddy_link;
pub mod config; pub mod config;
pub mod crash; pub mod crash;
+23 -1
View File
@@ -30,7 +30,8 @@ fn usage() -> ExitCode {
eprintln!( eprintln!(
"usage: ianitor-control --config <control.toml> | --dev [--edge-bin <path>] | \ "usage: ianitor-control --config <control.toml> | --dev [--edge-bin <path>] | \
token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) | \ token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) | \
token list (...) | token revoke <id> (...) | openapi | check --config <c>" token list (...) | token revoke <id> (...) | openapi | check --config <c> | \
caddy-revert --config <c> | caddy-guard --config <c>"
); );
ExitCode::from(2) ExitCode::from(2)
} }
@@ -395,6 +396,27 @@ fn main() -> ExitCode {
Ok(()) Ok(())
} }
Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")), 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("--dev") => rt.block_on(dev::run(&args[1..])),
Some("--config") => match args.get(1) { Some("--config") => match args.get(1) {
Some(p) => match Config::load(&PathBuf::from(p)) { Some(p) => match Config::load(&PathBuf::from(p)) {
+80 -9
View File
@@ -218,9 +218,11 @@ fn bundle_password() -> Result<String, PkiFail> {
/// Private keys in `dir` that are not control's own: control refuses to run with one in its /// Private keys in `dir` that are not control's own: control refuses to run with one in its
/// state directory (ROADMAP §1.2: the root is never on the server). Found by content (any /// state directory (ROADMAP §1.2: the root is never on the server). Found by content (any
/// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`, `*root*.pem` with /// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`); the only keys
/// a key); the only keys allowed are `pki/intermediate.key`, `pki/pending-*.key` and /// allowed are `pki/intermediate.key`, `pki/pending-*.key` and `pki/devices/*.key`, and those
/// `pki/devices/*.key`, which control writes encrypted itself. /// must hold exactly one key in control's own encrypted armour, nothing else. A symbolic link
/// is never followed and never skipped: it is reported. Git's object store (`*.git/objects`,
/// compressed history) is not read.
pub fn root_key_files(dir: &Path) -> Vec<PathBuf> { pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
let allowed = |p: &Path| -> bool { let allowed = |p: &Path| -> bool {
let Ok(rel) = p.strip_prefix(dir) else { let Ok(rel) = p.strip_prefix(dir) else {
@@ -242,6 +244,12 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
_ => false, _ => false,
} }
}; };
let own_armour = |b: &[u8]| -> bool {
let t = String::from_utf8_lossy(b);
let begins = t.matches("-----BEGIN ").count();
let ours = t.matches(OWN_BEGIN).count();
begins == 1 && ours == 1 && t.matches(KEY_MARK).count() == 2
};
let mut found = Vec::new(); let mut found = Vec::new();
let mut stack = vec![(dir.to_path_buf(), 0)]; let mut stack = vec![(dir.to_path_buf(), 0)];
while let Some((d, depth)) = stack.pop() { while let Some((d, depth)) = stack.pop() {
@@ -250,21 +258,41 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
}; };
for e in rd.flatten() { for e in rd.flatten() {
let p = e.path(); let p = e.path();
let Ok(meta) = e.metadata() else { continue }; // symlink_metadata: a link is looked at, not followed.
let Ok(meta) = std::fs::symlink_metadata(&p) else {
continue;
};
if meta.file_type().is_symlink() {
found.push(p);
continue;
}
if meta.is_dir() { if meta.is_dir() {
if depth < 8 { let git_objects =
e.file_name() == "objects" && d.extension().is_some_and(|x| x == "git");
if depth < 8 && !git_objects {
stack.push((p, depth + 1)); stack.push((p, depth + 1));
} }
continue; continue;
} }
if !meta.is_file() || allowed(&p) { if !meta.is_file() {
continue;
}
let read = || {
(meta.len() <= 1 << 20)
.then(|| std::fs::read(&p).ok())
.flatten()
};
if allowed(&p) {
// Control's own key files: one key, in control's encrypted armour.
if !read().is_some_and(|b| own_armour(&b)) {
found.push(p);
}
continue; continue;
} }
let name = e.file_name().to_string_lossy().to_ascii_lowercase(); let name = e.file_name().to_string_lossy().to_ascii_lowercase();
let by_name = name.contains("root") && name.contains("key"); let by_name = name.contains("root") && name.contains("key");
let by_content = meta.len() <= 1 << 20 let by_content =
&& std::fs::read(&p) read().is_some_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes()));
.is_ok_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes()));
if by_name || by_content { if by_name || by_content {
found.push(p); found.push(p);
} }
@@ -275,6 +303,7 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
// Split so that this file does not match the pre-commit hook itself. // Split so that this file does not match the pre-commit hook itself.
const KEY_MARK: &str = concat!("PRIVATE ", "KEY-----"); const KEY_MARK: &str = concat!("PRIVATE ", "KEY-----");
const OWN_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----");
impl Pki { impl Pki {
/// Open the CA state. The root certificate must be a CA and self-signed; the password /// Open the CA state. The root certificate must be a CA and self-signed; the password
@@ -1182,3 +1211,45 @@ pub fn cli_wait(state_dir: &Path, rid: &str, since: u64) -> Result<String, Strin
std::thread::sleep(std::time::Duration::from_millis(250)); std::thread::sleep(std::time::Duration::from_millis(250));
} }
} }
#[cfg(test)]
mod root_key_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn allowed_paths_hold_only_our_armour_links_are_reported_and_git_objects_are_not_read() {
let dir = std::env::temp_dir().join(format!("ianitor-rk-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("pki/devices")).unwrap();
std::fs::create_dir_all(dir.join("routes.git/objects/ab")).unwrap();
let key = pki::generate_key().unwrap();
let sealed = pki::encrypt_key_with(&key, b"pw", 1000).unwrap();
let plain = key.serialize_pem();
std::fs::write(dir.join("pki/intermediate.key"), &sealed).unwrap();
std::fs::write(dir.join("pki/devices/d1.key"), &sealed).unwrap();
// Git's store is not read (a blob could hold anything, compressed or not).
std::fs::write(dir.join("routes.git/objects/ab/cdef"), &plain).unwrap();
assert!(
root_key_files(&dir).is_empty(),
"{:?}",
root_key_files(&dir)
);
// A plain key, or a second block, in an allowed place is not ours.
std::fs::write(dir.join("pki/pending-x.key"), &plain).unwrap();
std::fs::write(dir.join("pki/devices/d2.key"), format!("{sealed}{plain}")).unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("/nonexistent/domi-root.key", dir.join("pki/devices/d3.key"))
.unwrap();
let found = root_key_files(&dir);
assert!(found.contains(&dir.join("pki/pending-x.key")), "{found:?}");
assert!(found.contains(&dir.join("pki/devices/d2.key")), "{found:?}");
#[cfg(unix)]
assert!(found.contains(&dir.join("pki/devices/d3.key")), "{found:?}");
assert!(
!found.contains(&dir.join("pki/intermediate.key")),
"{found:?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
}
+56 -16
View File
@@ -164,9 +164,16 @@ impl Control {
} }
/// The device files changed (issue or revoke): rewrite them and tell the engine at once. /// 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> { pub async fn devices_changed(&self) -> Result<(), String> {
let Some(p) = &self.pki else { return Ok(()) }; let Some(p) = &self.pki else { return Ok(()) };
let _engine = self.engine_lock.lock().await; let _files = self.devices_lock.lock().await;
let t = now(); let t = now();
let mut result = Ok(()); let mut result = Ok(());
for dir in self.cert_dirs() { for dir in self.cert_dirs() {
@@ -177,23 +184,34 @@ impl Control {
)); ));
} }
} }
// Tell the serving engine every time, changed or not: a repeated Revoke nudges again. // The engine lock is held for long only by a switch; an apply holds it for a moment
if result.is_ok() { // (loading a trial, or from the claim to the promoted reload), so then this waits.
result = if self.engine_running() == "caddy" { let engine =
self.caddy_reload() match tokio::time::timeout(Duration::from_secs(1), self.engine_lock.lock()).await {
.await Ok(g) => Some(g),
.map_err(|e| format!("Caddy did not reload the device list: {e}")) Err(_) if self.engine_state().state == "switching" => None,
} else if self.edge.attached() { Err(_) => Some(self.engine_lock.lock().await),
self.edge
.reload_devices()
.await
.map_err(|e| format!("edge did not re-read the device list: {e}"))
} else {
Ok(())
}; };
// 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() { if let Ok(mut pr) = self.devices_problem.lock() {
*pr = result.as_ref().err().cloned(); *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 { if let Err(e) = &result {
log::error!(target: "ianitor::pki", "{e}; retrying"); log::error!(target: "ianitor::pki", "{e}; retrying");
@@ -201,10 +219,32 @@ impl Control {
result 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) { async fn reload_serving_engine(&self) {
let _engine = self.engine_lock.lock().await; let _engine = self.engine_lock.lock().await;
if self.engine_running() == "caddy" { if self.engine_running() == "caddy" {
if let Err(e) = self.caddy_reload().await { if let Err(e) = self.caddy_reload_checked().await {
log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {e}"); log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {e}");
} }
} else if self.edge.attached() } else if self.edge.attached()
+11
View File
@@ -254,6 +254,17 @@ impl Control {
}); });
} }
} }
// 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> { fn units_and_cfg(&self) -> Result<(Arc<dyn Units>, EngineConfig), String> {
+845 -6
View File
@@ -78,6 +78,12 @@ esac
let deadline = Instant::now() + Duration::from_secs(30); let deadline = Instant::now() + Duration::from_secs(30);
loop { loop {
let r = env.call("GET", "/api/v1/engine", None).await; let r = env.call("GET", "/api/v1/engine", None).await;
// On a loaded machine a switch takes longer: stay under the API's 120 calls a
// minute rather than fail on a 429.
if r.status == 429 {
tokio::time::sleep(Duration::from_secs(1)).await;
continue;
}
assert_eq!(r.status, 200, "{}", r.text); assert_eq!(r.status, 200, "{}", r.text);
if r.json["state"] == "running" && r.json["running"] == running { if r.json["state"] == "running" && r.json["running"] == running {
return r.json; return r.json;
@@ -85,7 +91,7 @@ esac
if Instant::now() > deadline { if Instant::now() > deadline {
panic!("engine is {}\n{}", r.text, env.control_log()); panic!("engine is {}\n{}", r.text, env.control_log());
} }
tokio::time::sleep(Duration::from_millis(100)).await; tokio::time::sleep(Duration::from_millis(300)).await;
} }
} }
@@ -228,11 +234,30 @@ mkdir -p "$dir"
echo "$*" >> "{d}/fake/calls.log" echo "$*" >> "{d}/fake/calls.log"
case "$1:$2" in case "$1:$2" in
start:caddy-fallback.service) start:caddy-fallback.service)
# Like systemd: starting a unit that is active does nothing.
[ -e "$dir/$2" ] && exit 0
XDG_DATA_HOME="{d}/caddy-state" XDG_CONFIG_HOME="{d}/caddy-state" HOME="{d}/caddy-state" \ XDG_DATA_HOME="{d}/caddy-state" XDG_CONFIG_HOME="{d}/caddy-state" HOME="{d}/caddy-state" \
nohup "{c}" run --config "{d}/caddy/caddy.json" >> "{d}/logs/caddy.log" 2>&1 & nohup "{c}" run --config "{d}/caddy/caddy.json" >> "{d}/logs/caddy.log" 2>&1 &
echo $! > "{d}/fake/caddy.pid"; touch "$dir/$2" ;; echo $! > "{d}/fake/caddy.pid"
# The NixOS module starts ianitor-caddy-guard with caddy-fallback (crate::caddy_guard).
if [ ! -e "{d}/fake/no-guard" ]; then
IANITOR_LOG=info nohup "{g}" caddy-guard --config "{d}/control.toml" >> "{d}/logs/caddy-guard.log" 2>&1 &
echo $! > "{d}/fake/guard.pid"
fi
# fake/start-delay: Caddy serves at once, the unit reports active only later (a switch
# that is still in wait_serving while Caddy has read its files).
if [ -f "{d}/fake/start-delay" ]; then
(sleep "$(cat "{d}/fake/start-delay")"; touch "$dir/$2") >/dev/null 2>&1 &
else
touch "$dir/$2"
fi ;;
stop:caddy-fallback.service) stop:caddy-fallback.service)
[ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null; rm -f "$dir/$2" "{d}/fake/caddy.pid" ;; # fake/stop-delay and fake/fail-stop: a slow stop, and one that fails (Caddy keeps running).
[ -f "{d}/fake/stop-delay" ] && sleep "$(cat "{d}/fake/stop-delay")"
grep -qx "$2" "{d}/fake/fail-stop" 2>/dev/null && exit 1
[ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null
[ -f "{d}/fake/guard.pid" ] && kill "$(cat "{d}/fake/guard.pid")" 2>/dev/null
rm -f "$dir/$2" "{d}/fake/caddy.pid" "{d}/fake/guard.pid" ;;
start:*) touch "$dir/$2" ;; start:*) touch "$dir/$2" ;;
stop:*) rm -f "$dir/$2" ;; stop:*) rm -f "$dir/$2" ;;
is-active:*) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;; is-active:*) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;;
@@ -240,7 +265,8 @@ case "$1:$2" in
esac esac
"#, "#,
d = dir.display(), d = dir.display(),
c = caddy.display() c = caddy.display(),
g = env!("CARGO_BIN_EXE_ianitor-control"),
) )
} }
@@ -251,8 +277,10 @@ esac
impl Drop for CaddyEnv { impl Drop for CaddyEnv {
fn drop(&mut self) { fn drop(&mut self) {
if let Ok(p) = std::fs::read_to_string(self.env.dir.join("fake/caddy.pid")) { for f in ["fake/caddy.pid", "fake/guard.pid"] {
let _ = std::process::Command::new("kill").arg(p.trim()).status(); if let Ok(p) = std::fs::read_to_string(self.env.dir.join(f)) {
let _ = std::process::Command::new("kill").arg(p.trim()).status();
}
} }
} }
} }
@@ -392,4 +420,815 @@ esac
&& !edge_json.contains("c.test") && !edge_json.contains("c.test")
); );
} }
// ---------------------------------------------------------------- QC round 2
async fn qc_env_with_caddy_site(site: String) -> Option<CaddyEnv> {
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
let mut env = Env::new(EnvSpec {
site,
..Default::default()
})
.await;
let fake = env.dir.join("fake/systemctl");
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap();
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let d = |p: &str| env.dir.join(p).display().to_string();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
d("engine"),
fake.display(),
d("certs"),
d("caddy-state"),
d("logs/caddy-access.log"),
d("creds"),
d("caddy/admin.sock"),
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
Some(CaddyEnv { env, https })
}
/// QC r2: a forward-auth host with a health check is kept under edge (edge checks the
/// upstream). Under Caddy the watch probes *through* Caddy without a session: Authelia's
/// redirect is not 2xx, so the same change is reverted.
#[tokio::test(flavor = "multi_thread")]
async fn qc_forward_auth_host_with_health_check_is_kept_under_caddy_as_under_edge() {
let auth = ianitor_testkit::authelia::MockAuthelia::start().await;
let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url());
let Some(ce) = qc_env_with_caddy_site(site).await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let host = |h: &str| {
json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi",
"auth": "forward-auth", "health_check": {"path": "/", "interval_secs": 1}}})
};
let rec = env
.apply("POST", "/api/v1/hosts", Some(host("a.test")))
.await;
eprintln!("QC under edge: {}", rec["state"]);
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
let rec = env
.apply("POST", "/api/v1/hosts", Some(host("b.test")))
.await;
eprintln!(
"QC under caddy: {} {}",
rec["state"], rec["reason"]["detail"]
);
assert_eq!(rec["state"], "kept", "{rec}");
}
/// QC r2: control nudges Caddy (device list, renewed certificates) by POST /load of the
/// unchanged caddy.json. Caddy skips a load of an identical config, so the files it read at
/// start are not read again.
#[tokio::test(flavor = "multi_thread")]
async fn qc_reloading_the_same_caddy_json_rereads_the_certificate_files() {
let Some(ce) = env_with_caddy().await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let rec = env
.apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})))
.await;
assert_eq!(rec["state"], "kept");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202);
wait_engine(env, "caddy").await;
assert_eq!(visit(env, ce.https, "a.test").await, 200);
// Replace a.test's certificate with one from a root the client does not trust.
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let (root, rk) = ianitor_core::pki::create_root(now).unwrap();
let k = ianitor_core::pki::generate_key().unwrap();
let csr =
ianitor_core::pki::intermediate_csr(&k, ianitor_core::pki::INTERMEDIATE_CN).unwrap();
let int = ianitor_core::pki::Intermediate::new(
&ianitor_core::pki::sign_intermediate(&root, &rk, &csr, now).unwrap(),
k,
)
.unwrap();
let leaf = ianitor_core::pki::issue_server(&int, "a.test", now).unwrap();
std::fs::write(env.dir.join("certs/a.test.key"), &leaf.key_pem).unwrap();
std::fs::write(env.dir.join("certs/a.test.crt"), &leaf.chain_pem).unwrap();
// What control does in devices_changed / reload_serving_engine under Caddy.
let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
let r = ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &text).await;
assert!(r.is_ok(), "{r:?}");
let after = visit(env, ce.https, "a.test").await;
eprintln!(
"QC after same-config load: visit = {after} (200 = old certificate still served)"
);
assert_ne!(
after, 200,
"Caddy still serves the certificate it read at start"
);
}
/// QC r2: a control crash with a trial loaded into Caddy. Edge reverts an unconfirmed trial
/// by itself; Caddy has no deadline, so the unverified config keeps serving while control
/// is down.
#[tokio::test(flavor = "multi_thread")]
async fn qc_control_crash_mid_trial_under_caddy_leaves_the_last_good_config() {
let Some(mut ce) = env_with_caddy().await else {
return;
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let host = |h: &str| json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi", "auth": "none"}});
assert_eq!(
ce.env
.apply("POST", "/api/v1/hosts", Some(host("a.test")))
.await["state"],
"kept"
);
let r = ce
.env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202);
wait_engine(&ce.env, "caddy").await;
ce.env.kill_control();
ce.env.start_control(Some("trial_loaded"));
let r = ce
.env
.call("POST", "/api/v1/hosts", Some(host("b.test")))
.await;
assert_eq!(r.status, 202, "{}", r.text);
let st = ce.env.wait_control_exit(Duration::from_secs(30));
eprintln!("QC control exit: {st:?}");
assert!(st.is_some());
// Longer than edge's trial deadline would allow.
tokio::time::sleep(Duration::from_secs(15)).await;
let during = visit(&ce.env, ce.https, "b.test").await;
eprintln!("QC b.test through Caddy 15 s after the crash, control down: {during}");
ce.env.start_control(None);
tokio::time::sleep(Duration::from_secs(3)).await;
let after = visit(&ce.env, ce.https, "b.test").await;
eprintln!("QC b.test after control restarted (recovery): {after}");
assert_ne!(after, 200, "recovery must revert the trial");
assert_ne!(
during, 200,
"Caddy served the unconfirmed trial while control was down"
);
}
// ---------------------------------------------------------------- fix round 2
/// Like `env_with_caddy`, with a chosen watch, and with or without the Caddy trial guard
/// (the fake systemctl starts it next to Caddy unless `fake/no-guard` exists).
async fn caddy_env(watch_secs: u64, guard: bool) -> Option<CaddyEnv> {
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
let mut env = Env::new(EnvSpec {
watch_secs,
..Default::default()
})
.await;
let fake = env.dir.join("fake/systemctl");
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap();
if !guard {
std::fs::write(env.dir.join("fake/no-guard"), "").unwrap();
}
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let d = |p: &str| env.dir.join(p).display().to_string();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
d("engine"),
fake.display(),
d("certs"),
d("caddy-state"),
d("logs/caddy-access.log"),
d("creds"),
d("caddy/admin.sock"),
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
Some(CaddyEnv { env, https })
}
async fn to_caddy_with(env: &Env, echo: &ianitor_testkit::upstream::Echo) {
let rec = env
.apply(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})),
)
.await;
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
}
async fn wait_state(env: &Env, id: &str, state: &str) {
let deadline = Instant::now() + Duration::from_secs(20);
loop {
let r = env
.call("GET", &format!("/api/v1/applies/{id}"), None)
.await;
if r.json["state"] == state {
return;
}
assert!(Instant::now() < deadline, "never {state}: {}", r.text);
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
fn b_host(echo: &ianitor_testkit::upstream::Echo) -> Value {
json!({"host": {"hostname": "b.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})
}
/// QC round 2, M2: something reloads Caddy during a trial's watch (a device change, a
/// restart of caddy-fallback). The trial is gone from Caddy; the watch must notice and
/// treat it as interrupted, not report it kept while Caddy serves the old config.
#[tokio::test(flavor = "multi_thread")]
async fn a_reload_of_caddy_during_the_watch_is_noticed() {
let Some(ce) = caddy_env(8, true).await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
to_caddy_with(env, &echo).await;
let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
wait_state(env, &id, "watching").await;
assert_eq!(
visit(env, ce.https, "b.test").await,
200,
"the trial serves"
);
// What a device change or a Caddy restart does: Caddy gets the last good config.
let good = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &good)
.await
.unwrap();
let rec = env.wait_apply(&id).await;
assert_ne!(rec["state"], "kept", "{rec}");
assert_eq!(rec["reason"]["code"], "apply.reverted.edge_lost", "{rec}");
let now_good = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap();
assert!(!now_good.contains("b.test"), "{now_good}");
assert_ne!(visit(env, ce.https, "b.test").await, 200);
}
/// QC round 2, minor 3: the `watching` crash point under Caddy.
#[tokio::test(flavor = "multi_thread")]
async fn a_crash_while_watching_under_caddy_is_reverted() {
let Some(mut ce) = caddy_env(4, true).await else {
return;
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
to_caddy_with(&ce.env, &echo).await;
ce.env.kill_control();
ce.env.start_control(Some("watching"));
let r = ce
.env
.call("POST", "/api/v1/hosts", Some(b_host(&echo)))
.await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some());
ce.env.start_control(None);
let rec = ce.env.wait_apply(&id).await;
assert_eq!(rec["state"], "reverted", "{rec}");
assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
}
/// QC round 2, B2 (a): what systemd runs after control stops (ExecStopPost): with an
/// unconfirmed trial in the journal, Caddy goes back to the last good caddy.json at once,
/// without waiting for the guard's deadline.
#[tokio::test(flavor = "multi_thread")]
async fn caddy_revert_after_a_crash_loads_the_last_good_config() {
let Some(mut ce) = caddy_env(3, false).await else {
return;
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
to_caddy_with(&ce.env, &echo).await;
ce.env.kill_control();
ce.env.start_control(Some("trial_loaded"));
let r = ce
.env
.call("POST", "/api/v1/hosts", Some(b_host(&echo)))
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some());
assert_eq!(
visit(&ce.env, ce.https, "b.test").await,
200,
"the trial was loaded"
);
let config = ce.env.config_path();
let revert = || {
std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
.args(["caddy-revert", "--config"])
.arg(&config)
.output()
.unwrap()
};
let out = revert();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
// After recovery there is no trial: it changes nothing and succeeds.
ce.env.start_control(None);
tokio::time::sleep(Duration::from_secs(2)).await;
let out = revert();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
}
/// QC r3: a device revoked while Caddy serves. Control rewrites the allow list and loads
/// caddy.json (must-revalidate); the revoked device must no longer get in, the newly
/// allowed one must.
#[tokio::test(flavor = "multi_thread")]
async fn qc_device_revoked_under_caddy_is_refused() {
use ianitor_core::pki;
use ianitor_testkit::client::{self, ClientCert, Req};
let Some(ce) = env_with_caddy().await else {
return;
};
let env = &ce.env;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let (root, rk) = pki::create_root(now).unwrap();
let k = pki::generate_key().unwrap();
let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
let int =
pki::Intermediate::new(&pki::sign_intermediate(&root, &rk, &csr, now).unwrap(), k)
.unwrap();
let phone = pki::issue_device(&int, "phone", now).unwrap();
let laptop = pki::issue_device(&int, "laptop", now).unwrap();
std::fs::write(env.dir.join("certs/domi-devices-ca.pem"), int.cert_pem()).unwrap();
std::fs::write(env.dir.join("certs/domi-devices.pem"), &phone.cert_pem).unwrap();
let cc = |d: &pki::Issued| ClientCert {
chain_pem: d.chain_pem.clone(),
key_pem: d.key_pem.clone(),
tls12_only: false,
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let rec = env
.apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})))
.await;
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202);
wait_engine(env, "caddy").await;
let visit_as = |d: &pki::Issued| {
let c = cc(d);
let roots = env.ca.roots();
async move {
match client::https_with_cert(
ce.https,
"d.test",
roots,
&c,
&Req::get("d.test", "/"),
)
.await
{
Ok(r) => r.status,
Err(_) => 0,
}
}
};
let before = visit_as(&phone).await;
eprintln!("QC phone under Caddy before revocation: {before}");
assert_eq!(before, 200);
// Revoke the phone, allow the laptop; tell Caddy the way control does.
std::fs::write(env.dir.join("certs/domi-devices.pem"), &laptop.cert_pem).unwrap();
let sock = env.dir.join("caddy/admin.sock");
let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
ianitor_control::caddy_link::load(&sock, &text)
.await
.unwrap();
assert!(
ianitor_control::caddy_link::runs(&sock, &text)
.await
.unwrap()
);
let phone_after = visit_as(&phone).await;
let laptop_after = visit_as(&laptop).await;
eprintln!("QC after revocation under Caddy: phone {phone_after}, laptop {laptop_after}");
assert_ne!(phone_after, 200, "revoked phone still gets in under Caddy");
assert_eq!(
laptop_after, 200,
"newly allowed laptop is not let in under Caddy"
);
}
// ---------------------------------------------------------------- fix round 3
/// A control with the Domi CA, an intermediate signed by a test root, one device issued
/// and approved, and `d.test` asking for device certificates. With `caddy`, Caddy serves.
struct PkiEnv {
ce: CaddyEnv,
roots: std::sync::Arc<rustls::RootCertStore>,
device_id: String,
device: ianitor_testkit::client::ClientCert,
}
async fn pki_env(watch_secs: u64, caddy: bool) -> Option<PkiEnv> {
use ianitor_core::pki;
let ce = caddy_env(watch_secs, true).await?;
let mut ce = ce;
let env = &mut ce.env;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let (root_pem, root_key) = pki::create_root(now).unwrap();
std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap();
std::fs::write(
env.dir.join("creds/pki-password"),
"round-three-password-123",
)
.unwrap();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n",
env.dir.join("offline-root.crt").display()
);
std::fs::write(env.config_path(), text).unwrap();
env.kill_control();
env.start_control(None);
let cli = |env: &Env, args: &[&str]| {
env.command()
.args(args)
.arg("--config")
.arg(env.config_path())
.output()
.unwrap()
};
// The intermediate, signed offline.
let r = env
.call(
"POST",
"/api/v1/certs/intermediate/renewal",
Some(json!({})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
let signed = pki::sign_intermediate(&root_pem, &root_key, &csr, now).unwrap();
std::fs::write(env.dir.join("int.crt"), signed).unwrap();
let int_path = env.dir.join("int.crt").display().to_string();
let out = cli(env, &["pki", "install", &int_path]);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
// One device.
let r = env
.call(
"POST",
"/api/v1/certs/devices",
Some(json!({"name": "phone", "kind": "phone"})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let code = r.json["match_code"].as_str().unwrap().to_owned();
let out = cli(env, &["pki", "approve", &code]);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let devices: Value = serde_json::from_str(
&std::fs::read_to_string(env.dir.join("state/pki/devices.json")).unwrap(),
)
.unwrap();
let d = &devices[0];
let device_id = d["id"].as_str().unwrap().to_owned();
let sealed =
std::fs::read_to_string(env.dir.join(&format!("state/pki/devices/{device_id}.key")))
.unwrap();
let key = pki::decrypt_key(&sealed, b"round-three-password-123").unwrap();
let int_pem = std::fs::read_to_string(env.dir.join("state/pki/intermediate.crt")).unwrap();
let device = ianitor_testkit::client::ClientCert {
chain_pem: format!("{}{int_pem}", d["cert_pem"].as_str().unwrap()),
key_pem: key.serialize_pem(),
tls12_only: false,
};
let mut store = rustls::RootCertStore::empty();
store
.add(rustls_pki_types::CertificateDer::from(
pki::chain_der(&root_pem).unwrap().remove(0),
))
.unwrap();
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let rec = env
.apply(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})),
)
.await;
assert_eq!(rec["state"], "kept", "{rec}");
// The echo upstream must outlive this function: keep it running in the background.
std::mem::forget(echo);
if caddy {
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
}
Some(PkiEnv {
ce,
roots: std::sync::Arc::new(store),
device_id,
device,
})
}
impl PkiEnv {
async fn visit_as_device(&self, at: std::net::SocketAddr) -> u16 {
match ianitor_testkit::client::https_with_cert(
at,
"d.test",
self.roots.clone(),
&self.device,
&ianitor_testkit::client::Req::get("d.test", "/"),
)
.await
{
Ok(r) => r.status,
Err(_) => 0,
}
}
fn serving(&self, caddy: bool) -> std::net::SocketAddr {
if caddy {
self.ce.https
} else {
self.ce.env.edge.as_ref().unwrap().https
}
}
}
/// Fix round 3 (QC r3 Major): a revocation never waits for a running apply. The DELETE
/// answers at once, the allow list is on disk at once, and the device is refused within
/// edge's backstop window although an apply is still watching.
async fn revoke_during_a_watch(caddy: bool) {
let Some(p) = pki_env(6, caddy).await else {
return;
};
let env = &p.ce.env;
let at = p.serving(caddy);
assert_eq!(p.visit_as_device(at).await, 200, "the device gets in");
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
wait_state(env, &id, "watching").await;
let t = Instant::now();
let d = env
.call(
"DELETE",
&format!("/api/v1/certs/devices/{}", p.device_id),
None,
)
.await;
let took = t.elapsed();
assert_eq!(d.status, 204, "{}", d.text);
assert!(
took < Duration::from_millis(1500),
"the DELETE waited {took:?}"
);
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
let listed = p
.device
.chain_pem
.split("-----END CERTIFICATE-----")
.next()
.unwrap();
assert!(
!allow.contains(listed.trim()),
"the revoked device is still on the list"
);
if caddy {
// Caddy keeps the trial until the apply ends; then the device is out at once.
let rec = env.wait_apply(&id).await;
assert_eq!(rec["state"], "kept", "{rec}");
assert_ne!(
p.visit_as_device(at).await,
200,
"revoked device still gets in under Caddy"
);
} else {
let deadline = Instant::now() + Duration::from_secs(6);
while p.visit_as_device(at).await == 200 {
assert!(
Instant::now() < deadline,
"revoked device still gets in under Pingora"
);
tokio::time::sleep(Duration::from_millis(250)).await;
}
let rec = env.wait_apply(&id).await;
assert_eq!(rec["state"], "kept", "{rec}");
}
let c = env.call("GET", "/api/v1/certs", None).await;
assert!(c.json["devices_problem"].is_null(), "{}", c.text);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_watch_is_in_force_at_once_under_pingora() {
revoke_during_a_watch(false).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_watch_is_in_force_when_the_apply_ends_under_caddy() {
revoke_during_a_watch(true).await;
}
/// Fix round 3, minor 3: with Pingora serving, a deadline file left behind is cleared and
/// caddy-revert succeeds (the unit must not show failed).
#[tokio::test(flavor = "multi_thread")]
async fn caddy_revert_with_pingora_serving_clears_a_stale_deadline() {
let mut env = env().await;
env.kill_control();
std::fs::write(
env.dir.join("state/caddy-trial.json"),
r#"{"apply_id":"ch_x","deadline":1}"#,
)
.unwrap();
let out = env
.command()
.args(["caddy-revert", "--config"])
.arg(env.config_path())
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert!(!env.dir.join("state/caddy-trial.json").exists());
}
// ---------------------------------------------------------------- fix round 4
async fn engine_view(env: &Env) -> Value {
env.call("GET", "/api/v1/engine", None).await.json
}
async fn wait_switching(env: &Env) {
let deadline = Instant::now() + Duration::from_secs(10);
while engine_view(env).await["state"] != "switching" {
assert!(Instant::now() < deadline, "the switch never started");
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
async fn wait_switch_over(env: &Env) -> Value {
let deadline = Instant::now() + Duration::from_secs(40);
loop {
let e = engine_view(env).await;
if e["state"] == "running" {
return e;
}
assert!(Instant::now() < deadline, "the switch never ended: {e}");
tokio::time::sleep(Duration::from_millis(300)).await;
}
}
async fn revoke(env: &Env, id: &str) {
let t = Instant::now();
let d = env
.call("DELETE", &format!("/api/v1/certs/devices/{id}"), None)
.await;
assert_eq!(d.status, 204, "{}", d.text);
assert!(
t.elapsed() < Duration::from_secs(3),
"the DELETE waited {:?}",
t.elapsed()
);
}
async fn refused_soon(p: &PkiEnv, at: std::net::SocketAddr, what: &str) {
let deadline = Instant::now() + Duration::from_secs(4);
while p.visit_as_device(at).await == 200 {
assert!(Instant::now() < deadline, "{what}");
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
/// QC round 4, case A: a device is revoked while a switch to Caddy is still waiting for
/// the unit, after Caddy has already read the allow list. The switch ends by telling
/// Caddy again, so the device is refused once Caddy serves.
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_switch_to_caddy_is_in_force_when_it_ends() {
let Some(p) = pki_env(2, false).await else {
return;
};
let env = &p.ce.env;
std::fs::write(env.dir.join("fake/start-delay"), "5").unwrap();
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_switching(env).await;
// Caddy is up and has read its files; the unit is not reported active yet.
let deadline = Instant::now() + Duration::from_secs(5);
while p.visit_as_device(p.ce.https).await != 200 {
assert!(Instant::now() < deadline, "Caddy did not come up");
tokio::time::sleep(Duration::from_millis(200)).await;
}
assert_eq!(engine_view(env).await["state"], "switching");
revoke(env, &p.device_id).await;
let e = wait_switch_over(env).await;
assert_eq!(e["running"], "caddy", "{e}");
refused_soon(
&p,
p.ce.https,
"the revoked device still gets in under Caddy after the switch",
)
.await;
}
/// QC round 4, case B: a switch away from Caddy fails before Caddy is stopped, and a
/// device was revoked meanwhile. The Caddy that kept serving must refuse it.
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_failed_switch_away_from_caddy_is_in_force() {
let Some(p) = pki_env(2, true).await else {
return;
};
let env = &p.ce.env;
assert_eq!(
p.visit_as_device(p.ce.https).await,
200,
"the device gets in"
);
std::fs::write(env.dir.join("fake/stop-delay"), "4").unwrap();
std::fs::write(env.dir.join("fake/fail-stop"), "caddy-fallback.service\n").unwrap();
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "pingora"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_switching(env).await;
revoke(env, &p.device_id).await;
let e = wait_switch_over(env).await;
assert_eq!(e["running"], "caddy", "{e}");
assert!(!e["last_error"].is_null(), "{e}");
refused_soon(
&p,
p.ce.https,
"the revoked device still gets in under the Caddy that kept serving",
)
.await;
// Nothing is left pending.
let deadline = Instant::now() + Duration::from_secs(6);
loop {
let c = env.call("GET", "/api/v1/certs", None).await;
if c.json["devices_problem"].is_null() {
break;
}
assert!(Instant::now() < deadline, "{}", c.text);
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
} }
+26 -7
View File
@@ -78,12 +78,23 @@ pub fn hostname(host_header: &str) -> String {
/// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost /// 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 /// `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. /// `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> { pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option<IpAddr> {
let peer = session let peer = canonical(
.client_addr() session
.and_then(|a| a.as_inet()) .client_addr()
.map(|a| a.ip())?; .and_then(|a| a.as_inet())
if !trusted.contains(&peer) { .map(|a| a.ip())?,
);
let trusted_ip = |ip: &IpAddr| trusted.iter().any(|t| canonical(*t) == *ip);
if !trusted_ip(&peer) {
return Some(peer); return Some(peer);
} }
let mut last = peer; let mut last = peer;
@@ -96,8 +107,8 @@ pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option<IpAddr> {
{ {
let Ok(s) = v.to_str() else { return Some(last) }; let Ok(s) = v.to_str() else { return Some(last) };
for part in s.rsplit(',') { for part in s.rsplit(',') {
match part.trim().parse::<IpAddr>() { match part.trim().parse::<IpAddr>().map(canonical) {
Ok(ip) if trusted.contains(&ip) => last = ip, Ok(ip) if trusted_ip(&ip) => last = ip,
Ok(ip) => return Some(ip), Ok(ip) => return Some(ip),
Err(_) => return Some(last), Err(_) => return Some(last),
} }
@@ -506,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");
+72
View File
@@ -264,4 +264,76 @@ mod unix {
tokio::time::sleep(std::time::Duration::from_millis(250)).await; tokio::time::sleep(std::time::Duration::from_millis(250)).await;
} }
} }
/// QC r2: end to end through Pingora (2 worker threads, pre-TLS hook): a handshake that
/// fails after the resolver (bad ALPN) must not break the next TLS 1.2 device handshake.
#[tokio::test(flavor = "multi_thread")]
async fn qc_tls12_device_after_bad_alpn_handshakes_end_to_end() {
use std::sync::Arc;
let echo = Echo::start("app").await;
let p = pki();
let (phone, phone_pem) = device(&p, "phone");
let edge = setup(&echo, &p, &[&phone_pem]).await;
let roots = edge.roots();
let req = Req::get("locked.test", "/");
let mut failures = Vec::new();
let mut poisoned = 0;
for i in 0..40 {
let addr = edge.https;
let r2 = roots.clone();
let failed = tokio::task::spawn_blocking(move || {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let mut cfg = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(r2)
.with_no_client_auth();
cfg.alpn_protocols = vec![b"foo".to_vec()];
let mut conn = rustls::ClientConnection::new(
Arc::new(cfg),
rustls_pki_types::ServerName::try_from("open.test".to_owned()).unwrap(),
)
.unwrap();
let mut sock = std::net::TcpStream::connect(addr).unwrap();
sock.set_read_timeout(Some(std::time::Duration::from_secs(5)))
.unwrap();
let mut r = Ok((0, 0));
for _ in 0..5 {
r = conn.complete_io(&mut sock);
if r.is_err() || !conn.is_handshaking() {
break;
}
}
r.is_err()
})
.await
.unwrap();
if failed {
poisoned += 1;
}
match client::https_with_cert(
edge.https,
"locked.test",
roots.clone(),
&tls12(&phone),
&req,
)
.await
{
Ok(r) if r.status == 200 => {}
other => failures.push(format!("{i}: {other:?}")),
}
}
eprintln!(
"QC poison handshakes that failed: {poisoned}/40; device failures: {}",
failures.len()
);
assert_eq!(poisoned, 40, "the poison handshake must fail");
assert!(
failures.is_empty(),
"{} of 40 TLS 1.2 device handshakes failed: {:?}",
failures.len(),
failures.first()
);
}
} }
+30 -3
View File
@@ -151,7 +151,7 @@ in
type = types.listOf types.str; type = types.listOf types.str;
default = [ ]; default = [ ];
example = [ "127.0.0.1" ]; example = [ "127.0.0.1" ];
description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default."; description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default: on a loopback listener any local process could then claim any address (docs/deploy/beside-caddy.md).";
}; };
}; };
@@ -252,7 +252,9 @@ in
}) userCreds; }) userCreds;
users.groups.ianitor = { }; users.groups.ianitor = { };
users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; home = "${stateRoot}/control"; }; # Only control (and Caddy itself) may reach Caddy's admin socket; edge is not in it.
users.groups.ianitor-caddy-admin = { };
users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; extraGroups = [ "ianitor-caddy-admin" ]; home = "${stateRoot}/control"; };
users.users.ianitor-edge = { isSystemUser = true; group = "ianitor"; }; users.users.ianitor-edge = { isSystemUser = true; group = "ianitor"; };
users.users.caddy-fallback = { isSystemUser = true; group = "ianitor"; }; users.users.caddy-fallback = { isSystemUser = true; group = "ianitor"; };
@@ -300,6 +302,10 @@ in
User = "ianitor-control"; User = "ianitor-control";
Group = "ianitor"; Group = "ianitor";
ExecStart = "${pkg}/bin/ianitor-control --config ${controlToml}"; ExecStart = "${pkg}/bin/ianitor-control --config ${controlToml}";
# After every stop, a crash included: a trial still loaded into Caddy goes back to the
# last good caddy.json at once (ianitor_control::caddy_guard). It runs after a crash
# too, so no separate OnFailure= unit is needed.
ExecStopPost = "${pkg}/bin/ianitor-control caddy-revert --config ${controlToml}";
LoadCredential = loadCreds controlCreds ++ [ "ui-proof:${runProof}/ui-proof" ]; LoadCredential = loadCreds controlCreds ++ [ "ui-proof:${runProof}/ui-proof" ];
ReadWritePaths = [ stateRoot ]; ReadWritePaths = [ stateRoot ];
Restart = "on-failure"; Restart = "on-failure";
@@ -352,7 +358,10 @@ in
}; };
serviceConfig = hardening // { serviceConfig = hardening // {
User = "caddy-fallback"; User = "caddy-fallback";
Group = "ianitor"; # The admin socket (and its runtime directory) belong to this group; "ianitor" for the
# certificates and logs.
Group = "ianitor-caddy-admin";
SupplementaryGroups = [ "ianitor" ];
ExecStart = "${cfg.caddyPackage}/bin/caddy run --config ${stateRoot}/caddy/caddy.json"; ExecStart = "${cfg.caddyPackage}/bin/caddy run --config ${stateRoot}/caddy/caddy.json";
LoadCredential = loadCreds cfg.credentials ++ [ "ui-proof:${runProof}/ui-proof" ]; LoadCredential = loadCreds cfg.credentials ++ [ "ui-proof:${runProof}/ui-proof" ];
RuntimeDirectory = "caddy-fallback"; RuntimeDirectory = "caddy-fallback";
@@ -367,6 +376,24 @@ in
}; };
}; };
# The deadline of a trial under Caddy, outside control (a hung control included): once a
# second it reverts a trial past its deadline to the last good caddy.json. Runs with Caddy.
systemd.services.ianitor-caddy-guard = {
description = "Ianitor: deadline for changes tried on Caddy";
partOf = [ "caddy-fallback.service" ];
after = [ "caddy-fallback.service" ];
wantedBy = [ "caddy-fallback.service" ];
environment.IANITOR_LOG = "info";
serviceConfig = hardening // {
User = "ianitor-control";
Group = "ianitor";
ExecStart = "${pkg}/bin/ianitor-control caddy-guard --config ${controlToml}";
ReadWritePaths = [ "${stateRoot}/control" ];
Restart = "always";
RestartSec = 1;
};
};
# At boot: start the engine the UI chose last (ROADMAP §3). # At boot: start the engine the UI chose last (ROADMAP §3).
systemd.services.ianitor-engine-select = { systemd.services.ianitor-engine-select = {
description = "Ianitor: start the chosen engine"; description = "Ianitor: start the chosen engine";
+21
View File
@@ -157,6 +157,27 @@ in
assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept" assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept"
server.succeed("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve two.test:443:127.0.0.1 https://two.test/ | grep -q 200") server.succeed("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve two.test:443:127.0.0.1 https://two.test/ | grep -q 200")
# The trial's deadline under Caddy does not depend on control (fix round 2, B2): the guard
# runs with Caddy, only control may use Caddy's admin socket, and a control killed during
# the watch leaves Caddy on the last good config (ExecStopPost=caddy-revert).
server.succeed("systemctl is-active ianitor-caddy-guard.service")
server.fail("runuser -u ianitor-edge -- test -w /run/caddy-fallback/admin.sock")
server.succeed("runuser -u ianitor-control -- test -w /run/caddy-fallback/admin.sock")
r = api(server, t, "POST", "/hosts", {"host": {
"hostname": "three.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}})
three = r["apply"]["id"]
for _ in range(60):
if api(server, t, "GET", f"/applies/{three}").get("state") == "watching":
break
time.sleep(0.5)
assert visit(server, "three.test") == "200", "the trial serves"
server.succeed("systemctl kill --signal=KILL ianitor-control.service")
server.wait_until_fails("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve three.test:443:127.0.0.1 https://three.test/ | grep -q 200", timeout=10)
server.wait_for_unit("ianitor-control.service")
server.wait_until_succeeds(f"curl -sf -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/overview")
assert wait_apply(server, t, three)["state"] == "reverted"
assert visit(server, "two.test") == "200"
api(server, t, "POST", "/engine", {"target": "pingora"}) api(server, t, "POST", "/engine", {"target": "pingora"})
server.wait_until_succeeds( server.wait_until_succeeds(
f"curl -s -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/engine | jq -e '.running == \"pingora\" and .state == \"running\"'" f"curl -s -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/engine | jq -e '.running == \"pingora\" and .state == \"running\"'"
+60 -3
View File
@@ -144,13 +144,70 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit
|:--|:--|:--| |:--|:--|:--|
| 1 Core and engine | Done | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. The Let's Encrypt staging check moved to phase 3 (Mark, 2026-11-07). | | 1 Core and engine | Done | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. The Let's Encrypt staging check moved to phase 3 (Mark, 2026-11-07). |
| 2 Control plane | Done | Merged to main 2026-11-07 (PR 3): routes repo, journaled apply with trial/watch/revert, undo, restore, share links, API tokens, REST API + OpenAPI, `--dev`. Four QC rounds; every finding fixed or listed in Handover. Real Gitea, systemd credentials and Authelia not exercised. | | 2 Control plane | Done | Merged to main 2026-11-07 (PR 3): routes repo, journaled apply with trial/watch/revert, undo, restore, share links, API tokens, REST API + OpenAPI, `--dev`. Four QC rounds; every finding fixed or listed in Handover. Real Gitea, systemd credentials and Authelia not exercised. |
| 3 Web UI, PKI, NixOS | Not started | UI design drafted: claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u ("murex" palette on the Domi system, approved). Carries the Let's Encrypt staging check, on the first low-risk host beside Caddy. | | 3 Web UI, PKI, NixOS | Built and merged; Done criteria pending Mark | Merged to main 2026-11-08 (PR 5): web UI (murex palette), Domi CA and device mTLS, UI sign-in behind Authelia, runtime engine switch with changes under Caddy, NixOS flake, module and VM tests. Click smoke test green. Not yet done: VM tests run on a KVM host, Mark's nixos-rebuild on the staging mirror, deploy/test-access.sh there, the LE staging check. |
| 4 Hardening and release | Not started | Known gaps carried here: see Handover. | | 4 Hardening and release | Started: the release kit | A `v*` tag's Gitea release carries the notes and screenshots of the web UI under a signed SHA256SUMS (docs/release.md, 2026-11-09). The rest of phase 4 is not started; known gaps carried here: see Handover. |
## 10. Handover ## 10. Handover
(Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.) (Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.)
**2026-11-07: Phase 2, control plane.** **2026-11-09: Release notes and screenshots for Fabrica.**
- **Changed:** `.fabrica/artifex/release.yaml` (on a `v*` tag, Windows runner: version check, web check and tests,
`fabrica notes`, the screenshots, Custos approval, publish to the tag's Gitea release with `sums: domi-release`);
`apps/web/scripts/shots.mjs` (the built UI against the demo control plane `apps/web/tests/demo.ts`, invented data,
headless Edge over DevTools: `aula-hosts`, `-host`, `-engine`, `-history`, `-certificates`.png and `aula.json`);
`apps/web/tests/demo.test.ts` (each shot drawn from the demo alone, and nothing in it outside `.test` and the
documentation address ranges); `mockApi.ts` exports its builders and routes for the demo; `scripts/check-version.mjs`;
`.fabrica/notes/0.1.0.md` (the first release's highlights). docs/release.md says how. app.yaml is unchanged (no
`aula: true`, so no landing page; no desktop part: Ianitor has no installer).
- **Verified:** `fabrica artifex check` 0 problems; `fabrica notes` (whole history; PR 3 to 5 come out as bare
"PR #n", hence the highlights); the shots script 9 runs (one browser start timed out, before the retry was added),
each PNG looked at; vitest 21 (smoke 15, demo 6), svelte-check clean. Rust on Windows only (WSL2 Debian would not
start: HCS_E_CONNECTION_TIMEOUT): core 103, control 21, edge 31 and diff 2 (the Linux-only targets are skip stubs
there), testkit 1; no Rust file changed.
- **Deployed:** nothing; no tag, no run.
- **Next step:** Mark tags `v0.1.0`, starts `release` at it, then Deploy as before.
**2026-11-08: Ianitor declared to Fabrica.**
- **Changed:** `.fabrica/app.yaml` (a server part, flake input `ianitor`) and `.fabrica/artifex/deploy.yaml` (approve,
then `deploy: ianitor`), so Fabrica's Apps screen shows an Ianitor card with Deploy. `fabrica artifex check`: 0 problems.
- **Deployed:** nothing; no deploy was started.
- **For Mark, before the card's Deploy can work:** the server flake needs the `ianitor` input (the patch in
docs/deploy/configuration-server.patch; with `rev=` pinned, `nix flake update ianitor` cannot move it, so drop the
`rev=` once the first lock is reviewed), and `ianitor` in `services.fabrica-artifex.deploy.inputs` (Fabrica
docs/04_deploy.md) with its health URL.
**2026-11-08: Phase 3, web UI, PKI, NixOS.**
- **Changed:**
- apps/web and packages/ui: Svelte 5 UI from the designer's hand-off (docs/ui-handoff.md, decisions in docs/ui-decisions.md), murex palette, self-hosted fonts, no outside requests (CSP). vitest click smoke test for every §4 flow, with the accepted 4th clicks.
- Domi CA in core and control (docs/pki.md): ECDSA P-256; root made offline by `ianitor-control ca init`; intermediate key encrypted at rest; server certificates 90 days, device certificates 1 year and never past the intermediate; control refuses to start with a private key it does not expect in its state dir. Device mTLS in edge and Caddy (`device_certs` hosts, allow list, 421 on SNI/Host mismatch).
- §8.6 answered: Custos has no CSR signing; ticket written (docs/custos-ticket.md, not filed); interim manual openssl signing and `pki approve` on the server.
- UI sign-in (G14): a per-boot `ui-proof` secret that only the admin host behind Authelia sends; control trusts Remote-User only with it.
- Engine switch at runtime through polkit (start/stop of exactly two units). Changes keep working under Caddy: trials loaded through its admin socket, watched by probing upstreams with edge's rules, reverted by control, a deadline guard unit, or ExecStopPost after a crash. Share links are off under Caddy.
- Test hooks moved behind the default `test-hooks` feature; the Nix release build is checked to contain none.
- flake.nix (`.#ianitor`, `.#ianitor-web`, `nixosModules.ianitor`), deploy/nixos with four VM tests, deploy/test-access.sh; docs/deploy/configuration-server.patch and beside-caddy.md (flowers.stage and esp32.stage on the staging mirror, the LE staging check).
- Tests: core 103, edge 57, control 75, diff 4, testkit 1 (240); vitest 15; svelte-check clean; hook self-test 55. Four QC rounds and two design reviews; every finding fixed or listed below.
- **Deployed:** nothing. The server is unchanged. The prepared change is docs/deploy/configuration-server.patch; Mark runs it (beside-caddy.md).
- **Not verified:**
- The four NixOS VM tests: written and their drivers build, but never run (no /dev/kvm in WSL2).
- Real systemd, polkit, LoadCredential, Authelia, Gitea push and Caddy under systemd; the module against hyperv-infra's nixpkgs 24.11.
- The caddy guard retrying a failed load (code reading only).
- PKCS#12 (AES-256) install on older iOS and macOS; a screen reader; a real clipboard copy in Chrome, Firefox and iOS Safari.
- https upstreams: Caddy-path probes use the system CA bundle; not compared with Pingora's roots.
- **Known gaps for later phases:**
- Edge beside Caddy listens on loopback TCP, so any local process could forge X-Forwarded-For; `trustedProxies` stays off there. A Unix-socket listener is the fix. (phase 4)
- Control on a Unix socket only edge can reach (G14 option b). (phase 4)
- Share links under Caddy need a validator Caddy calls via forward_auth. (before v1.1)
- "All hosts answered" after a switch is not claimed: control does not check every host.
- A revocation during an engine switch reaches the engine at the end of the switch (or by the 2 s retry), not at once.
- The open `apply_sequence` flake from phase 2 has not recurred, but its cause is still unknown.
- **Decided by Mark (2026-11-07/08):** the share link on a host with links off keeps 4 clicks; UI sign-in by a secret header from edge; the switch to Caddy is allowed with differences shown; share links off under Caddy for v1; device approval falls back to `pki approve`; manual intermediate signing is a §4 exception; device certificates last 1 year; confirmations on Stop all and Revoke; hidden tabs stop polling after 15 minutes; token lifetime choice; "Open to anyone" chip; production runs Authelia outside Configuration_Server; trial hosts flowers.stage and esp32.stage; changes keep working under Caddy.
- **Still open:**
- Mark: add hyperv-infra/ianitor/domi-root.crt (made offline), apply the patch with the merged commit hash, deploy to the staging mirror, run deploy/test-access.sh, then the LE staging check (it needs a new public name on production).
- Run the VM tests on a machine with KVM (`nix flake check`).
- (e) Delete F:\pwt and the merged remote branches.
- **Next step:** Mark's staging deploy and the VM tests close Phase 3; then Phase 4.
**2026-11-07: Phase 2, control plane** (kept for its open items).
- **Changed:** - **Changed:**
- Phase 2 on branch control/phase-2: crates/control (routes repo through the `git` binary, journaled apply with edge trial reloads, 60 s watch and revert, undo/redo, restore, push with retry, share links, API tokens, REST API with OpenAPI, `--dev`), edge in-process reload over an admin Unix socket, share-link checks and visitor pages in edge, share tokens and the exact `hosts/<hostname>.toml` loader in core. - Phase 2 on branch control/phase-2: crates/control (routes repo through the `git` binary, journaled apply with edge trial reloads, 60 s watch and revert, undo/redo, restore, push with retry, share links, API tokens, REST API with OpenAPI, `--dev`), edge in-process reload over an admin Unix socket, share-link checks and visitor pages in edge, share tokens and the exact `hosts/<hostname>.toml` loader in core.
- docs/api.md (curl examples, run end to end against `--dev`) and docs/ui-api.md (the designer's contract for phase 3, with the deviations listed at its end). - docs/api.md (curl examples, run end to end against `--dev`) and docs/ui-api.md (the designer's contract for phase 3, with the deviations listed at its end).
+26 -7
View File
@@ -309,22 +309,41 @@ allows exactly `ianitor-edge.service` and `caddy-fallback.service`, verbs start
waits until it serves; if it does not within 20 s, it starts the old one again and reports waits until it serves; if it does not within 20 s, it starts the old one again and reports
`engine.switch_failed`. The switch waits for a running apply (same lock, first come first `engine.switch_failed`. The switch waits for a running apply (same lock, first come first
served: a queued switch runs right after the apply in progress, before any apply queued after served: a queued switch runs right after the apply in progress, before any apply queued after
it). Back on Pingora, edge is reloaded so it serves what was applied while Caddy served. it). Back on Pingora, edge is reloaded so it serves what was applied while Caddy served. Every
switch, kept or gone back, ends by telling the engine that serves to read the device files again;
a device change during a switch only writes them and shows `devices_problem` ("an engine switch is
under way") until then, and the 2 s retry tells the serving engine too.
Refusals: `engine.unmanaged` (no `[engine]` in control.toml), `engine.same`, `engine.switching`, Refusals: `engine.unmanaged` (no `[engine]` in control.toml), `engine.same`, `engine.switching`,
`engine.not_ready` (Caddy's settings cannot be built from the current routes). `engine.not_ready` (Caddy's settings cannot be built from the current routes).
While Caddy serves (decisions Q3, Q4; Mark 2026-11-08): While Caddy serves (decisions Q3, Q4; Mark 2026-11-08):
- **changes keep working**: applies, Undo and Restore go through the same pipeline. Both outputs - **changes keep working**: applies, Undo and Restore go through the same pipeline. Both outputs
are compiled; the trial is loaded into Caddy through its admin API (`POST /load` on the Unix are compiled; the trial is loaded into Caddy through its admin API (`POST /load` on the Unix
socket `[compile_caddy] caddy_admin_socket`, `/run/caddy-fallback/admin.sock` under NixOS), the socket `[compile_caddy] caddy_admin_socket`, `/run/caddy-fallback/admin.sock` under NixOS,
touched hosts are probed *through Caddy* for the watch window, and a revert loads the previous group `ianitor-caddy-admin`: control and Caddy, not edge), and a revert loads the previous
`caddy.json` again. Without `caddy_admin_socket` an apply under Caddy fails with `caddy.json` again. Every load sends `Cache-Control: must-revalidate`, so Caddy reads its
`apply.failed.reload` and nothing changes; certificate and device files again even when the config is unchanged. The watch judges health
as edge does: control probes the upstreams itself with edge's rules (health check: `GET <path>`,
Host = the upstream, 2xx; none: `GET /`, Host = the hostname, below 500), and a probe *through*
Caddy only asks that Caddy answers at all (any status, its sign-in redirect included). Each
round also checks that Caddy still runs the trial (`GET /config/`); if anything else reloaded it,
the change is undone as `apply.reverted.edge_lost`. Without `caddy_admin_socket` an apply under
Caddy fails with `apply.failed.reload` and nothing changes;
- **an unconfirmed trial never outlives control**, as with edge: control arms a deadline
(`caddy-trial.json` in its state directory: watch + margin) before loading the trial and claims
it right after the journal says `confirmed` (a crash in between leaves both, and recovery
promotes). A guard revert counts only once Caddy is verified on caddy.json; a failed load is
retried with a growing pause. With Pingora serving, caddy-revert only clears a stale deadline. `ianitor-caddy-guard` (a unit that runs with caddy-fallback,
`ianitor-control caddy-guard`) reverts a trial past its deadline, which covers a hung control;
ianitor-control's `ExecStopPost=ianitor-control caddy-revert` reverts at once after any stop or
crash. Whoever renames the deadline file first wins, so a trial is either kept or reverted;
- device issues and revocations never wait for an apply: the files are written and edge is told
at once. Under Caddy, Caddy is reloaded at once and checked to serve the certificate on disk
for a Domi host (else `devices_problem`, retried), except while a trial is out: then the end
of that apply (promote or revert, both load caddy.json) brings the new files in;
- **share links are off**: minting is `409 share.engine_caddy`, and a visitor with a link gets the - **share links are off**: minting is `409 share.engine_caddy`, and a visitor with a link gets the
normal sign-in (fails closed). Caddy cannot check a share token and control never serves normal sign-in (fails closed). Caddy cannot check a share token and control never serves
visitors; a validator Caddy calls through `forward_auth` is planned before v1.1; visitors; a validator Caddy calls through `forward_auth` is planned before v1.1;
- device issues and revocations reload Caddy through the same socket (Caddy reads the allow list
when a config is loaded).
A revocation is in force only once the serving engine has the new list. If the list cannot be A revocation is in force only once the serving engine has the new list. If the list cannot be
written or the engine does not take it, `DELETE /certs/devices/{id}` answers `503 written or the engine does not take it, `DELETE /certs/devices/{id}` answers `503
+8
View File
@@ -32,6 +32,14 @@ visitor ── Caddy :443 (as today) ── https://127.0.0.1:18443 Ianitor edg
- Caddy keeps the public side for the two names and hands them to Ianitor over TLS; Ianitor - Caddy keeps the public side for the two names and hands them to Ianitor over TLS; Ianitor
serves them with Domi certificates, which Caddy checks against the Domi root (a public file). serves them with Domi certificates, which Caddy checks against the Domi root (a public file).
- Every other host is untouched. Rollback: revert the patch and switch (below). - Every other host is untouched. Rollback: revert the patch and switch (below).
- Visitor addresses: Ianitor sees every visit coming from 127.0.0.1 (Caddy), so the share-link
throttle counts all visitors together and the visit log shows 127.0.0.0. The option
`services.ianitor.edge.trustedProxies = [ "127.0.0.1" ]` would make edge believe Caddy's
`X-Forwarded-For` instead, but edge listens on a TCP port on loopback that **any local user or
process can reach**, and any of them could then claim any address. It stays **off** for the
trial (the two hosts have no share links and no visit log); turn it on only on a machine where
every local account is trusted. (A Unix-socket listener for edge, which Caddy alone could reach,
is the proper fix; not built yet.)
## The patch ## The patch
+1 -3
View File
@@ -67,7 +67,7 @@ new file mode 100644
index 0000000..cd23016 index 0000000..cd23016
--- /dev/null --- /dev/null
+++ b/hyperv-infra/modules/ianitor.nix +++ b/hyperv-infra/modules/ianitor.nix
@@ -0,0 +1,51 @@ @@ -0,0 +1,49 @@
+{ config, lib, inputs, ... }: +{ config, lib, inputs, ... }:
+ +
+# Ianitor beside Caddy (Ianitor ROADMAP §1.12, Phase 3): two low-risk hosts, flowers and esp32, +# Ianitor beside Caddy (Ianitor ROADMAP §1.12, Phase 3): two low-risk hosts, flowers and esp32,
@@ -100,8 +100,6 @@ index 0000000..cd23016
+ httpListen = "127.0.0.1:18080"; + httpListen = "127.0.0.1:18080";
+ httpsListen = "127.0.0.1:18443"; + httpsListen = "127.0.0.1:18443";
+ openFirewall = false; + openFirewall = false;
+ # Caddy in front, on loopback: its X-Forwarded-For names the visitor (throttle, logs).
+ trustedProxies = [ "127.0.0.1" ];
+ }; + };
+ control.listen = "127.0.0.1:7878"; + control.listen = "127.0.0.1:7878";
+ shareLinkKeyFile = config.sops.secrets."ianitor/share-link-key".path; + shareLinkKeyFile = config.sops.secrets."ianitor/share-link-key".path;
+109
View File
@@ -0,0 +1,109 @@
# Releases: notes and screenshots on the Gitea release
Ianitor is server-only: what runs is built by Nix on the server and switched in by the `deploy` pipeline
(`.fabrica/artifex/deploy.yaml`, `fabrica-deploy@ianitor`). A release adds what a deploy does not leave behind: a
Gitea release for the `vX.Y.Z` tag with the release notes and screenshots of the web UI, under a `SHA256SUMS`
signed by `domi-release`. It ships no binary; the deploy stays the deploy.
The release kit is Fabrica's (Fabrica `docs/12_release_kit.md`, core `docs/FORMATS.md`, "Fabrica: release notes"
and "Fabrica: the Aula page"). Ianitor uses it as it is, with one difference: Fabrica's `fabrica aula shots`
drives a built Windows WebView2 exe, which Ianitor does not have, so a repo script takes the same files from the
web UI in a headless browser.
## The pipeline: `.fabrica/artifex/release.yaml`
`on: tag "v*"` and `manual: true`, on the Windows runner (the Fabrica app on Mark's PC: `fabrica`, node and pnpm
are on every step's PATH).
| Step | Does | Produces |
| :-- | :-- | :-- |
| `version` | `node scripts/check-version.mjs <version>`: the tag's version must be the workspace `Cargo.toml`'s and both `package.json`s' | |
| `install` | `pnpm install --frozen-lockfile` | |
| `check`, `test` | `svelte-check` and the vitest click smoke test of the web UI the shots show | |
| `notes` | `fabrica notes` (the range since the previous `v*` tag; the first release covers the whole history) | `target/notes/release-notes.md`, `release-notes.json` |
| `shots` | `node apps/web/scripts/shots.mjs` (below) | `target/aula/aula-<name>.png`, `aula.json` |
| `approve` | the run's Custos approval, before anything is published | |
| `publish` | the Gitea release of the tag: the notes, the shots and `aula.json`; `sums: domi-release` adds `SHA256SUMS` and `SHA256SUMS.minisig`; `release-notes.md` becomes the release's text | |
The Rust tests are not in it: the edge, diff and ACME tests are Linux-only (ROADMAP §8.3) and the release builds
nothing. They run in WSL2 and in the Nix build.
**No landing page.** `fabrica aula page` and `aula-page.json` are left out while `.fabrica/app.yaml` has no
`aula: true`. Turning Aula on later is two lines: `aula: true` in `app.yaml` and a `page` step (`fabrica aula
page`, after `notes` and `shots`) whose `aula-page.json` is published; a brief (`.fabrica/aula/brief.md`) is
optional, its caption names are the shot names below.
**app.yaml stays as it is.** Its parts are `desktop` (a release pipeline started by the tag the card's Deploy
bumps and pushes, with installers) and `server` (a deploy pipeline). Ianitor has no installer and no version bump to
make, so it keeps its one `server` part; the release is started by its tag.
## Release notes
`fabrica notes` writes them from the first-parent commit subjects, the Pensum tickets done (Ianitor has none) and
`.fabrica/notes/<version>.md`, the highlights a person writes. The merges of PR 3 to 5 predate the
`[repo] Merge: <branch> (<title>, PR #n)` form and come out as bare "PR #n" lines; history is not rewritten, so
`.fabrica/notes/0.1.0.md` says in a few sentences what 0.1.0 is, and goes first.
## Screenshots: `apps/web/scripts/shots.mjs`
`node apps/web/scripts/shots.mjs [--out <dir>]` (default `target/aula` at the repo root):
1. empties the output folder of `aula-*.png` and `aula.json`;
2. builds the web UI (Vite, production) into a fresh temporary folder;
3. serves it on `127.0.0.1` (a free port), with `/api/v1` answered by the demo control plane
(`apps/web/tests/demo.ts`), and every other path falling back to `index.html` as in production;
4. starts headless Microsoft Edge (or Chrome; `IANITOR_SHOTS_BROWSER` names another) with a fresh profile in the
temporary folder, its DevTools port on loopback only, and a cleared environment (the system variables and the
temporary folder, nothing of the runner's: no `GITEA_TOKEN`, no hub token); a browser whose DevTools do not
answer within 20 s is stopped and started again, at most three times;
5. for each shot: sets the viewport (1440 × 900, scale 1), loads its page, clicks its selectors, waits for its
selector, the fonts, two frames and 400 ms, and saves `aula-<name>.png`; a wait that runs out (20 s) saves
`aula-<name>-failed.png` and fails;
6. writes `aula.json` in the format of core `docs/FORMATS.md` ("Fabrica: the Aula page"): `{"v":1,"shots":[…]}`,
each shot's `name`, `title`, `file`, `width` and `height` read from the PNG, and `sha256`;
7. on every way out kills the browser's process tree and, on Windows, any process left with a profile in the
temporary folder (Edge can start its browser again as a new process, outside the tree), stops the server, and
removes the temporary folder.
| Name | Page | Shows |
| :-- | :-- | :-- |
| `hosts` | `/` | the host list: health, chips, where each sends traffic, the last change |
| `host` | `/hosts/wiki.home.test/edit` | editing a host: upstreams, certificate, sign-in, health check |
| `engine` | `/`, then the engine chip | Pingora serving and the Caddy fallback ready, with its differences |
| `history` | `/history/<change>` | the history with a version picked and what restoring it changes |
| `certificates` | `/certificates` | the Domi intermediate and the device certificates |
**The demo control plane** (`apps/web/tests/demo.ts`) answers like control (docs/api.md), built on the click smoke
test's stand-in (`apps/web/tests/mockApi.ts`: the same host and apply shapes and every call the demo does not
replace). Its data is invented: hostnames under `.test`, upstream addresses in the documentation ranges
(192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24), people *ada* and *felix*, made-up commits, match codes and
fingerprints. A vitest test (`apps/web/tests/demo.test.ts`) asks every page's calls and fails on any other
hostname or address, so a real name cannot slip in through a later fixture.
## Risks
| Risk | Answer |
| :-- | :-- |
| A screenshot shows Mark's network | The UI talks only to the demo control plane; the demo data test refuses names outside `.test` and addresses outside the documentation ranges; the PNGs are looked at in the review. |
| The browser reaches out | It loads only `127.0.0.1`; the UI's own CSP allows no outside requests; background networking, sync and component updates are off; its profile is thrown away. |
| A secret reaches the browser | Its environment is cleared to the system variables. The demo serves no token, key or certificate. |
| A forged screenshot or note | They are release assets under `SHA256SUMS`, signed by `domi-release` through Custos; the Gitea text is not signed, the asset is. |
| The browser outlives the run | Its process tree is killed on every way out (`taskkill /T` on Windows). |
| A shot of a half-drawn screen | Each `wait` selector exists only once the screen's data is there; fonts and two frames are awaited. |
## Gaps
- Windows and Edge or Chrome only as tested; the script is plain Node and DevTools, so Linux with Chromium should
work, untested.
- One size (desktop); no phone layout shot.
- The release does not run the Rust tests (see above).
- No `[repo] Release:` bump: the version in `Cargo.toml` and the `package.json`s is changed by hand before tagging.
## Handover: releasing 0.1.0
1. On main: `git tag v0.1.0 && git push origin v0.1.0`.
2. Start the `release` pipeline at `v0.1.0` from Fabrica (no Gitea webhook to the hub yet: the hub's
`POST /api/runs`, ref `v0.1.0`). Approve on the Custos card, then sign `SHA256SUMS` on Custos (`domi-release`).
3. The Gitea release `v0.1.0` has the notes as its text and `release-notes.md`, `release-notes.json`, five
`aula-*.png`, `aula.json`, `SHA256SUMS` and `SHA256SUMS.minisig`.
4. Deploy as before: Fabrica's *Apps* → Ianitor → *Deploy*, then deploy/test-access.sh from a LAN machine.
+2 -1
View File
@@ -545,4 +545,5 @@ Recorded by the Phase 3 implementation (branch `phase-3`); docs/api.md has the c
10 minutes. 10 minutes.
- New host field `device_certs` (bool): only Domi device certificates on the allow list get in. - New host field `device_certs` (bool): only Domi device certificates on the allow list get in.
- `overview.paused_reason` gives the underlying code (`apply.needs_attention`, - `overview.paused_reason` gives the underlying code (`apply.needs_attention`,
`control.files_unwritten`, `repo.*`) next to `paused {code: "control.paused"}`. `control.files_unwritten`, `repo.*`) next to `paused {code: "control.paused"}`, and
`overview.paused_detail` the technical detail behind it (for "Show details").
+26 -3
View File
@@ -16,6 +16,7 @@
onclose, onclose,
escape = true, escape = true,
closable = true, closable = true,
toggle,
children, children,
footer, footer,
}: { }: {
@@ -26,6 +27,8 @@
onclose: () => void; onclose: () => void;
escape?: boolean; escape?: boolean;
closable?: boolean; closable?: boolean;
/** A popover's opener (a CSS selector): a click there is the opener's, which toggles it. */
toggle?: string;
children?: Snippet; children?: Snippet;
footer?: Snippet; footer?: Snippet;
} = $props(); } = $props();
@@ -39,12 +42,32 @@
if (modal && typeof el.showModal === "function") el.showModal(); if (modal && typeof el.showModal === "function") el.showModal();
else if (typeof el.show === "function") el.show(); else if (typeof el.show === "function") el.show();
else el.setAttribute("open", ""); else el.setAttribute("open", "");
const first = el.querySelector<HTMLElement>( const first =
"[data-autofocus], input:not([type=hidden]):not([readonly]):not([type=radio]), textarea, select", el.querySelector<HTMLElement>("[data-autofocus]") ??
); el.querySelector<HTMLElement>("input:not([type=hidden]):not([readonly]):not([type=radio]), textarea:not([readonly]), select");
(first ?? el.querySelector<HTMLElement>(".ia-dialog-title"))?.focus(); (first ?? el.querySelector<HTMLElement>(".ia-dialog-title"))?.focus();
} }
// A dialog opened with show() (the popover) gets no cancel event: Esc and a click outside
// close it here, like the modal ones.
const key = (e: KeyboardEvent) => {
if (!modal && e.key === "Escape" && escape) {
e.preventDefault();
onclose();
}
};
const down = (e: PointerEvent) => {
if (!modal && escape && el && e.target instanceof Node && !el.contains(e.target)) {
if (toggle && e.target instanceof Element && e.target.closest(toggle)) return;
onclose();
}
};
document.addEventListener("keydown", key);
// On the next turn, so the click that opened the popover does not close it.
const t = setTimeout(() => document.addEventListener("pointerdown", down), 0);
return () => { return () => {
clearTimeout(t);
document.removeEventListener("keydown", key);
document.removeEventListener("pointerdown", down);
if (opener instanceof HTMLElement && document.contains(opener)) opener.focus(); if (opener instanceof HTMLElement && document.contains(opener)) opener.focus();
}; };
}); });
+15 -2
View File
@@ -12,6 +12,15 @@
@import "@fontsource/manrope/latin-400.css"; @import "@fontsource/manrope/latin-400.css";
@import "@fontsource/manrope/latin-600.css"; @import "@fontsource/manrope/latin-600.css";
@import "@fontsource/manrope/latin-700.css"; @import "@fontsource/manrope/latin-700.css";
/* latin-ext: Czech names and places (č, ř, ů) in host names, device names and messages. */
@import "@fontsource/cinzel/latin-ext-500.css";
@import "@fontsource/cormorant-garamond/latin-ext-500.css";
@import "@fontsource/cormorant-garamond/latin-ext-600.css";
@import "@fontsource/manrope/latin-ext-400.css";
@import "@fontsource/manrope/latin-ext-600.css";
@import "@fontsource/manrope/latin-ext-700.css";
html, body { margin: 0; }
.ia .sr-only { .ia .sr-only {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden;
@@ -98,7 +107,10 @@
.ia .ia-engine small { color: var(--muted); font-weight: 400; font-size: 0.86rem; } .ia .ia-engine small { color: var(--muted); font-weight: 400; font-size: 0.86rem; }
/* ── Lists and rows (§2.5) ──────────────────────────────────────────────── */ /* ── Lists and rows (§2.5) ──────────────────────────────────────────────── */
.ia .ia-list { border: 1px solid var(--hairline); border-radius: var(--radius-lg); overflow: hidden; } .ia .ia-list { border: 1px solid var(--hairline); border-radius: var(--radius-lg); }
/* No overflow clipping on the list: a row's menu must reach past it. The end rows carry the corners. */
.ia .ia-list > :first-child { border-top-left-radius: calc(var(--radius-lg) - 1px); border-top-right-radius: calc(var(--radius-lg) - 1px); }
.ia .ia-list > :last-child { border-bottom-left-radius: calc(var(--radius-lg) - 1px); border-bottom-right-radius: calc(var(--radius-lg) - 1px); }
.ia .ia-row { display: grid; grid-template-columns: 128px minmax(0, 1.4fr) minmax(0, 1.6fr) 44px; gap: 16px; padding: 12px 10px 12px 18px; align-items: start; border-top: 1px solid var(--hairline); } .ia .ia-row { display: grid; grid-template-columns: 128px minmax(0, 1.4fr) minmax(0, 1.6fr) 44px; gap: 16px; padding: 12px 10px 12px 18px; align-items: start; border-top: 1px solid var(--hairline); }
.ia .ia-row:first-child { border-top: 0; } .ia .ia-row:first-child { border-top: 0; }
.ia .ia-row.head { background: var(--colonnade); padding-top: 10px; padding-bottom: 10px; align-items: center; } .ia .ia-row.head { background: var(--colonnade); padding-top: 10px; padding-bottom: 10px; align-items: center; }
@@ -121,6 +133,7 @@
background: none; color: var(--text-2); font-weight: 600; font-size: 0.92rem; text-align: left; cursor: pointer; background: none; color: var(--text-2); font-weight: 600; font-size: 0.92rem; text-align: left; cursor: pointer;
} }
.ia .ia-menu [role="menuitem"]:hover, .ia .ia-menu [role="menuitem"]:focus { background: var(--surface-2); color: var(--text); outline: none; } .ia .ia-menu [role="menuitem"]:hover, .ia .ia-menu [role="menuitem"]:focus { background: var(--surface-2); color: var(--text); outline: none; }
.ia .ia-menu [role="menuitem"]:focus-visible { outline: var(--focus-ring); outline-offset: -2px; }
.ia .ia-menu [role="menuitem"].danger { color: var(--danger); } .ia .ia-menu [role="menuitem"].danger { color: var(--danger); }
.ia .ia-menu [role="menuitem"][aria-disabled="true"] { color: var(--disabled); cursor: not-allowed; flex-wrap: wrap; padding-top: 6px; padding-bottom: 6px; } .ia .ia-menu [role="menuitem"][aria-disabled="true"] { color: var(--disabled); cursor: not-allowed; flex-wrap: wrap; padding-top: 6px; padding-bottom: 6px; }
.ia .ia-menu .reason { flex-basis: 100%; padding-left: 28px; font-weight: 400; font-size: var(--fs-sub); color: var(--muted); } .ia .ia-menu .reason { flex-basis: 100%; padding-left: 28px; font-weight: 400; font-size: var(--fs-sub); color: var(--muted); }
@@ -185,7 +198,7 @@
@media (max-width: 719.98px) { .ia .ia-toasts { right: 16px; left: 16px; bottom: calc(80px + env(safe-area-inset-bottom)); } } @media (max-width: 719.98px) { .ia .ia-toasts { right: 16px; left: 16px; bottom: calc(80px + env(safe-area-inset-bottom)); } }
.ia .ia-progress { height: 6px; border-radius: 3px; background: var(--surface-2); overflow: hidden; } .ia .ia-progress { height: 6px; border-radius: 3px; background: var(--surface-2); overflow: hidden; }
.ia .ia-progress > span { display: block; height: 100%; background: var(--accent); transition: width var(--dur-tick) linear; } .ia .ia-progress > span { display: block; height: 100%; background: var(--accent); transition: width var(--dur-tick) linear; }
.ia .ia-secret { display: block; width: 100%; background: var(--surface); border: 1px solid var(--control-edge); border-radius: var(--radius-sm); box-shadow: var(--carved); padding: 12px 14px; font-weight: 600; letter-spacing: 0.02em; word-break: break-all; color: var(--text); font: inherit; } .ia .ia-secret { display: block; width: 100%; background: var(--surface); border: 1px solid var(--control-edge); border-radius: var(--radius-sm); box-shadow: var(--carved); padding: 12px 14px; font: inherit; font-weight: 600; letter-spacing: 0.02em; word-break: break-all; overflow-wrap: anywhere; white-space: pre-wrap; color: var(--text); resize: none; }
.ia .ia-details pre { background: var(--surface); border-radius: var(--radius-sm); color: var(--muted); font-size: var(--fs-sub); white-space: pre-wrap; padding: 10px 12px; margin: 6px 0; } .ia .ia-details pre { background: var(--surface); border-radius: var(--radius-sm); color: var(--muted); font-size: var(--fs-sub); white-space: pre-wrap; padding: 10px 12px; margin: 6px 0; }
.ia .ia-frame { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 32px; text-align: center; } .ia .ia-frame { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 32px; text-align: center; }
.ia .ia-card { background: var(--surface); border: 1px solid var(--hairline); border-radius: var(--radius); padding: 12px 14px; } .ia .ia-card { background: var(--surface); border: 1px solid var(--hairline); border-radius: var(--radius); padding: 12px 14px; }
+1
View File
@@ -17,6 +17,7 @@ export const ICONS = {
building: "M4 21V5l8-3 8 3v16M9 21v-5h6v5M8 8h2M14 8h2M8 12h2M14 12h2", building: "M4 21V5l8-3 8 3v16M9 21v-5h6v5M8 8h2M14 8h2M8 12h2M14 12h2",
swap: "M7 7h13l-4-4M17 17H4l4 4", swap: "M7 7h13l-4-4M17 17H4l4 4",
copy: "M9 9h11v11H9zM5 15H4V4h11v1", copy: "M9 9h11v11H9zM5 15H4V4h11v1",
download: "M12 4v11M7 10l5 5 5-5M5 20h14",
chevron: "M6 9l6 6 6-6", chevron: "M6 9l6 6 6-6",
dots: "M5 12h.01M12 12h.01M19 12h.01", dots: "M5 12h.01M12 12h.01M19 12h.01",
close: "M6 6l12 12M18 6 6 18", close: "M6 6l12 12M18 6 6 18",
+43
View File
@@ -0,0 +1,43 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The release's version check (docs/release.md): every place that carries Ianitor's version agrees,
// and, given a version (the tag's, e.g. 0.1.0 for v0.1.0), is that version.
// node scripts/check-version.mjs [X.Y.Z]
// Exit codes: 0 they agree, 1 they do not, 2 usage.
import { readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const repo = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const want = process.argv[2];
if (process.argv.length > 3 || (want !== undefined && !/^\d+\.\d+\.\d+$/.test(want))) {
console.error("usage: node scripts/check-version.mjs [X.Y.Z]");
process.exit(2);
}
function cargo() {
const text = readFileSync(join(repo, "Cargo.toml"), "utf8");
const section = /^\[workspace\.package\]\s*$([\s\S]*?)(?=^\[|(?![\s\S]))/m.exec(text);
const v = section && /^version\s*=\s*"([^"]*)"\s*$/m.exec(section[1]);
return v ? v[1] : null;
}
const pkg = (p) => JSON.parse(readFileSync(join(repo, p), "utf8")).version ?? null;
const found = [
["Cargo.toml [workspace.package]", cargo()],
["apps/web/package.json", pkg("apps/web/package.json")],
["packages/ui/package.json", pkg("packages/ui/package.json")],
];
const expected = want ?? found[0][1];
const wrong = found.filter(([, v]) => v !== expected);
for (const [where, v] of found) console.log(`${where}: ${v ?? "(none)"}`);
if (wrong.length) {
console.error(`version: expected ${expected} everywhere; ${wrong.map(([w, v]) => `${w} has ${v ?? "none"}`).join(", ")}`);
process.exit(1);
}
console.log(`version: ${expected} everywhere`);