18 Commits

Author SHA1 Message Date
mnovak 51a95e4f75 [control] Caddy mode, tests: a previews-only token opens a branch preview that answers through Caddy (admin on loopback TCP, Domi certificate, no edge) and is gone after close; runs on Windows 2026-11-17 14:03:52 +01:00
mnovak 5e273241e4 [tests] Diff: the differential suite runs on Windows too (Windows Caddy, drive paths), with two branch previews in the fixtures; edge leaves a websocket 101 as the upstream sent it, as Caddy does 2026-11-17 13:59:18 +01:00
mnovak acf69a8ed2 [control] Windows Caddy mode: Caddy's admin API on loopback TCP where there is no Unix socket, applies go through Caddy without an edge, control and the Caddy guard as Windows services, a log file 2026-11-17 13:59:12 +01:00
mnovak fc9e16f1b2 [control] Previews: POST/GET/DELETE /api/v1/previews, tokens scoped to previews only, the upstream allow list, expiry; Windows drive paths in compile options (tests first) 2026-11-17 13:46:33 +01:00
mnovak 83270e0746 [core] Previews: branch and project names to one safe host label, and the [preview] table of a host file (tests first) 2026-11-17 13:29:35 +01:00
mnovak 00b506670f [repo] Merge: feature/domi-pki (The Domi CA from the shared crate domi-pki v1.0.0, PR #9) 2026-11-17 12:36:54 +01:00
mnovak d4da521a91 [core] PKI: the Domi CA from the shared crate domi-pki v1.0.0 (same API, messages and key format) 2026-11-17 12:30:10 +01:00
mnovak 1cc3599f10 [repo] Merge: disk rule in CLAUDE.md (PR #8) 2026-11-10 23:44:51 +01:00
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
54 changed files with 3995 additions and 690 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).
+9 -1
View File
@@ -4,7 +4,8 @@ Ianitor is a reverse proxy built on Cloudflare's Pingora, with a small Domi CA,
NixOS-native, with Caddy as a tested fallback. MPL-2.0. Plan, decisions and status: docs/ROADMAP.md — read it first. NixOS-native, with Caddy as a tested fallback. MPL-2.0. Plan, decisions and status: docs/ROADMAP.md — read it first.
## Layout ## Layout
crates/core config model, schema, compilers (Pingora runtime + Caddy JSON), CA. Pure: no I/O, no network. crates/core config model, schema, compilers (Pingora runtime + Caddy JSON), CA (Ianitor's view of the shared
crate domi-pki, pinned by tag). Pure: no I/O, no network.
crates/edge Pingora data plane. Reads compiled config, serves traffic. Never decides policy. crates/edge Pingora data plane. Reads compiled config, serves traffic. Never decides policy.
crates/control API, git routes repo, apply/rollback, share links, PKI flows. Loopback only. Never serves public traffic. crates/control API, git routes repo, apply/rollback, share links, PKI flows. Loopback only. Never serves public traffic.
apps/web Svelte 5 (runes, TypeScript strict). A client of the API; no logic. apps/web Svelte 5 (runes, TypeScript strict). A client of the API; no logic.
@@ -13,11 +14,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 +35,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.
Generated
+36 -3
View File
@@ -859,6 +859,21 @@ dependencies = [
"syn 3.0.9", "syn 3.0.9",
] ]
[[package]]
name = "domi-pki"
version = "1.0.0"
source = "git+https://gitea.marek-novak.cz/mnovak/domi-pki?tag=v1.0.0#b1ec5b3196fc22355270f381e5a7748c50e3380d"
dependencies = [
"base64 0.22.1",
"rcgen",
"ring",
"rustls-pki-types",
"rustls-webpki",
"thiserror 2.0.21",
"time",
"x509-parser 0.18.1",
]
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.3" version = "1.0.3"
@@ -1311,7 +1326,9 @@ dependencies = [
"tokio", "tokio",
"tokio-rustls", "tokio-rustls",
"toml", "toml",
"url",
"utoipa", "utoipa",
"windows-service",
] ]
[[package]] [[package]]
@@ -1319,18 +1336,16 @@ name = "ianitor-core"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"rcgen", "domi-pki",
"ring", "ring",
"rustls-pki-types", "rustls-pki-types",
"rustls-webpki", "rustls-webpki",
"serde", "serde",
"serde_json", "serde_json",
"thiserror 2.0.21", "thiserror 2.0.21",
"time",
"toml", "toml",
"unicode-normalization", "unicode-normalization",
"url", "url",
"x509-parser 0.18.1",
] ]
[[package]] [[package]]
@@ -1345,6 +1360,7 @@ dependencies = [
"rustls", "rustls",
"serde_json", "serde_json",
"tokio", "tokio",
"toml",
] ]
[[package]] [[package]]
@@ -3539,6 +3555,12 @@ dependencies = [
"rustls-pki-types", "rustls-pki-types",
] ]
[[package]]
name = "widestring"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
[[package]] [[package]]
name = "winapi-util" name = "winapi-util"
version = "0.1.11" version = "0.1.11"
@@ -3554,6 +3576,17 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-service"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "857224b3b211c6f3616921f081ee54721ee3ad2ace2fac6a6337e032f7b4dcf2"
dependencies = [
"bitflags",
"widestring",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.52.0" version = "0.52.0"
+2
View File
@@ -13,6 +13,8 @@ publish = false
ianitor-core = { path = "crates/core" } ianitor-core = { path = "crates/core" }
ianitor-edge = { path = "crates/edge" } ianitor-edge = { path = "crates/edge" }
ianitor-testkit = { path = "tests/support" } ianitor-testkit = { path = "tests/support" }
# The Domi CA, shared with Fabrica (docs/32_coherence.md T3a); pinned by tag.
domi-pki = { git = "https://gitea.marek-novak.cz/mnovak/domi-pki", tag = "v1.0.0" }
serde = { version = "1.0.228", features = ["derive"] } serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145" serde_json = "1.0.145"
toml = "1.2.1" toml = "1.2.1"
+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);
+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);
}
+32 -15
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))],
@@ -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;
+5
View File
@@ -23,6 +23,7 @@ test-hooks = []
[dependencies] [dependencies]
ianitor-core.workspace = true ianitor-core.workspace = true
url.workspace = true
rustls.workspace = true rustls.workspace = true
rustls-pki-types.workspace = true rustls-pki-types.workspace = true
tokio-rustls.workspace = true tokio-rustls.workspace = true
@@ -44,6 +45,10 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] }
# The offline root CLI asks for its passphrase without echo. # The offline root CLI asks for its passphrase without echo.
rpassword = "7" rpassword = "7"
# Windows Server, Caddy mode: the service control manager starts control and the guard.
[target.'cfg(windows)'.dependencies]
windows-service = "0.8"
[dev-dependencies] [dev-dependencies]
ianitor-testkit.workspace = true ianitor-testkit.workspace = true
p12-keystore = "0.4" p12-keystore = "0.4"
+23 -4
View File
@@ -935,6 +935,9 @@ pub struct TokenCreate {
pub expires_in_days: Option<u64>, pub expires_in_days: Option<u64>,
#[serde(default)] #[serde(default)]
pub never_expires: bool, pub never_expires: bool,
/// `full` (default) or `previews`: a token for Fabrica that may only use `/api/v1/previews`.
#[serde(default)]
pub scope: Option<String>,
} }
/// Make a token. Its value is in this response only. /// Make a token. Its value is in this response only.
@@ -966,7 +969,19 @@ pub async fn create_token(
let name = b let name = b
.name .name
.unwrap_or_else(|| format!("Token {}", ianitor_core::time::long_date(now()))); .unwrap_or_else(|| format!("Token {}", ianitor_core::time::long_date(now())));
let (rec, value) = st.ctl.tokens.create(&name, expires).map_err(|e| { let scope = match b.scope.as_deref() {
None => crate::tokens::Scope::Full,
Some(s) => crate::tokens::Scope::parse(s).ok_or_else(|| {
let mut e = ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"token.scope_value",
Params::new(),
);
e.body.field = Some("scope".into());
e
})?,
};
let (rec, value) = st.ctl.tokens.create(&name, expires, scope).map_err(|e| {
if e == "token.name" { if e == "token.name" {
let mut err = ApiError::new( let mut err = ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY, StatusCode::UNPROCESSABLE_ENTITY,
@@ -1384,7 +1399,9 @@ impl Modify for Bearer {
mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi, mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi,
super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request, super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request,
super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device, super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device,
super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine,
super::previews::list_previews, super::previews::open_preview, super::previews::get_preview,
super::previews::kill_preview, super::previews::close_preview
), ),
components(schemas( components(schemas(
HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate, HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate,
@@ -1394,13 +1411,15 @@ impl Modify for Bearer {
HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView, HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView,
super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody, super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody,
super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody, super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody,
FallbackReady FallbackReady, crate::hostspec::PreviewSpec, super::previews::PreviewOpen, super::previews::PreviewClose,
super::previews::PreviewView, super::previews::PreviewOpened, super::previews::PreviewOne,
super::previews::PreviewList, super::previews::PreviewClosed
)), )),
modifiers(&Bearer), modifiers(&Bearer),
tags( tags(
(name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"), (name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"),
(name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"), (name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"),
(name = "certs"), (name = "engine") (name = "certs"), (name = "engine"), (name = "previews")
) )
)] )]
pub struct ApiDoc; pub struct ApiDoc;
+29 -1
View File
@@ -17,6 +17,7 @@
pub mod handlers; pub mod handlers;
pub mod pki; pub mod pki;
pub mod previews;
pub mod ui; pub mod ui;
pub mod views; pub mod views;
@@ -45,11 +46,20 @@ use views::{ErrorBody, ErrorEnvelope};
pub const MAX_BODY: usize = 64 * 1024; pub const MAX_BODY: usize = 64 * 1024;
const RATE_PER_MINUTE: u32 = 120; const RATE_PER_MINUTE: u32 = 120;
/// Who is calling: the API token's id and name. /// Who is calling: the API token's id and name, and what the token may do.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Actor { pub struct Actor {
pub token_id: String, pub token_id: String,
pub name: String, pub name: String,
pub scope: crate::tokens::Scope,
}
/// The only routes a `previews` token may call (T4: it can never touch another host).
fn in_preview_scope(path: &str) -> bool {
path == "/api/v1/previews"
|| path
.strip_prefix("/api/v1/previews/")
.is_some_and(|rest| !rest.is_empty() && !rest.contains('/'))
} }
pub enum Stored { pub enum Stored {
@@ -461,6 +471,7 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
req.extensions_mut().insert(Actor { req.extensions_mut().insert(Actor {
token_id: format!("user:{user}"), token_id: format!("user:{user}"),
name: display, name: display,
scope: crate::tokens::Scope::Full,
}); });
return Ok(next.run(req).await); return Ok(next.run(req).await);
} }
@@ -490,6 +501,13 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
}; };
ApiError::new(StatusCode::UNAUTHORIZED, code, params) ApiError::new(StatusCode::UNAUTHORIZED, code, params)
})?; })?;
if tok.scope == crate::tokens::Scope::Previews && !in_preview_scope(req.uri().path()) {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"token.scope",
Params::new(),
));
}
st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60) st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60)
.map_err(|s| { .map_err(|s| {
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
@@ -497,6 +515,7 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
req.extensions_mut().insert(Actor { req.extensions_mut().insert(Actor {
token_id: tok.id, token_id: tok.id,
name: tok.name, name: tok.name,
scope: tok.scope,
}); });
Ok(next.run(req).await) Ok(next.run(req).await)
} }
@@ -620,6 +639,15 @@ pub fn router(st: Arc<AppState>) -> Router {
"/api/v1/engine", "/api/v1/engine",
get(pki::get_engine).post(pki::switch_engine), get(pki::get_engine).post(pki::switch_engine),
) )
.route(
"/api/v1/previews",
get(previews::list_previews).post(previews::open_preview),
)
.route("/api/v1/previews/close", post(previews::close_preview))
.route(
"/api/v1/previews/{hostname}",
get(previews::get_preview).delete(previews::kill_preview),
)
.route("/api/v1/health", get(h::health)) .route("/api/v1/health", get(h::health))
.route("/api/v1/openapi.json", get(h::openapi)) .route("/api/v1/openapi.json", get(h::openapi))
.method_not_allowed_fallback(method_not_allowed) .method_not_allowed_fallback(method_not_allowed)
+265
View File
@@ -0,0 +1,265 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! `/api/v1/previews`: Fabrica's branch previews (T4). The only routes a `previews` token may
//! call (the guard in `api` refuses every other route for it).
// An error answer is built once per failed request; boxing it buys nothing.
#![allow(clippy::result_large_err)]
use std::sync::Arc;
use axum::Extension;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use super::views::{ApplyView, apply_view};
use super::{Actor, ApiError, AppState, Body};
use crate::messages::Params;
use crate::util::rfc3339;
type Shared = State<Arc<AppState>>;
fn json<T: Serialize>(status: StatusCode, v: &T) -> Response {
(status, axum::Json(v)).into_response()
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PreviewOpen {
/// Fabrica's project, e.g. `mnovak/Arca` or `github:acme/web`.
pub project: String,
/// The git branch, as the git host names it.
pub branch: String,
/// Where the branch's build runs, e.g. `http://10.0.0.5:8080` (must be in `[previews] upstreams`).
pub upstream: String,
/// Seconds until the preview closes by itself (default from `[previews]`).
pub ttl: Option<u64>,
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PreviewClose {
pub project: String,
pub branch: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct PreviewView {
pub hostname: String,
/// `https://<hostname>/`
pub url: String,
pub project: String,
pub branch: String,
pub upstream: String,
pub expires_at: String,
/// `applying`, `live` or `failed`.
pub state: String,
/// Why it failed, in plain English.
#[serde(skip_serializing_if = "Option::is_none")]
pub problem: Option<String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct PreviewOpened {
pub preview: PreviewView,
pub apply: ApplyView,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct PreviewOne {
pub preview: PreviewView,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct PreviewList {
pub items: Vec<PreviewView>,
/// The domain previews live under; absent when previews are off.
pub domain: Option<String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct PreviewClosed {
pub apply: ApplyView,
}
fn view(st: &AppState, p: &crate::previews::Listed) -> PreviewView {
let (state, problem) = st
.ctl
.preview_state(&p.hostname)
.unwrap_or(("live".into(), None));
PreviewView {
url: format!("https://{}/", p.hostname),
hostname: p.hostname.clone(),
project: p.project.clone(),
branch: p.branch.clone(),
upstream: p.upstream.clone(),
expires_at: rfc3339(p.expires_at),
state,
problem,
}
}
/// Every open preview.
#[utoipa::path(get, path = "/api/v1/previews", tag = "previews",
responses((status = 200, body = PreviewList)), security(("bearer" = [])))]
pub async fn list_previews(State(st): Shared) -> Result<Response, ApiError> {
let domain = st.ctl.cfg.previews.as_ref().map(|p| p.domain.clone());
let items = if domain.is_some() {
st.ctl.previews()?.iter().map(|p| view(&st, p)).collect()
} else {
Vec::new()
};
Ok(json(StatusCode::OK, &PreviewList { items, domain }))
}
/// Open a branch's preview, or move it to a new upstream and lifetime. The host is
/// `<branch>--<project>.<preview domain>`; it is live when its apply is kept.
#[utoipa::path(post, path = "/api/v1/previews", tag = "previews", request_body = PreviewOpen,
responses((status = 202, body = PreviewOpened), (status = 403, body = super::views::ErrorEnvelope),
(status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)),
security(("bearer" = [])))]
pub async fn open_preview(
State(st): Shared,
Extension(actor): Extension<Actor>,
body: Body<PreviewOpen>,
) -> Result<Response, ApiError> {
let b = body.value;
let (hostname, expires_at, rec) =
st.ctl
.open_preview(&b.project, &b.branch, &b.upstream, b.ttl, &actor.name)?;
let preview = PreviewView {
url: format!("https://{hostname}/"),
hostname,
project: b.project,
branch: b.branch,
upstream: b.upstream,
expires_at: rfc3339(expires_at),
state: "applying".into(),
problem: None,
};
Ok(json(
StatusCode::ACCEPTED,
&PreviewOpened {
preview,
apply: apply_view(&st.ctl, &rec),
},
))
}
/// One preview and where it stands (Fabrica polls this after opening one).
#[utoipa::path(get, path = "/api/v1/previews/{hostname}", tag = "previews",
params(("hostname" = String, Path)),
responses((status = 200, body = PreviewOne), (status = 404, body = super::views::ErrorEnvelope)),
security(("bearer" = [])))]
pub async fn get_preview(
State(st): Shared,
Path(hostname): Path<String>,
) -> Result<Response, ApiError> {
st.ctl.previews_cfg()?;
let not_found = || ApiError::new(StatusCode::NOT_FOUND, "preview.not_found", Params::new());
if let Some(p) = st
.ctl
.previews()?
.into_iter()
.find(|p| p.hostname == hostname)
{
return Ok(json(
StatusCode::OK,
&PreviewOne {
preview: view(&st, &p),
},
));
}
// Not at the head: a preview whose apply is still running or failed.
let (state, problem) = st.ctl.preview_state(&hostname).ok_or_else(not_found)?;
let rec = st
.ctl
.records()
.into_iter()
.rev()
.find(|r| r.hosts.contains(&hostname))
.ok_or_else(not_found)?;
let pv = rec
.attempted_host
.as_ref()
.and_then(|h| h.preview.clone())
.ok_or_else(not_found)?;
Ok(json(
StatusCode::OK,
&PreviewOne {
preview: PreviewView {
url: format!("https://{hostname}/"),
hostname,
project: pv.project,
branch: pv.branch,
upstream: rec
.attempted_host
.as_ref()
.and_then(|h| h.upstreams.first().cloned())
.unwrap_or_default(),
expires_at: rfc3339(u64::try_from(pv.expires_at).unwrap_or(0)),
state,
problem,
},
},
))
}
/// Close a preview now (the previews screen's Close, or Fabrica after a merge).
#[utoipa::path(delete, path = "/api/v1/previews/{hostname}", tag = "previews",
params(("hostname" = String, Path)),
responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)),
security(("bearer" = [])))]
pub async fn kill_preview(
State(st): Shared,
Extension(actor): Extension<Actor>,
Path(hostname): Path<String>,
) -> Result<Response, ApiError> {
let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?;
Ok(json(
StatusCode::ACCEPTED,
&PreviewClosed {
apply: apply_view(&st.ctl, &rec),
},
))
}
/// Close a branch's preview by project and branch (Fabrica, when the branch is merged or
/// deleted).
#[utoipa::path(post, path = "/api/v1/previews/close", tag = "previews", request_body = PreviewClose,
responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)),
security(("bearer" = [])))]
pub async fn close_preview(
State(st): Shared,
Extension(actor): Extension<Actor>,
body: Body<PreviewClose>,
) -> Result<Response, ApiError> {
let b = body.value;
let p = st.ctl.previews_cfg()?;
let hostname = ianitor_core::preview::hostname(&b.project, &b.branch, &p.domain)
.map_err(crate::previews::name_fail)?;
let mine = st
.ctl
.previews()?
.into_iter()
.any(|x| x.hostname == hostname && x.project == b.project && x.branch == b.branch);
if !mine {
return Err(ApiError::new(
StatusCode::NOT_FOUND,
"preview.not_found",
Params::new(),
));
}
let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?;
Ok(json(
StatusCode::ACCEPTED,
&PreviewClosed {
apply: apply_view(&st.ctl, &rec),
},
))
}
+3
View File
@@ -746,6 +746,8 @@ pub struct TokenView {
pub last_used_at: Option<String>, pub last_used_at: Option<String>,
pub expires_at: Option<String>, pub expires_at: Option<String>,
pub revoked_at: Option<String>, pub revoked_at: Option<String>,
/// `full` or `previews`.
pub scope: String,
} }
impl From<&crate::tokens::TokenRecord> for TokenView { impl From<&crate::tokens::TokenRecord> for TokenView {
@@ -757,6 +759,7 @@ impl From<&crate::tokens::TokenRecord> for TokenView {
last_used_at: t(r.last_used_at), last_used_at: t(r.last_used_at),
expires_at: t(r.expires_at), expires_at: t(r.expires_at),
revoked_at: t(r.revoked_at), revoked_at: t(r.revoked_at),
scope: r.scope.as_str().into(),
} }
} }
} }
+4 -7
View File
@@ -127,15 +127,12 @@ async fn revert(cfg: &Config, why: &str) -> Result<bool, String> {
return Ok(false); return Ok(false);
} }
let loaded = async { let loaded = async {
let sock = cfg let sock = crate::caddy_link::Admin::from_compile(cfg.caddy_compile())
.caddy_compile() .ok_or("no caddy_admin_socket (or loopback caddy_admin) is configured")?;
.caddy_admin_socket
.clone()
.ok_or("no caddy_admin_socket is configured")?;
let text = std::fs::read(&cfg.caddy.config) let text = std::fs::read(&cfg.caddy.config)
.map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?; .map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?;
crate::caddy_link::load(Path::new(&sock), &text).await?; crate::caddy_link::load(&sock, &text).await?;
if !crate::caddy_link::runs(Path::new(&sock), &text).await? { if !crate::caddy_link::runs(&sock, &text).await? {
return Err("Caddy took caddy.json but does not run it".to_owned()); return Err("Caddy took caddy.json but does not run it".to_owned());
} }
Ok::<_, String>(()) Ok::<_, String>(())
+79 -23
View File
@@ -3,31 +3,93 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep //! 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, or on
//! loopback TCP where there are no Unix sockets (Windows Caddy mode, T4)
//! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host //! (`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, //! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch,
//! judged like edge's), and the certificate Caddy serves. //! 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, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const TIMEOUT: Duration = Duration::from_secs(10); const TIMEOUT: Duration = Duration::from_secs(10);
/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). /// Where Caddy's admin API listens: a Unix socket (Linux, mode 0660), or loopback TCP
async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec<u8>), String> { /// (Windows, where control and Caddy are the only services and the port is on 127.0.0.1).
#[cfg(unix)] #[derive(Debug, Clone, PartialEq, Eq)]
{ pub enum Admin {
use tokio::io::{AsyncReadExt, AsyncWriteExt}; Unix(PathBuf),
let exchange = async { Tcp(SocketAddr),
let mut s = tokio::net::UnixStream::connect(socket).await?; }
s.write_all(request).await?;
impl Admin {
/// From the compile facts: the socket when there is one, else a loopback TCP address.
pub fn from_compile(c: &crate::config::Compile) -> Option<Admin> {
match (&c.caddy_admin_socket, c.caddy_admin) {
(Some(s), _) => Some(Admin::Unix(PathBuf::from(s))),
(None, Some(a)) if a.ip().is_loopback() => Some(Admin::Tcp(a)),
_ => None,
}
}
/// The `Host` header Caddy's admin API accepts (its origin check).
fn host(&self) -> String {
match self {
Admin::Unix(_) => "localhost".into(),
Admin::Tcp(a) => a.to_string(),
}
}
}
impl From<&Path> for Admin {
fn from(p: &Path) -> Admin {
Admin::Unix(p.to_owned())
}
}
async fn exchange(admin: &Admin, request: &[u8]) -> std::io::Result<Vec<u8>> {
let mut buf = Vec::new(); let mut buf = Vec::new();
match admin {
#[cfg(unix)]
Admin::Unix(p) => {
let mut s = tokio::net::UnixStream::connect(p).await?;
s.write_all(request).await?;
s.read_to_end(&mut buf).await?; s.read_to_end(&mut buf).await?;
Ok::<_, std::io::Error>(buf) }
#[cfg(not(unix))]
Admin::Unix(_) => {
return Err(std::io::Error::other(
"Caddy's admin socket needs Unix; set caddy_admin = \"127.0.0.1:2019\" instead",
));
}
Admin::Tcp(a) => {
let mut s = tokio::net::TcpStream::connect(a).await?;
s.write_all(request).await?;
s.read_to_end(&mut buf).await?;
}
}
Ok(buf)
}
/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). `request` has
/// `{host}` where the Host header value goes.
async fn admin(admin: &Admin, request: &[u8]) -> Result<(u16, Vec<u8>), String> {
let host = admin.host();
let request = {
let split = request
.windows(4)
.position(|w| w == b"\r\n\r\n")
.unwrap_or(request.len());
let head = String::from_utf8_lossy(&request[..split]).replace("{host}", &host);
let mut r = head.into_bytes();
r.extend_from_slice(&request[split..]);
r
}; };
let buf = tokio::time::timeout(TIMEOUT, exchange) let buf = tokio::time::timeout(TIMEOUT, exchange(admin, &request))
.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}"))?;
@@ -43,20 +105,14 @@ async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec<u8>), String>
.ok_or("no answer from Caddy's admin API")?; .ok_or("no answer from Caddy's admin API")?;
Ok((status, buf[split + 4..].to_vec())) Ok((status, buf[split + 4..].to_vec()))
} }
#[cfg(not(unix))]
{
let _ = (socket, request);
Err("Caddy's admin socket needs Unix".into())
}
}
/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the /// 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 /// 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 /// 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`). /// 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> { pub async fn load(socket: &Admin, config: &[u8]) -> Result<(), String> {
let mut req = format!( 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", "POST /load HTTP/1.0\r\nHost: {{host}}\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n",
config.len() config.len()
) )
.into_bytes(); .into_bytes();
@@ -77,8 +133,8 @@ pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
} }
/// The config Caddy runs now. /// The config Caddy runs now.
pub async fn running_config(socket: &Path) -> Result<serde_json::Value, String> { pub async fn running_config(socket: &Admin) -> Result<serde_json::Value, String> {
let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?; let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: {host}\r\n\r\n").await?;
if status != 200 { if status != 200 {
return Err(format!( return Err(format!(
"Caddy's admin API answered {status} to GET /config/" "Caddy's admin API answered {status} to GET /config/"
@@ -88,7 +144,7 @@ pub async fn running_config(socket: &Path) -> Result<serde_json::Value, String>
} }
/// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter). /// 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> { pub async fn runs(socket: &Admin, config: &[u8]) -> Result<bool, String> {
let want: serde_json::Value = let want: serde_json::Value =
serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?; serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?;
Ok(running_config(socket).await? == want) Ok(running_config(socket).await? == want)
+63 -4
View File
@@ -58,6 +58,61 @@ pub struct Config {
/// Switching between Pingora and the Caddy fallback at runtime. /// Switching between Pingora and the Caddy fallback at runtime.
#[serde(default)] #[serde(default)]
pub engine: Option<EngineConfig>, pub engine: Option<EngineConfig>,
/// Branch previews for Fabrica (`POST /api/v1/previews`); off without it.
#[serde(default)]
pub previews: Option<PreviewsConfig>,
}
/// `[previews]`: where branch previews live and what they may point at.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PreviewsConfig {
/// Previews are `<branch>--<project>.<domain>`; a wildcard DNS record points here.
pub domain: String,
/// `domi` (the Domi CA, internal) or `letsencrypt` (public; one certificate per preview).
#[serde(default = "default_preview_tls")]
pub tls: String,
/// `none` (anyone with the address) or `forward-auth` (behind the site's sign-in).
#[serde(default = "default_preview_auth")]
pub auth: String,
/// Where previews may send traffic: `10.0.0.0/8`, `127.0.0.1:20000-29999`, `app.internal`,
/// `*.svc.internal:8080`. Nothing else is accepted; control's own port and Caddy's admin
/// port never are. Empty: every preview is refused.
#[serde(default)]
pub upstreams: Vec<String>,
#[serde(default = "default_preview_ttl")]
pub default_ttl_secs: u64,
#[serde(default = "default_preview_min_ttl")]
pub min_ttl_secs: u64,
#[serde(default = "default_preview_max_ttl")]
pub max_ttl_secs: u64,
#[serde(default = "default_preview_max")]
pub max_previews: usize,
/// How often expired previews are looked for.
#[serde(default = "default_preview_sweep")]
pub sweep_secs: u64,
}
fn default_preview_tls() -> String {
"domi".into()
}
fn default_preview_auth() -> String {
"none".into()
}
fn default_preview_ttl() -> u64 {
72 * 3600
}
fn default_preview_min_ttl() -> u64 {
300
}
fn default_preview_max_ttl() -> u64 {
30 * 86_400
}
fn default_preview_max() -> usize {
100
}
fn default_preview_sweep() -> u64 {
30
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -120,13 +175,14 @@ pub struct Compile {
impl Compile { impl Compile {
pub fn options(&self) -> CompileOptions { pub fn options(&self) -> CompileOptions {
use ianitor_core::compile::windows_path as w;
CompileOptions { CompileOptions {
http_listen: self.http_listen, http_listen: self.http_listen,
https_listen: self.https_listen, https_listen: self.https_listen,
cert_dir: self.cert_dir.clone(), cert_dir: w(&self.cert_dir),
state_dir: self.state_dir.clone(), state_dir: w(&self.state_dir),
access_log: self.access_log.clone(), access_log: w(&self.access_log),
caddy_credentials_dir: self.caddy_credentials_dir.clone(), caddy_credentials_dir: w(&self.caddy_credentials_dir),
caddy_admin: self.caddy_admin, caddy_admin: self.caddy_admin,
caddy_admin_socket: self.caddy_admin_socket.clone(), caddy_admin_socket: self.caddy_admin_socket.clone(),
trusted_proxies: self.trusted_proxies.clone(), trusted_proxies: self.trusted_proxies.clone(),
@@ -240,6 +296,9 @@ impl Config {
"pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}" "pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}"
))); )));
} }
if let Some(p) = &self.previews {
crate::previews::check_config(p, self).map_err(ConfigError::Invalid)?;
}
if let Some(m) = empty_model() { if let Some(m) = empty_model() {
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) { for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
ianitor_core::compile::edge(&m, &c.options()) ianitor_core::compile::edge(&m, &c.options())
+13 -1
View File
@@ -170,11 +170,23 @@ pub async fn run(args: &[String]) -> Result<(), String> {
logout_url: None, logout_url: None,
}), }),
engine: None, engine: None,
// Branch previews on a name nobody can own (RFC 2606), from loopback test upstreams.
previews: Some(ianitor_control::config::PreviewsConfig {
domain: "preview.dev.test".into(),
tls: "domi".into(),
auth: "none".into(),
upstreams: vec!["127.0.0.1:20000-29999".into(), "10.0.0.0/8".into()],
default_ttl_secs: 72 * 3600,
min_ttl_secs: 60,
max_ttl_secs: 30 * 86_400,
max_previews: 100,
sweep_secs: 10,
}),
}; };
cfg.check().map_err(|e| e.to_string())?; cfg.check().map_err(|e| e.to_string())?;
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE) Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None)?; let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None, Default::default())?;
// Control writes edge.json first; then edge can start from it. // Control writes edge.json first; then edge can start from it.
let ctl_cfg = cfg.clone(); let ctl_cfg = cfg.clone();
+28 -3
View File
@@ -53,6 +53,8 @@ struct Job {
id: String, id: String,
change: Change, change: Change,
base_rev: Option<String>, base_rev: Option<String>,
/// Replaces the plan's summary (and so the commit message), e.g. for previews.
summary: Option<String>,
} }
/// A refusal, before or during an apply. /// A refusal, before or during an apply.
@@ -740,6 +742,18 @@ impl Control {
change: Change, change: Change,
base_rev: Option<String>, base_rev: Option<String>,
actor: &str, actor: &str,
) -> Result<ApplyRecord, Fail> {
self.submit_as(change, base_rev, actor, None)
}
/// [`Control::submit`] with a summary of the caller's own (the history line and commit
/// message), e.g. "Opened the preview of fix-42 (shop)".
pub fn submit_as(
&self,
change: Change,
base_rev: Option<String>,
actor: &str,
summary: Option<String>,
) -> Result<ApplyRecord, Fail> { ) -> Result<ApplyRecord, Fail> {
if let Some(p) = self.paused_for(&change, false) { if let Some(p) = self.paused_for(&change, false) {
return Err(Fail::new( return Err(Fail::new(
@@ -749,7 +763,10 @@ impl Control {
)); ));
} }
let (head, tree) = self.head_and_tree()?; let (head, tree) = self.head_and_tree()?;
let plan = self.plan(&change, &head, &tree, base_rev.as_deref())?; let mut plan = self.plan(&change, &head, &tree, base_rev.as_deref())?;
if let Some(s) = &summary {
plan.summary = s.clone();
}
self.compile(&plan.model)?; self.compile(&plan.model)?;
let id = format!( let id = format!(
"ch_{}", "ch_{}",
@@ -792,6 +809,7 @@ impl Control {
id, id,
change, change,
base_rev, base_rev,
summary,
}); });
} }
self.wake.notify_one(); self.wake.notify_one();
@@ -930,7 +948,14 @@ impl Control {
Ok(x) => x, Ok(x) => x,
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors), Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
}; };
let plan = match self.plan(&job.change, &head, &tree, job.base_rev.as_deref()) { let plan = match self
.plan(&job.change, &head, &tree, job.base_rev.as_deref())
.map(|mut p| {
if let Some(s) = &job.summary {
p.summary = s.clone();
}
p
}) {
Ok(p) => p, Ok(p) => p,
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors), Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
}; };
@@ -1000,7 +1025,7 @@ impl Control {
} }
crash::point("committed"); crash::point("committed");
if !self.edge.attached() { if !self.edge.attached() && self.engine_running() != "caddy" {
// Development without an edge: write the files directly, nothing to watch. // Development without an edge: write the files directly, nothing to watch.
let r = write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644) let r = write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644)
.and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644)); .and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644));
+6 -9
View File
@@ -42,13 +42,10 @@ struct Rule {
} }
impl Control { impl Control {
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`). /// Caddy's admin API, from `[compile_caddy]` (or `[compile]`): its Unix socket, or its
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> { /// loopback TCP address on Windows.
self.cfg pub fn caddy_socket(&self) -> Option<caddy_link::Admin> {
.caddy_compile() caddy_link::Admin::from_compile(self.cfg.caddy_compile())
.caddy_admin_socket
.as_ref()
.map(std::path::PathBuf::from)
} }
/// Load caddy.json (the last good config) into the running Caddy, even when it is the /// Load caddy.json (the last good config) into the running Caddy, even when it is the
@@ -56,7 +53,7 @@ impl Control {
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 (or loopback caddy_admin) 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?;
@@ -334,7 +331,7 @@ impl Control {
async fn caddy_watch( async fn caddy_watch(
&self, &self,
id: &str, id: &str,
sock: &std::path::Path, sock: &caddy_link::Admin,
trial: &str, trial: &str,
judged: &[String], judged: &[String],
rules: &BTreeMap<String, Rule>, rules: &BTreeMap<String, Rule>,
+13
View File
@@ -38,6 +38,18 @@ pub struct HostSpec {
pub request_headers: Vec<HeaderRuleSpec>, pub request_headers: Vec<HeaderRuleSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub response_headers: Vec<HeaderRuleSpec>, pub response_headers: Vec<HeaderRuleSpec>,
/// Set on a branch preview (Fabrica); written by `/api/v1/previews`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preview: Option<PreviewSpec>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PreviewSpec {
pub project: String,
pub branch: String,
/// Unix seconds.
pub expires_at: i64,
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
@@ -178,6 +190,7 @@ mod tests {
secret: None, secret: None,
}], }],
response_headers: vec![], response_headers: vec![],
preview: None,
}; };
let text = h.to_toml().unwrap(); let text = h.to_toml().unwrap();
assert_eq!(HostSpec::from_toml(&text).unwrap(), h); assert_eq!(HostSpec::from_toml(&text).unwrap(), h);
+2
View File
@@ -18,6 +18,7 @@ pub mod logger;
pub mod messages; pub mod messages;
pub mod pki; pub mod pki;
pub mod pki_ctl; pub mod pki_ctl;
pub mod previews;
pub mod records; pub mod records;
pub mod repo; pub mod repo;
pub mod shares; pub mod shares;
@@ -42,6 +43,7 @@ pub async fn serve(
tokio::spawn(ctl.clone().health_poller()); tokio::spawn(ctl.clone().health_poller());
tokio::spawn(ctl.clone().pusher()); tokio::spawn(ctl.clone().pusher());
tokio::spawn(ctl.clone().pki_poller()); tokio::spawn(ctl.clone().pki_poller());
tokio::spawn(ctl.clone().preview_sweeper());
let app = api::router(api::AppState::new(ctl.clone())); let app = api::router(api::AppState::new(ctl.clone()));
if !listen.ip().is_loopback() { if !listen.ip().is_loopback() {
return Err("ianitor-control only listens on loopback".into()); return Err("ianitor-control only listens on loopback".into());
+34 -1
View File
@@ -12,6 +12,8 @@ use log::{Level, LevelFilter, Log, Metadata, Record};
struct Stderr { struct Stderr {
own: LevelFilter, own: LevelFilter,
/// `$IANITOR_LOG_FILE` or `--log-file`: append here instead of stderr (Windows services).
file: Option<std::sync::Mutex<std::fs::File>>,
} }
impl Log for Stderr { impl Log for Stderr {
@@ -33,6 +35,19 @@ impl Log for Stderr {
Level::Debug => "DEBUG", Level::Debug => "DEBUG",
Level::Trace => "TRACE", Level::Trace => "TRACE",
}; };
match &self.file {
Some(f) => {
if let Ok(mut f) = f.lock() {
let _ = writeln!(
f,
"{} {lvl} {}: {}",
crate::util::rfc3339(crate::util::now()),
r.target(),
r.args()
);
}
}
None => {
let _ = writeln!( let _ = writeln!(
std::io::stderr().lock(), std::io::stderr().lock(),
"{lvl} {}: {}", "{lvl} {}: {}",
@@ -41,6 +56,8 @@ impl Log for Stderr {
); );
} }
} }
}
}
fn flush(&self) { fn flush(&self) {
let _ = std::io::stderr().flush(); let _ = std::io::stderr().flush();
@@ -48,6 +65,22 @@ impl Log for Stderr {
} }
pub fn init(level: Option<&str>) { pub fn init(level: Option<&str>) {
init_to(
level,
std::env::var_os("IANITOR_LOG_FILE").map(std::path::PathBuf::from),
);
}
/// Like [`init`], appending to `file` when given.
pub fn init_to(level: Option<&str>, file: Option<std::path::PathBuf>) {
let file = file.and_then(|p| {
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(p)
.ok()
.map(std::sync::Mutex::new)
});
let own = match level.map(str::to_ascii_lowercase).as_deref() { let own = match level.map(str::to_ascii_lowercase).as_deref() {
Some("error") => LevelFilter::Error, Some("error") => LevelFilter::Error,
Some("warn") => LevelFilter::Warn, Some("warn") => LevelFilter::Warn,
@@ -55,7 +88,7 @@ pub fn init(level: Option<&str>) {
Some("trace") => LevelFilter::Trace, Some("trace") => LevelFilter::Trace,
_ => LevelFilter::Info, _ => LevelFilter::Info,
}; };
if log::set_boxed_logger(Box::new(Stderr { own })).is_ok() { if log::set_boxed_logger(Box::new(Stderr { own, file })).is_ok() {
log::set_max_level(own); log::set_max_level(own);
} }
} }
+44 -5
View File
@@ -5,7 +5,7 @@
//! ```text //! ```text
//! ianitor-control --config <control.toml> run the control plane //! ianitor-control --config <control.toml> run the control plane
//! ianitor-control --dev [--edge-bin <ianitor-edge>] temporary everything on 127.0.0.1 //! ianitor-control --dev [--edge-bin <ianitor-edge>] temporary everything on 127.0.0.1
//! ianitor-control token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) //! ianitor-control token create --name <name> [--scope full|previews] [--expires-days <n> | --never] (--config <c> | --state-dir <d>)
//! ianitor-control token list (--config <c> | --state-dir <d>) //! ianitor-control token list (--config <c> | --state-dir <d>)
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>) //! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
//! ianitor-control openapi print the OpenAPI document //! ianitor-control openapi print the OpenAPI document
@@ -15,6 +15,7 @@
//! ianitor-control ca init --out <dir> [--passphrase-file <f>] the offline root (never on the server) //! ianitor-control ca init --out <dir> [--passphrase-file <f>] the offline root (never on the server)
//! ianitor-control ca sign --root <dir> --csr <f> --out <f> [--yes] sign an intermediate offline //! ianitor-control ca sign --root <dir> --csr <f> --out <f> [--yes] sign an intermediate offline
//! ianitor-control check --config <control.toml> check the config and exit //! ianitor-control check --config <control.toml> check the config and exit
//! ianitor-control service control|caddy-guard --config <c> [--log-file <f>] Windows service
//! ``` //! ```
//! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`), //! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`),
//! the binary answers git's prompt from the push credential file. //! the binary answers git's prompt from the push credential file.
@@ -25,6 +26,8 @@ use std::process::ExitCode;
use ianitor_control::{Config, logger, tokens::Tokens}; use ianitor_control::{Config, logger, tokens::Tokens};
mod dev; mod dev;
#[cfg(windows)]
mod winsvc;
fn usage() -> ExitCode { fn usage() -> ExitCode {
eprintln!( eprintln!(
@@ -139,12 +142,19 @@ fn token(args: &[String]) -> Result<(), String> {
match args.first().map(String::as_str) { match args.first().map(String::as_str) {
Some("create") => { Some("create") => {
let mut name = None; let mut name = None;
let mut scope = ianitor_control::tokens::Scope::Full;
let mut expires = Some(ianitor_control::util::now() + 365 * 86_400); let mut expires = Some(ianitor_control::util::now() + 365 * 86_400);
let mut it = args.iter().skip(1); let mut it = args.iter().skip(1);
while let Some(a) = it.next() { while let Some(a) = it.next() {
match a.as_str() { match a.as_str() {
"--name" => name = it.next().cloned(), "--name" => name = it.next().cloned(),
"--never" => expires = None, "--never" => expires = None,
"--scope" => {
scope = it
.next()
.and_then(|s| ianitor_control::tokens::Scope::parse(s))
.ok_or("--scope must be full or previews")?;
}
"--expires-days" => { "--expires-days" => {
let d: u64 = it let d: u64 = it
.next() .next()
@@ -157,7 +167,7 @@ fn token(args: &[String]) -> Result<(), String> {
} }
} }
let name = name.ok_or("--name <name> is required")?; let name = name.ok_or("--name <name> is required")?;
let (rec, value) = tokens.create(&name, expires).map_err(|e| { let (rec, value) = tokens.create(&name, expires, scope).map_err(|e| {
if e == "token.name" { if e == "token.name" {
"the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores" "the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores"
.to_owned() .to_owned()
@@ -166,8 +176,10 @@ fn token(args: &[String]) -> Result<(), String> {
} }
})?; })?;
eprintln!( eprintln!(
"Token {} ({}) created. It is shown once; save it in Custos now:", "Token {} ({}, scope {}) created. It is shown once; save it in Custos now:",
rec.id, rec.name rec.id,
rec.name,
rec.scope.as_str()
); );
println!("{value}"); println!("{value}");
Ok(()) Ok(())
@@ -186,6 +198,9 @@ fn token(args: &[String]) -> Result<(), String> {
.map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e))) .map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e)))
.unwrap_or_default() .unwrap_or_default()
); );
if t.scope != ianitor_control::tokens::Scope::Full {
println!(" scope {}", t.scope.as_str());
}
} }
Ok(()) Ok(())
} }
@@ -375,8 +390,32 @@ fn main() -> ExitCode {
if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") { if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") {
return askpass(); return askpass();
} }
logger::init(std::env::var("IANITOR_LOG").ok().as_deref());
let args: Vec<String> = std::env::args().skip(1).collect(); let args: Vec<String> = std::env::args().skip(1).collect();
let log_file = args
.iter()
.position(|a| a == "--log-file")
.and_then(|i| args.get(i + 1))
.map(PathBuf::from);
match log_file {
Some(f) => logger::init_to(std::env::var("IANITOR_LOG").ok().as_deref(), Some(f)),
None => logger::init(std::env::var("IANITOR_LOG").ok().as_deref()),
}
// Windows Server, Caddy mode: started by the service control manager.
if args.first().map(String::as_str) == Some("service") {
#[cfg(windows)]
return match winsvc::run(&args[1..]) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("ianitor-control: {e}");
ExitCode::FAILURE
}
};
#[cfg(not(windows))]
{
eprintln!("ianitor-control: `service` is for Windows; use the systemd units on Linux");
return ExitCode::FAILURE;
}
}
let rt = match tokio::runtime::Builder::new_multi_thread() let rt = match tokio::runtime::Builder::new_multi_thread()
.enable_all() .enable_all()
.build() .build()
+23
View File
@@ -205,6 +205,29 @@ fn template(code: &str) -> &'static str {
"token.not_found" => "There is no API token with that id.", "token.not_found" => "There is no API token with that id.",
"token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.", "token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.",
"token.expiry" => "Choose between 1 and 3650 days, or never.", "token.expiry" => "Choose between 1 and 3650 days, or never.",
"token.scope" => {
"This API token may only open and close branch previews (/api/v1/previews)."
}
"token.scope_value" => "A token's scope is full or previews.",
"preview.off" => {
"Previews are off on this server: set a preview domain under [previews] in control.toml."
}
"preview.taken" => {
"{hostname} is already used by another host or branch, so this branch's preview cannot have it."
}
"preview.not_found" => "There is no preview at that address.",
"preview.branch" => "The branch name {problem}.",
"preview.project" => "The project name {problem}.",
"preview.domain" => "The preview address is not usable: {problem}.",
"preview.ttl" => "Choose a lifetime between {min} and {max} seconds.",
"preview.upstream" => {
"Write the preview's address as http://host:port or https://host:port, without a path, user or password."
}
"preview.upstream_not_allowed" => {
"{upstream} is not an address previews may use. Allowed: {allowed}."
}
"preview.too_many" => "There are already {max} previews. Close some first.",
"preview.expired" => "Preview of {branch} expired",
"rate.limited" => "Too many requests in a short time. Try again in {seconds} s.", "rate.limited" => "Too many requests in a short time. Try again in {seconds} s.",
"control.files_unwritten" => { "control.files_unwritten" => {
"The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them." "The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them."
+537
View File
@@ -0,0 +1,537 @@
// 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/.
//! Branch previews for Fabrica (Fabrica docs/32_coherence.md, T4). A preview is an ordinary
//! host file in the routes repository with a `[preview]` table, so it goes through the same
//! validation, compilers, differential tests and commit-confirmed apply as any host. This
//! module holds what is preview-only: the host body control writes, the upstream allow list
//! (a preview token is hostile: it must not be able to publish this machine's admin ports),
//! and the sweeper that closes expired previews.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use std::time::Duration;
use crate::config::{Config, PreviewsConfig};
use crate::engine::{Change, Control, Fail};
use crate::hostspec::{HeaderRuleSpec, HostSpec, PreviewSpec};
use crate::messages::{self, Params};
use crate::util::now;
/// The actor name the sweeper's removals carry in the history.
pub const EXPIRY_ACTOR: &str = "Preview expiry";
/// One entry of `[previews] upstreams`.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Target {
Net(IpAddr, u8),
Name(String),
/// `*.suffix`: any name ending in `.suffix`.
Suffix(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Allowed {
target: Target,
ports: Option<(u16, u16)>,
}
fn parse_ports(p: &str) -> Option<(u16, u16)> {
let (lo, hi) = match p.split_once('-') {
Some((a, b)) => (a.parse().ok()?, b.parse().ok()?),
None => {
let x: u16 = p.parse().ok()?;
(x, x)
}
};
(lo >= 1 && lo <= hi).then_some((lo, hi))
}
fn parse_entry(e: &str) -> Option<Allowed> {
let e = e.trim();
// IPv6 networks carry no port (`fd00::/8`); everything else may end in `:port[-port]`.
if e.matches(':').count() > 1 {
let (ip, bits) = e.split_once('/').unwrap_or((e, "128"));
let ip: Ipv6Addr = ip.parse().ok()?;
let bits: u8 = bits.parse().ok().filter(|b| *b <= 128)?;
return Some(Allowed {
target: Target::Net(IpAddr::V6(ip), bits),
ports: None,
});
}
let (host, ports) = match e.rsplit_once(':') {
Some((h, p)) => (h, Some(parse_ports(p)?)),
None => (e, None),
};
if let Some((ip, bits)) = host.split_once('/') {
let ip: Ipv4Addr = ip.parse().ok()?;
let bits: u8 = bits.parse().ok().filter(|b| *b <= 32)?;
return Some(Allowed {
target: Target::Net(IpAddr::V4(ip), bits),
ports,
});
}
if let Ok(ip) = host.parse::<Ipv4Addr>() {
return Some(Allowed {
target: Target::Net(IpAddr::V4(ip), 32),
ports,
});
}
let name = host.to_ascii_lowercase();
let plain = |n: &str| {
!n.is_empty()
&& n.len() <= 253
&& n.split('.').all(|l| {
!l.is_empty()
&& l.len() <= 63
&& l.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
})
};
if let Some(suffix) = name.strip_prefix("*.") {
return plain(suffix).then(|| Allowed {
target: Target::Suffix(suffix.to_owned()),
ports,
});
}
plain(&name).then(|| Allowed {
target: Target::Name(name),
ports,
})
}
fn in_net(ip: IpAddr, net: IpAddr, bits: u8) -> bool {
match (ip, net) {
(IpAddr::V4(a), IpAddr::V4(n)) => {
let mask = if bits == 0 {
0
} else {
u32::MAX << (32 - u32::from(bits))
};
u32::from(a) & mask == u32::from(n) & mask
}
(IpAddr::V6(a), IpAddr::V6(n)) => {
let mask = if bits == 0 {
0
} else {
u128::MAX << (128 - u32::from(bits))
};
u128::from(a) & mask == u128::from(n) & mask
}
_ => false,
}
}
/// Addresses no preview may ever use, whatever the allow list says.
fn never(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v) => {
v.is_unspecified() || v.is_link_local() || v.is_multicast() || v.is_broadcast()
}
IpAddr::V6(v) => {
v.is_unspecified()
|| v.is_multicast()
|| (v.segments()[0] & 0xffc0) == 0xfe80
|| v.to_ipv4_mapped().is_some()
}
}
}
/// Check the `[previews]` section at start.
pub fn check_config(p: &PreviewsConfig, cfg: &Config) -> Result<(), String> {
ianitor_core::preview::hostname("p", "main", &p.domain)
.map_err(|e| format!("previews.domain: {e}"))?;
if !["domi", "letsencrypt"].contains(&p.tls.as_str()) {
return Err("previews.tls must be domi or letsencrypt".into());
}
if !["none", "forward-auth"].contains(&p.auth.as_str()) {
return Err("previews.auth must be none or forward-auth".into());
}
for u in &p.upstreams {
if parse_entry(u).is_none() {
return Err(format!(
"previews.upstreams: {u:?} is not a network (10.0.0.0/8), an address with ports (127.0.0.1:20000-29999) or a name (app.internal, *.svc.internal)"
));
}
}
if p.min_ttl_secs == 0
|| p.min_ttl_secs > p.max_ttl_secs
|| !(p.min_ttl_secs..=p.max_ttl_secs).contains(&p.default_ttl_secs)
{
return Err(
"previews: min_ttl_secs ≤ default_ttl_secs ≤ max_ttl_secs, and min_ttl_secs > 0".into(),
);
}
if !(1..=3600).contains(&p.sweep_secs) || !(1..=10_000).contains(&p.max_previews) {
return Err("previews: sweep_secs 1 to 3600, max_previews 1 to 10000".into());
}
let _ = cfg;
Ok(())
}
fn fail(status: u16, code: &str, params: Params) -> Fail {
Fail::new(status, code, params)
}
/// Whether a preview may send traffic to `upstream`; the parsed URL's host and port.
pub fn check_upstream(cfg: &Config, p: &PreviewsConfig, upstream: &str) -> Result<(), Fail> {
let bad = || fail(422, "preview.upstream", Params::new());
if upstream.is_empty()
|| upstream.len() > 512
|| !upstream.bytes().all(|c| c.is_ascii_graphic())
{
return Err(bad());
}
let u = url::Url::parse(upstream).map_err(|_| bad())?;
if !["http", "https"].contains(&u.scheme())
|| !u.username().is_empty()
|| u.password().is_some()
|| u.query().is_some()
|| u.fragment().is_some()
|| !(u.path().is_empty() || u.path() == "/")
{
return Err(bad());
}
let port = u.port_or_known_default().ok_or_else(bad)?;
let host = u.host().ok_or_else(bad)?;
let shown = || {
messages::params([
("upstream", upstream.to_owned()),
("allowed", {
if p.upstreams.is_empty() {
"nothing yet (set [previews] upstreams)".to_owned()
} else {
p.upstreams.join(", ")
}
}),
])
};
let not_allowed = || fail(403, "preview.upstream_not_allowed", shown());
let ip = match &host {
url::Host::Ipv4(v) => Some(IpAddr::V4(*v)),
url::Host::Ipv6(v) => Some(IpAddr::V6(*v)),
url::Host::Domain(_) => None,
};
if let Some(ip) = ip {
if never(ip) {
return Err(not_allowed());
}
// This machine's own control API and Caddy admin API, whatever the list says.
if ip.is_loopback() {
let admin_ports = std::iter::once(cfg.listen.port()).chain(
[cfg.compile.caddy_admin, cfg.caddy_compile().caddy_admin]
.into_iter()
.flatten()
.map(|a| a.port()),
);
if admin_ports.into_iter().any(|a| a == port) || port == 2019 {
return Err(not_allowed());
}
}
}
let name = match &host {
url::Host::Domain(d) => Some(d.to_ascii_lowercase()),
_ => None,
};
let ok = p.upstreams.iter().filter_map(|e| parse_entry(e)).any(|a| {
let port_ok = a.ports.is_none_or(|(lo, hi)| (lo..=hi).contains(&port));
let host_ok = match (&a.target, ip, &name) {
(Target::Net(net, bits), Some(ip), _) => in_net(ip, *net, *bits),
(Target::Name(n), _, Some(h)) => n == h,
(Target::Suffix(s), _, Some(h)) => h.ends_with(&format!(".{s}")),
_ => false,
};
port_ok && host_ok
});
if ok { Ok(()) } else { Err(not_allowed()) }
}
/// The host body of a branch's preview.
pub fn spec(
p: &PreviewsConfig,
hostname: &str,
project: &str,
branch: &str,
upstream: &str,
expires_at: u64,
) -> HostSpec {
HostSpec {
hostname: hostname.to_owned(),
upstreams: vec![upstream.trim_end_matches('/').to_owned()],
tls: p.tls.clone(),
auth: p.auth.clone(),
websockets: true,
share_links: false,
device_certs: false,
access_log: "off".into(),
health_check: None,
request_headers: Vec::new(),
// A preview is not for search engines.
response_headers: vec![HeaderRuleSpec {
action: "set".into(),
name: "X-Robots-Tag".into(),
value: Some("noindex, nofollow".into()),
secret: None,
}],
preview: Some(PreviewSpec {
project: project.to_owned(),
branch: branch.to_owned(),
expires_at: i64::try_from(expires_at).unwrap_or(i64::MAX),
}),
}
}
/// A preview's field problem as an API refusal.
pub fn name_fail(e: ianitor_core::preview::PreviewError) -> Fail {
use ianitor_core::preview::PreviewError as P;
let (code, problem) = match &e {
P::Branch(r) => ("preview.branch", (*r).to_owned()),
P::Project(r) => ("preview.project", (*r).to_owned()),
P::Domain(r) => ("preview.domain", r.clone()),
};
let mut f = fail(422, code, messages::params([("problem", problem)]));
f.reason.field = Some(
match e {
P::Branch(_) => "branch",
P::Project(_) => "project",
P::Domain(_) => "domain",
}
.into(),
);
f
}
/// What the previews screen and Fabrica see.
#[derive(Debug, Clone)]
pub struct Listed {
pub hostname: String,
pub project: String,
pub branch: String,
pub upstream: String,
pub expires_at: u64,
}
impl Control {
pub fn previews_cfg(&self) -> Result<&PreviewsConfig, Fail> {
self.cfg
.previews
.as_ref()
.ok_or_else(|| fail(409, "preview.off", Params::new()))
}
/// Every preview at the branch head, by host name.
pub fn previews(&self) -> Result<Vec<Listed>, Fail> {
let (_, _, model) = self.head_model()?;
Ok(model
.hosts()
.iter()
.filter_map(|h| {
let p = h.preview.as_ref()?;
Some(Listed {
hostname: h.hostname.to_string(),
project: p.project.clone(),
branch: p.branch.clone(),
upstream: h
.upstreams
.first()
.map(ToString::to_string)
.unwrap_or_default(),
expires_at: p.expires_at,
})
})
.collect())
}
/// Open (or move) a branch's preview.
pub fn open_preview(
&self,
project: &str,
branch: &str,
upstream: &str,
ttl: Option<u64>,
actor: &str,
) -> Result<(String, u64, crate::records::ApplyRecord), Fail> {
let p = self.previews_cfg()?;
let hostname =
ianitor_core::preview::hostname(project, branch, &p.domain).map_err(name_fail)?;
let ttl = ttl.unwrap_or(p.default_ttl_secs);
if !(p.min_ttl_secs..=p.max_ttl_secs).contains(&ttl) {
let mut f = fail(
422,
"preview.ttl",
messages::params([
("min", p.min_ttl_secs.to_string()),
("max", p.max_ttl_secs.to_string()),
]),
);
f.reason.field = Some("ttl".into());
return Err(f);
}
check_upstream(&self.cfg, p, upstream)?;
let previews = self.previews()?;
let (_, tree, model) = self.head_model()?;
let existing = model
.hosts()
.iter()
.find(|h| h.hostname.as_str() == hostname);
let create = match existing {
None => {
if previews.len() >= p.max_previews {
return Err(fail(
409,
"preview.too_many",
messages::params([("max", p.max_previews.to_string())]),
));
}
true
}
Some(h) => match &h.preview {
Some(pv) if pv.project == project && pv.branch == branch => false,
_ => {
return Err(fail(
409,
"preview.taken",
messages::params([("hostname", hostname.clone())]),
));
}
},
};
drop(tree);
let expires_at = now().saturating_add(ttl);
let spec = spec(p, &hostname, project, branch, upstream, expires_at);
let summary = format!(
"{} the preview of {branch} ({project})",
if create { "Opened" } else { "Moved" }
);
let rec = self.submit_as(Change::Put { spec, create }, None, actor, Some(summary))?;
Ok((hostname, expires_at, rec))
}
/// Close a preview by its host name. Only preview hosts.
pub fn close_preview(
&self,
hostname: &str,
actor: &str,
why: &str,
) -> Result<crate::records::ApplyRecord, Fail> {
self.previews_cfg()?;
let pv = self
.previews()?
.into_iter()
.find(|p| p.hostname == hostname)
.ok_or_else(|| fail(404, "preview.not_found", Params::new()))?;
let summary = format!("{why} preview of {} ({})", pv.branch, pv.project);
self.submit_as(
Change::Delete {
hostname: hostname.to_owned(),
},
None,
actor,
Some(summary),
)
}
/// Where a preview stands: `applying`, `live`, `failed` (with why), or not a preview.
pub fn preview_state(&self, hostname: &str) -> Option<(String, Option<String>)> {
let live = self.previews().ok()?.iter().any(|p| p.hostname == hostname);
let last = self
.records()
.into_iter()
.rev()
.find(|r| r.hosts.iter().any(|h| h == hostname));
let pending = last
.as_ref()
.is_some_and(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()));
if pending {
return Some(("applying".into(), None));
}
if live {
return Some(("live".into(), None));
}
let r = last?;
// A preview that never went live because its apply failed.
(r.summary.contains("the preview of") && r.state != "kept").then(|| {
(
"failed".into(),
r.reason.as_ref().map(|x| x.message.clone()),
)
})
}
/// Close expired previews, every `sweep_secs`.
pub async fn preview_sweeper(self: Arc<Self>) {
let Some(p) = self.cfg.previews.clone() else {
return;
};
loop {
tokio::time::sleep(Duration::from_secs(p.sweep_secs)).await;
let Ok(list) = self.previews() else {
continue;
};
let t = now();
let busy: Vec<String> = self
.records()
.into_iter()
.filter(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()))
.flat_map(|r| r.hosts)
.collect();
for pv in list.iter().filter(|p| p.expires_at <= t) {
if busy.contains(&pv.hostname) {
continue;
}
match self.close_preview(&pv.hostname, EXPIRY_ACTOR, "Closed the expired") {
Ok(_) => {
log::info!(target: "ianitor::previews", "the preview {} expired; closing it", pv.hostname)
}
Err(f) => {
log::warn!(target: "ianitor::previews", "cannot close the expired preview {}: {}", pv.hostname, f.reason.message)
}
}
}
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn allow_list_entries_parse() {
for ok in [
"10.0.0.0/8",
"127.0.0.1:20000-29999",
"192.168.1.5:8080",
"app.internal",
"app.internal:3000",
"*.svc.internal",
"fd00::/8",
] {
assert!(parse_entry(ok).is_some(), "{ok}");
}
for bad in [
"",
"10.0.0.0/33",
"a b",
"x:0",
"x:9-1",
"*.",
"http://x",
"1.2.3.4/8:70000",
] {
assert!(parse_entry(bad).is_none(), "{bad}");
}
}
#[test]
fn networks_match() {
let n = |s: &str| s.parse::<IpAddr>().unwrap();
assert!(in_net(n("10.1.2.3"), n("10.0.0.0"), 8));
assert!(!in_net(n("11.1.2.3"), n("10.0.0.0"), 8));
assert!(in_net(n("fd12::1"), n("fd00::"), 8));
assert!(in_net(n("1.2.3.4"), n("0.0.0.0"), 0));
assert!(never(n("0.0.0.0")) && never(n("169.254.169.254")) && never(n("::ffff:127.0.0.1")));
}
}
+34 -2
View File
@@ -23,6 +23,34 @@ use serde::{Deserialize, Serialize};
use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json}; use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json};
/// What a token may do. `full` (the default, and every token made before T4) may do
/// everything the API offers; `previews` may only use `/api/v1/previews` (Fabrica's branch
/// previews), so a leaked preview token can never touch another host.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Scope {
#[default]
Full,
Previews,
}
impl Scope {
pub fn as_str(self) -> &'static str {
match self {
Scope::Full => "full",
Scope::Previews => "previews",
}
}
pub fn parse(s: &str) -> Option<Scope> {
match s {
"full" => Some(Scope::Full),
"previews" => Some(Scope::Previews),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct TokenRecord { pub struct TokenRecord {
@@ -33,6 +61,8 @@ pub struct TokenRecord {
pub expires_at: Option<u64>, pub expires_at: Option<u64>,
pub last_used_at: Option<u64>, pub last_used_at: Option<u64>,
pub revoked_at: Option<u64>, pub revoked_at: Option<u64>,
#[serde(default)]
pub scope: Scope,
} }
#[derive(Debug, Default, Serialize, Deserialize)] #[derive(Debug, Default, Serialize, Deserialize)]
@@ -117,6 +147,7 @@ impl Tokens {
&self, &self,
name: &str, name: &str,
expires_at: Option<u64>, expires_at: Option<u64>,
scope: Scope,
) -> Result<(TokenRecord, String), String> { ) -> Result<(TokenRecord, String), String> {
let _g = self.guard()?; let _g = self.guard()?;
if !valid_name(name) { if !valid_name(name) {
@@ -137,6 +168,7 @@ impl Tokens {
expires_at, expires_at,
last_used_at: None, last_used_at: None,
revoked_at: None, revoked_at: None,
scope,
}; };
f.tokens.push(rec.clone()); f.tokens.push(rec.clone());
self.save(&f)?; self.save(&f)?;
@@ -231,7 +263,7 @@ mod tests {
fn create_check_revoke() { fn create_check_revoke() {
let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id())); let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id()));
let t = Tokens::new(&d); let t = Tokens::new(&d);
let (rec, value) = t.create("laptop", None).unwrap(); let (rec, value) = t.create("laptop", None, Scope::Full).unwrap();
assert!(value.starts_with("ian_")); assert!(value.starts_with("ian_"));
let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap(); let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap();
assert!(!stored.contains(&value[21..]), "only the hash is stored"); assert!(!stored.contains(&value[21..]), "only the hash is stored");
@@ -253,7 +285,7 @@ mod tests {
t.check(Some(&format!("Bearer {value}"))).unwrap_err(), t.check(Some(&format!("Bearer {value}"))).unwrap_err(),
Refusal::Revoked(_) Refusal::Revoked(_)
)); ));
let (_, v2) = t.create("old", Some(1)).unwrap(); let (_, v2) = t.create("old", Some(1), Scope::Full).unwrap();
assert_eq!( assert_eq!(
t.check(Some(&format!("Bearer {v2}"))).unwrap_err(), t.check(Some(&format!("Bearer {v2}"))).unwrap_err(),
Refusal::Expired(1) Refusal::Expired(1)
+109
View File
@@ -0,0 +1,109 @@
// 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/.
//! Windows Server, Caddy mode (Fabrica docs/32_coherence.md §2.5, T4): what the service
//! control manager starts. `ianitor-control service control --config <c>` is the control
//! plane, `ianitor-control service caddy-guard --config <c>` the Caddy trial deadline guard
//! (its own service, so a hung or crashed control cannot leave Caddy on an unconfirmed
//! trial). Both stop cleanly on the SCM's Stop. `deploy/windows/install.ps1` registers them.
//! Logs go to the file given with `--log-file` (stderr goes nowhere under the SCM).
use std::ffi::OsString;
use std::sync::OnceLock;
use std::time::Duration;
use windows_service::service::{
ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType,
};
use windows_service::service_control_handler::{self, ServiceControlHandlerResult};
use windows_service::{define_windows_service, service_dispatcher};
static ARGS: OnceLock<Vec<String>> = OnceLock::new();
define_windows_service!(ffi_service_main, service_main);
/// Hand this process to the service control manager (blocks until the service stops).
pub fn run(args: &[String]) -> Result<(), String> {
let _ = ARGS.set(args.to_vec());
// The name is ignored for a service in its own process.
service_dispatcher::start("IanitorControl", ffi_service_main)
.map_err(|e| format!("not started by the service control manager ({e}); run it as a service, or use --config to run it in a console"))
}
fn status(state: ServiceState, code: u32) -> ServiceStatus {
ServiceStatus {
service_type: ServiceType::OWN_PROCESS,
current_state: state,
controls_accepted: if state == ServiceState::Running {
ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN
} else {
ServiceControlAccept::empty()
},
exit_code: ServiceExitCode::Win32(code),
checkpoint: 0,
wait_hint: Duration::from_secs(10),
process_id: None,
}
}
fn service_main(_: Vec<OsString>) {
let args = ARGS.get().cloned().unwrap_or_default();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
let tx = std::sync::Mutex::new(Some(tx));
let handler = move |c| match c {
ServiceControl::Stop | ServiceControl::Shutdown => {
if let Ok(mut t) = tx.lock()
&& let Some(t) = t.take()
{
let _ = t.send(());
}
ServiceControlHandlerResult::NoError
}
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
_ => ServiceControlHandlerResult::NotImplemented,
};
let Ok(h) = service_control_handler::register("IanitorControl", handler) else {
return;
};
let _ = h.set_service_status(status(ServiceState::Running, 0));
let result = serve(&args, rx);
if let Err(e) = &result {
log::error!(target: "ianitor::service", "{e}");
}
let _ = h.set_service_status(status(ServiceState::Stopped, u32::from(result.is_err())));
}
fn serve(args: &[String], stop: tokio::sync::oneshot::Receiver<()>) -> Result<(), String> {
let what = args.first().map(String::as_str).unwrap_or("control");
let config = args
.iter()
.position(|a| a == "--config")
.and_then(|i| args.get(i + 1))
.ok_or("service: --config <control.toml> is required")?;
let cfg =
ianitor_control::Config::load(std::path::Path::new(config)).map_err(|e| e.to_string())?;
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|e| e.to_string())?;
rt.block_on(async move {
match what {
"control" => {
ianitor_control::serve(cfg, async {
let _ = stop.await;
})
.await
}
"caddy-guard" => {
tokio::select! {
r = ianitor_control::caddy_guard::run(cfg) => r,
_ = stop => Ok(()),
}
}
other => Err(format!(
"service: unknown part {other:?} (control or caddy-guard)"
)),
}
})
}
+280
View File
@@ -0,0 +1,280 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Caddy mode end to end (T4: Windows Server runs control with Caddy as the data plane, no
//! edge). Control runs with `engine = caddy`, Caddy's admin API on loopback TCP (as on
//! Windows), and the Domi CA. A previews-only token opens a branch preview; the apply goes
//! through Caddy (trial, watch, confirm); the preview's address then answers through Caddy
//! with a Domi certificate; closing it takes it away again. Runs on Windows and on Linux.
//! Needs `caddy` on PATH or `$IANITOR_CADDY_BIN` (else it fails, unless IANITOR_ALLOW_SKIP=1).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};
use ianitor_control::Config;
use ianitor_control::tokens::{Scope, Tokens};
use ianitor_testkit::client::{self, Req};
use ianitor_testkit::more::{JsonResp, tcp_json};
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, require_binary, wait_for_port};
use ianitor_testkit::upstream::Echo;
use serde_json::{Value, json};
fn s(p: &std::path::Path) -> String {
p.to_string_lossy().replace('\\', "/")
}
async fn call(
api: SocketAddr,
token: &str,
method: &str,
path: &str,
body: Option<Value>,
) -> JsonResp {
let auth = format!("Bearer {token}");
tcp_json(
api,
method,
path,
&[("Authorization", &auth)],
body.as_ref(),
)
.await
.unwrap()
}
async fn settle(api: SocketAddr, token: &str, apply: &Value) -> Value {
let id = apply["id"].as_str().unwrap().to_owned();
let t = Instant::now();
loop {
let r = call(api, token, "GET", &format!("/api/v1/applies/{id}"), None).await;
if ["kept", "reverted", "failed"].contains(&r.json["state"].as_str().unwrap_or("")) {
return r.json;
}
assert!(
t.elapsed() < Duration::from_secs(90),
"apply stuck: {}",
r.text
);
tokio::time::sleep(Duration::from_millis(700)).await;
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_branch_preview_answers_through_caddy_without_an_edge() {
let Some(caddy) = require_binary("caddy") else {
return;
};
let dir = TempDir::new("caddy-mode");
for d in [
"state",
"edge",
"caddy",
"certs",
"creds",
"caddy-state",
"root",
"xdg",
] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
// The offline root (a test one) and the intermediate's password.
let now = ianitor_control::util::now();
let (root_pem, root_key) = ianitor_core::pki::create_root(now as i64).unwrap();
std::fs::write(dir.join("root/domi-root.crt"), &root_pem).unwrap();
std::fs::write(
dir.join("creds/pki-password"),
"caddy-mode-test-password-0123456789",
)
.unwrap();
let api = local(free_port());
let admin = local(free_port());
let (http, https) = (free_port(), free_port());
// Caddy starts with only its admin API, as the installer starts it; control loads the rest.
let boot = json!({"admin": {"listen": admin.to_string()}}).to_string();
std::fs::write(dir.join("caddy/boot.json"), &boot).unwrap();
let log = std::fs::File::create(dir.join("caddy.log")).unwrap();
let _caddy = ChildGuard(
Command::new(&caddy)
.args(["run", "--config"])
.arg(dir.join("caddy/boot.json"))
.env("HOME", dir.join("xdg"))
.env("XDG_CONFIG_HOME", dir.join("xdg"))
.env("XDG_DATA_HOME", dir.join("xdg"))
.env("APPDATA", dir.join("xdg"))
.stdout(Stdio::from(log.try_clone().unwrap()))
.stderr(Stdio::from(log))
.spawn()
.unwrap(),
);
assert!(
wait_for_port(admin, Duration::from_secs(20)),
"Caddy's admin API did not start"
);
std::fs::write(dir.join("state/engine"), "caddy\n").unwrap();
let text = format!(
r#"listen = "{api}"
state_dir = "{state}"
credentials_dir = "{creds}"
watch_secs = 2
watch_every_secs = 1
trial_margin_secs = 5
[routes]
repo = "{repo}"
[edge]
config = "{edge}/edge.json"
share_revocations = "{edge}/share-revocations.json"
[caddy]
config = "{caddy_dir}/caddy.json"
[compile]
http_listen = "127.0.0.1:{http}"
https_listen = "127.0.0.1:{https}"
cert_dir = "{certs}"
state_dir = "{caddy_state}"
access_log = "{caddy_state}/access.log"
caddy_credentials_dir = "{creds}"
caddy_admin = "{admin}"
[pki]
root_cert = "{root}/domi-root.crt"
kdf_iterations = 10000
[engine]
file = "{state}/engine"
units = "none"
[previews]
domain = "pv.test"
tls = "domi"
upstreams = ["127.0.0.1:1024-65535"]
min_ttl_secs = 60
"#,
state = s(&dir.join("state")),
creds = s(&dir.join("creds")),
repo = s(&dir.join("routes.git")),
edge = s(&dir.join("edge")),
caddy_dir = s(&dir.join("caddy")),
certs = s(&dir.join("certs")),
caddy_state = s(&dir.join("caddy-state")),
root = s(&dir.join("root")),
);
std::fs::write(dir.join("control.toml"), text).unwrap();
let cfg = Config::load(&dir.join("control.toml")).unwrap();
// The intermediate, signed by the test root (the offline step of docs/pki.md).
{
let c = ianitor_control::Control::open(cfg.clone()).await.unwrap();
let p = c.pki.as_ref().unwrap();
let r = p.request_renewal(now, "test").unwrap();
let signed = ianitor_core::pki::sign_intermediate(
&root_pem,
&root_key,
r.csr_pem.as_deref().unwrap(),
now as i64,
)
.unwrap();
p.install_intermediate(&r.id, &signed, now).unwrap();
}
let tokens = Tokens::new(&dir.join("state"));
let (_, admin_tok) = tokens.create("admin", None, Scope::Full).unwrap();
let (_, fabrica) = tokens.create("fabrica", None, Scope::Previews).unwrap();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(ianitor_control::serve(cfg, async {
let _ = rx.await;
}));
assert!(wait_for_port(api, Duration::from_secs(20)));
let r = call(api, &admin_tok, "GET", "/api/v1/overview", None).await;
assert_eq!(r.json["engine"]["running"], "caddy", "{}", r.text);
assert_eq!(r.json["engine"]["switchable"], false, "{}", r.text);
// Fabrica opens the branch's preview.
let app = Echo::start("preview-app").await;
let r = call(
api,
&fabrica,
"POST",
"/api/v1/previews",
Some(json!({"project": "shop", "branch": "fix-42", "upstream": app.url(), "ttl": 3600})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned();
assert_eq!(host, "fix-42--shop.pv.test");
let done = settle(api, &admin_tok, &r.json["apply"]).await;
assert_eq!(done["state"], "kept", "{done}");
let steps: Vec<String> = done["steps"]
.as_array()
.unwrap()
.iter()
.map(|s| {
format!(
"{}={}",
s["key"].as_str().unwrap(),
s["state"].as_str().unwrap()
)
})
.collect();
assert!(
steps.contains(&"watch=done".to_owned()),
"watched through Caddy: {steps:?}"
);
// The preview answers through Caddy, with a certificate from the Domi CA.
let mut roots = rustls::RootCertStore::empty();
for der in ianitor_core::pki::chain_der(&root_pem).unwrap() {
roots
.add(rustls_pki_types::CertificateDer::from(der))
.unwrap();
}
let roots = Arc::new(roots);
let https_addr = local(https);
let resp = client::https(https_addr, &host, roots.clone(), &Req::get(&host, "/hello"))
.await
.unwrap();
assert_eq!(resp.status, 200);
assert_eq!(resp.header("x-robots-tag"), Some("noindex, nofollow"));
assert!(String::from_utf8_lossy(&resp.body).contains("preview-app"));
let r = call(
api,
&fabrica,
"GET",
&format!("/api/v1/previews/{host}"),
None,
)
.await;
assert_eq!(r.json["preview"]["state"], "live", "{}", r.text);
// Closed on merge: Caddy stops serving it.
let r = call(
api,
&fabrica,
"POST",
"/api/v1/previews/close",
Some(json!({"project": "shop", "branch": "fix-42"})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(
settle(api, &admin_tok, &r.json["apply"]).await["state"],
"kept"
);
let gone = client::https(https_addr, &host, roots, &Req::get(&host, "/hello")).await;
assert!(
gone.as_ref()
.map_or(true, |r| r.status == 404 || r.status == 421),
"{:?}",
gone.map(|r| r.status)
);
let _ = tx.send(());
}
+539
View File
@@ -0,0 +1,539 @@
// 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/.
//! Branch previews for Fabrica (T4, tests first). `POST /api/v1/previews {project, branch,
//! upstream, ttl}` gives the branch the host `<branch>--<project>.<preview domain>`; a token
//! scoped to previews may do that and nothing else. These tests run control in this process
//! without an edge (applies are kept at once), so they run on Windows too; the end-to-end
//! runs through Pingora and Caddy are in tests/diff and scripts/preview-smoke.*.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::time::{Duration, Instant};
use ianitor_control::Config;
use ianitor_control::tokens::{Scope, Tokens};
use ianitor_testkit::more::{JsonResp, tcp_json};
use ianitor_testkit::proc::{TempDir, free_port, local, wait_for_port};
use serde_json::{Value, json};
const DOMAIN: &str = "pv.example.test";
struct Ctl {
dir: TempDir,
api: SocketAddr,
admin: String,
preview: String,
stop: Option<tokio::sync::oneshot::Sender<()>>,
}
impl Drop for Ctl {
fn drop(&mut self) {
if let Some(s) = self.stop.take() {
let _ = s.send(());
}
}
}
fn s(p: &std::path::Path) -> String {
p.to_string_lossy().replace('\\', "/")
}
impl Ctl {
async fn start(extra: &str) -> Ctl {
let dir = TempDir::new("pv");
for d in ["state", "edge", "caddy", "certs", "creds", "edge-state"] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
let api = local(free_port());
let text = format!(
r#"listen = "{api}"
state_dir = "{state}"
credentials_dir = "{creds}"
[routes]
repo = "{repo}"
[edge]
config = "{edge}/edge.json"
share_revocations = "{edge}/share-revocations.json"
[caddy]
config = "{caddy}/caddy.json"
[compile]
http_listen = "127.0.0.1:{http}"
https_listen = "127.0.0.1:{https}"
cert_dir = "{certs}"
state_dir = "{edge_state}"
access_log = "{edge_state}/access.log"
caddy_credentials_dir = "{creds}"
[previews]
domain = "{DOMAIN}"
tls = "letsencrypt"
upstreams = ["10.0.0.0/8", "127.0.0.1:20000-29999", "app.internal"]
min_ttl_secs = 1
sweep_secs = 1
{extra}
"#,
state = s(&dir.join("state")),
creds = s(&dir.join("creds")),
repo = s(&dir.join("routes.git")),
edge = s(&dir.join("edge")),
caddy = s(&dir.join("caddy")),
certs = s(&dir.join("certs")),
edge_state = s(&dir.join("edge-state")),
http = free_port(),
https = free_port(),
);
let path = dir.join("control.toml");
std::fs::write(&path, text).unwrap();
let cfg = Config::load(&path).unwrap();
let tokens = Tokens::new(&dir.join("state"));
let (_, admin) = tokens.create("admin", None, Scope::Full).unwrap();
let (_, preview) = tokens
.create("fabrica previews", None, Scope::Previews)
.unwrap();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(async move {
if let Err(e) = ianitor_control::serve(cfg, async {
let _ = rx.await;
})
.await
{
panic!("control stopped: {e}");
}
});
assert!(
wait_for_port(api, Duration::from_secs(20)),
"control did not listen"
);
Ctl {
dir,
api,
admin,
preview,
stop: Some(tx),
}
}
async fn call(&self, token: &str, method: &str, path: &str, body: Option<Value>) -> JsonResp {
let auth = format!("Bearer {token}");
tcp_json(
self.api,
method,
path,
&[("Authorization", &auth)],
body.as_ref(),
)
.await
.unwrap()
}
async fn admin(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
self.call(&self.admin, method, path, body).await
}
async fn fabrica(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
self.call(&self.preview, method, path, body).await
}
/// Wait for an apply to end; returns its final state.
async fn settle(&self, apply: &Value) -> String {
let id = apply["id"].as_str().expect("an apply id").to_owned();
let t = Instant::now();
loop {
let r = self
.admin("GET", &format!("/api/v1/applies/{id}"), None)
.await;
let state = r.json["state"].as_str().unwrap_or("").to_owned();
if ["kept", "reverted", "failed"].contains(&state.as_str()) {
return state;
}
assert!(
t.elapsed() < Duration::from_secs(30),
"apply {id} stuck: {}",
r.text
);
tokio::time::sleep(Duration::from_millis(700)).await;
}
}
async fn host_names(&self) -> Vec<String> {
let r = self.admin("GET", "/api/v1/hosts", None).await;
assert_eq!(r.status, 200, "{}", r.text);
r.json["hosts"]
.as_array()
.unwrap()
.iter()
.map(|h| h["hostname"].as_str().unwrap().to_owned())
.collect()
}
async fn add_plain_host(&self, hostname: &str) {
let r = self
.admin(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": hostname, "upstreams": ["http://10.0.0.9:80"]}})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(self.settle(&r.json["apply"]).await, "kept");
}
async fn open_preview(&self, project: &str, branch: &str, upstream: &str) -> JsonResp {
self.fabrica(
"POST",
"/api/v1/previews",
Some(json!({"project": project, "branch": branch, "upstream": upstream, "ttl": 3600})),
)
.await
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_preview_token_cannot_touch_non_preview_hosts() {
let c = Ctl::start("").await;
c.add_plain_host("www.example.test").await;
let www =
json!({"host": {"hostname": "www.example.test", "upstreams": ["http://10.6.6.6:80"]}});
// Everything outside /api/v1/previews is refused, reads included.
let refused: Vec<(&str, &str, Option<Value>)> = vec![
("GET", "/api/v1/overview", None),
("GET", "/api/v1/hosts", None),
("GET", "/api/v1/hosts/www.example.test", None),
(
"POST",
"/api/v1/hosts",
Some(
json!({"host": {"hostname": "evil.example.test", "upstreams": ["http://10.6.6.6:80"]}}),
),
),
("PUT", "/api/v1/hosts/www.example.test", Some(www.clone())),
(
"PATCH",
"/api/v1/hosts/www.example.test",
Some(json!({"share_links": true})),
),
("DELETE", "/api/v1/hosts/www.example.test", None),
("POST", "/api/v1/hosts/validate", Some(www["host"].clone())),
("POST", "/api/v1/undo", Some(json!({}))),
("POST", "/api/v1/restore", Some(json!({"change_id": "x"}))),
("GET", "/api/v1/history", None),
("GET", "/api/v1/applies", None),
("GET", "/api/v1/tokens", None),
("POST", "/api/v1/tokens", Some(json!({"name": "escalate"}))),
(
"POST",
"/api/v1/hosts/www.example.test/share-links",
Some(json!({})),
),
("POST", "/api/v1/share-links/stop-all", None),
("GET", "/api/v1/certs", None),
("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))),
("POST", "/api/v1/repo/push", None),
("GET", "/api/v1/settings", None),
("GET", "/api/v1/team", None),
];
for (m, p, b) in refused {
let r = c.fabrica(m, p, b).await;
assert_eq!(r.status, 403, "{m} {p}: {}", r.text);
assert_eq!(
r.json["error"]["code"], "token.scope",
"{m} {p}: {}",
r.text
);
}
// The previews API refuses a host that is not a preview.
let r = c
.fabrica("DELETE", "/api/v1/previews/www.example.test", None)
.await;
assert_eq!(r.status, 404, "{}", r.text);
assert_eq!(r.json["error"]["code"], "preview.not_found");
let r = c
.fabrica("GET", "/api/v1/previews/www.example.test", None)
.await;
assert_eq!(r.status, 404, "{}", r.text);
// A non-preview host at exactly the name a preview would get is not taken over.
let taken = format!("main--shop.{DOMAIN}");
c.add_plain_host(&taken).await;
let r = c.open_preview("shop", "main", "http://10.0.0.5:8080").await;
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "preview.taken");
let r = c
.admin("GET", &format!("/api/v1/hosts/{taken}"), None)
.await;
assert_eq!(
r.json["host"]["upstreams"][0], "http://10.0.0.9:80",
"{}",
r.text
);
let r = c
.fabrica(
"POST",
"/api/v1/previews/close",
Some(json!({"project": "shop", "branch": "main"})),
)
.await;
assert_eq!(r.status, 404, "{}", r.text);
// A preview the token made touches only its own file, and the list holds only previews.
let r = c
.open_preview("shop", "fix-1", "http://10.0.0.5:8080")
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
let hosts = r.json["apply"]["hosts"].as_array().unwrap().clone();
assert_eq!(hosts, vec![json!(format!("fix-1--shop.{DOMAIN}"))]);
let r = c.fabrica("GET", "/api/v1/previews", None).await;
assert_eq!(r.status, 200, "{}", r.text);
let listed: Vec<&str> = r.json["items"]
.as_array()
.unwrap()
.iter()
.map(|p| p["hostname"].as_str().unwrap())
.collect();
assert_eq!(listed, vec![format!("fix-1--shop.{DOMAIN}").as_str()]);
let mut names = c.host_names().await;
names.sort();
assert_eq!(
names,
vec![
format!("fix-1--shop.{DOMAIN}"),
taken.clone(),
"www.example.test".into()
]
);
// An admin can still kill a preview; the scoped token was never needed for that.
let r = c
.admin(
"DELETE",
&format!("/api/v1/previews/fix-1--shop.{DOMAIN}"),
None,
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
assert!(
!c.host_names()
.await
.iter()
.any(|h| h.starts_with("fix-1--"))
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_preview_token_cannot_point_a_preview_at_this_machine_s_admin_ports() {
let c = Ctl::start("").await;
let control_port = c.api.port();
for upstream in [
// control itself, Caddy's admin API, anything on loopback outside the allowed range
format!("http://127.0.0.1:{control_port}"),
"http://127.0.0.1:2019".to_owned(),
"http://localhost:20001".to_owned(),
"http://[::1]:20001".to_owned(),
"http://0.0.0.0:20001".to_owned(),
"http://169.254.169.254:80".to_owned(),
// not in the allow list
"http://192.168.1.10:8080".to_owned(),
"http://other.internal:8080".to_owned(),
// not an upstream at all
"http://user:pw@10.0.0.5:8080".to_owned(),
"http://10.0.0.5:8080/path".to_owned(),
"file:///etc/passwd".to_owned(),
"".to_owned(),
] {
let r = c.open_preview("shop", "main", &upstream).await;
assert!(
r.status == 422 || r.status == 403,
"{upstream}: {} {}",
r.status,
r.text
);
assert!(
r.json["error"]["code"].as_str().is_some_and(
|c| c.starts_with("preview.upstream") || c.starts_with("host.upstream")
),
"{upstream}: {}",
r.text
);
}
assert!(c.host_names().await.is_empty());
// Allowed: the private range, the loopback port range, the listed name.
for (b, u) in [
("a", "http://10.1.2.3:8080"),
("b", "http://127.0.0.1:20001"),
("c", "http://app.internal:3000"),
] {
let r = c.open_preview("shop", b, u).await;
assert_eq!(r.status, 202, "{u}: {}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_preview_lives_until_closed_or_expired() {
let c = Ctl::start("").await;
// Open, with a hostile branch name: the host is safe and the API says where it is.
let r = c
.open_preview(
"github:acme/Web.App",
"feature/Ünï ../../etc",
"http://10.0.0.5:8080",
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned();
assert!(host.ends_with(&format!(".{DOMAIN}")), "{host}");
assert!(host.split('.').next().unwrap().contains("--"));
assert_eq!(r.json["preview"]["url"], format!("https://{host}/"));
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
let r = c
.fabrica("GET", &format!("/api/v1/previews/{host}"), None)
.await;
assert_eq!(r.status, 200, "{}", r.text);
assert_eq!(r.json["preview"]["branch"], "feature/Ünï ../../etc");
assert_eq!(r.json["preview"]["state"], "live", "{}", r.text);
// A new deploy of the same branch moves the same host, it does not add one.
let r = c
.open_preview(
"github:acme/Web.App",
"feature/Ünï ../../etc",
"http://10.0.0.6:8080",
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(r.json["preview"]["hostname"], host.as_str());
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
let r = c.admin("GET", &format!("/api/v1/hosts/{host}"), None).await;
assert_eq!(r.json["host"]["upstreams"][0], "http://10.0.0.6:8080");
assert_eq!(c.host_names().await.len(), 1);
// Closed on merge, by project and branch.
let r = c
.fabrica(
"POST",
"/api/v1/previews/close",
Some(json!({"project": "github:acme/Web.App", "branch": "feature/Ünï ../../etc"})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
assert!(c.host_names().await.is_empty());
// Expired: removed by control by itself.
let r = c
.fabrica(
"POST",
"/api/v1/previews",
Some(json!({"project": "shop", "branch": "short", "upstream": "http://10.0.0.5:80", "ttl": 2})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
let t = Instant::now();
while !c.host_names().await.is_empty() {
assert!(
t.elapsed() < Duration::from_secs(30),
"the expired preview stayed"
);
tokio::time::sleep(Duration::from_millis(700)).await;
}
let r = c.admin("GET", "/api/v1/history", None).await;
assert!(r.text.contains("expired"), "{}", r.text);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn bad_preview_requests_are_refused_with_a_reason() {
let c = Ctl::start(
"max_ttl_secs = 86400
default_ttl_secs = 3600",
)
.await;
for (body, code) in [
(
json!({"project": "shop", "branch": "a\nb", "upstream": "http://10.0.0.5:80"}),
"preview.branch",
),
(
json!({"project": "shop", "branch": "", "upstream": "http://10.0.0.5:80"}),
"preview.branch",
),
(
json!({"project": "sh op", "branch": "main", "upstream": "http://10.0.0.5:80"}),
"preview.project",
),
(
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 0}),
"preview.ttl",
),
(
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 864000}),
"preview.ttl",
),
(
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "auth": "none"}),
"request.body_unknown_field",
),
] {
let r = c
.fabrica("POST", "/api/v1/previews", Some(body.clone()))
.await;
assert_eq!(r.json["error"]["code"], code, "{body}: {}", r.text);
assert!(r.status == 422 || r.status == 400, "{body}: {}", r.text);
}
assert!(c.host_names().await.is_empty());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn without_a_preview_domain_the_api_says_previews_are_off() {
let c = Ctl::start("").await;
// Replace the config with one that has no [previews] section, then restart.
drop(c);
let c2 = {
let dir = TempDir::new("pv-off");
std::fs::create_dir_all(dir.join("state")).unwrap();
let api = local(free_port());
let text = format!(
"listen = \"{api}\"\nstate_dir = \"{st}\"\n\n[routes]\nrepo = \"{repo}\"\n\n[edge]\nconfig = \"{d}/edge.json\"\nshare_revocations = \"{d}/rev.json\"\n\n[caddy]\nconfig = \"{d}/caddy.json\"\n\n[compile]\nhttp_listen = \"127.0.0.1:{h}\"\nhttps_listen = \"127.0.0.1:{hs}\"\ncert_dir = \"{d}\"\nstate_dir = \"{d}\"\naccess_log = \"{d}/a.log\"\ncaddy_credentials_dir = \"{d}\"\n",
st = s(&dir.join("state")),
repo = s(&dir.join("routes.git")),
d = s(dir.path()),
h = free_port(),
hs = free_port(),
);
std::fs::write(dir.join("control.toml"), text).unwrap();
let cfg = Config::load(&dir.join("control.toml")).unwrap();
let (_, tok) = Tokens::new(&dir.join("state"))
.create("fabrica", None, Scope::Previews)
.unwrap();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(ianitor_control::serve(cfg, async {
let _ = rx.await;
}));
assert!(wait_for_port(api, Duration::from_secs(20)));
(dir, api, tok, tx)
};
let auth = format!("Bearer {}", c2.2);
let r = tcp_json(
c2.1,
"POST",
"/api/v1/previews",
&[("Authorization", &auth)],
Some(&json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80"})),
)
.await
.unwrap();
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "preview.off");
let _ = c2.3.send(());
}
+8 -2
View File
@@ -27,7 +27,11 @@ fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() {
let d = TempDir::new("tok-race"); let d = TempDir::new("tok-race");
let server = Tokens::new(d.path()); let server = Tokens::new(d.path());
let values: Vec<_> = (0..150) let values: Vec<_> = (0..150)
.map(|i| server.create(&format!("t{i}"), None).unwrap()) .map(|i| {
server
.create(&format!("t{i}"), None, Default::default())
.unwrap()
})
.collect(); .collect();
let victim = values[75].0.id.clone(); let victim = values[75].0.id.clone();
let mut cli = std::process::Command::new(bin) let mut cli = std::process::Command::new(bin)
@@ -77,7 +81,9 @@ fn concurrent_creates_from_the_cli_and_the_server_all_survive() {
}) })
.collect(); .collect();
for i in 0..40 { for i in 0..40 {
server.create(&format!("srv{i}"), None).unwrap(); server
.create(&format!("srv{i}"), None, Default::default())
.unwrap();
} }
for c in &mut clis { for c in &mut clis {
assert!(c.wait().unwrap().success()); assert!(c.wait().unwrap().success());
+1 -3
View File
@@ -16,9 +16,7 @@ url.workspace = true
ring.workspace = true ring.workspace = true
base64.workspace = true base64.workspace = true
unicode-normalization = "0.1.24" unicode-normalization = "0.1.24"
rcgen = { workspace = true, features = ["x509-parser"] } domi-pki.workspace = true
x509-parser = { version = "0.18", features = ["verify"] }
time = { version = "0.3", default-features = false }
[dev-dependencies] [dev-dependencies]
rustls-pki-types.workspace = true rustls-pki-types.workspace = true
+19 -2
View File
@@ -109,9 +109,13 @@ fn check_options(o: &CompileOptions) -> Result<(), CompileError> {
Ok(()) Ok(())
} }
/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders. /// Paths end up inside JSON strings and Caddy `{file.*}` placeholders. Absolute: `/…` on
/// Linux, or a drive path with forward slashes on Windows (`C:/ProgramData/Ianitor/…`, which
/// Caddy and Go read as is; control writes backslashes as `/`, see [`windows_path`]).
fn check_path(p: &str) -> Result<(), &'static str> { fn check_path(p: &str) -> Result<(), &'static str> {
if !p.starts_with('/') { let drive =
p.len() >= 3 && p.as_bytes()[0].is_ascii_alphabetic() && &p.as_bytes()[1..3] == b":/";
if !p.starts_with('/') && !drive {
return Err("it must be an absolute path"); return Err("it must be an absolute path");
} }
if p.len() > 1024 { if p.len() > 1024 {
@@ -126,6 +130,19 @@ fn check_path(p: &str) -> Result<(), &'static str> {
Ok(()) Ok(())
} }
/// A Windows path as the compilers take it: `C:\ProgramData\Ianitor` → `C:/ProgramData/Ianitor`.
/// Anything that is not a drive path is returned unchanged (and a Linux path with a backslash
/// is still refused by the option check).
pub fn windows_path(p: &str) -> String {
let b = p.as_bytes();
if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/')
{
p.replace('\\', "/")
} else {
p.to_owned()
}
}
/// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then /// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then
/// any other configured copy header (case-insensitive, no duplicates). /// any other configured copy header (case-insensitive, no duplicates).
fn strip_headers(fa: &crate::ForwardAuth) -> Vec<String> { fn strip_headers(fa: &crate::ForwardAuth) -> Vec<String> {
+6 -1
View File
@@ -178,6 +178,8 @@ pub enum ValidationError {
BadForwardAuth { file: String, reason: &'static str }, BadForwardAuth { file: String, reason: &'static str },
#[error("{file}: acme is not usable: {reason}")] #[error("{file}: acme is not usable: {reason}")]
BadAcme { file: String, reason: &'static str }, BadAcme { file: String, reason: &'static str },
#[error("{file}: the preview is not usable: {reason}")]
BadPreview { file: String, reason: String },
} }
fn line_suffix(line: Option<usize>) -> String { fn line_suffix(line: Option<usize>) -> String {
@@ -217,7 +219,8 @@ impl ValidationError {
| E::ForwardAuthNotConfigured { file } | E::ForwardAuthNotConfigured { file }
| E::ProofWithoutSignIn { file } | E::ProofWithoutSignIn { file }
| E::BadForwardAuth { file, .. } | E::BadForwardAuth { file, .. }
| E::BadAcme { file, .. } => file, | E::BadAcme { file, .. }
| E::BadPreview { file, .. } => file,
E::DuplicateHostname { second, .. } => second, E::DuplicateHostname { second, .. } => second,
} }
} }
@@ -304,6 +307,7 @@ impl ValidationError {
E::ProofWithoutSignIn { .. } => "host.header.proof", E::ProofWithoutSignIn { .. } => "host.header.proof",
E::BadForwardAuth { .. } => "site.forward_auth", E::BadForwardAuth { .. } => "site.forward_auth",
E::BadAcme { .. } => "site.acme", E::BadAcme { .. } => "site.acme",
E::BadPreview { .. } => "host.preview",
} }
} }
@@ -338,6 +342,7 @@ impl ValidationError {
E::BadHealthCheck { .. } => Some("health_check.path".into()), E::BadHealthCheck { .. } => Some("health_check.path".into()),
E::ForwardAuthNotConfigured { .. } => Some("auth".into()), E::ForwardAuthNotConfigured { .. } => Some("auth".into()),
E::ProofWithoutSignIn { .. } => Some("auth".into()), E::ProofWithoutSignIn { .. } => Some("auth".into()),
E::BadPreview { .. } => Some("preview".into()),
_ => None, _ => None,
} }
} }
+2 -1
View File
@@ -13,6 +13,7 @@ pub mod edge_config;
mod error; mod error;
mod model; mod model;
pub mod pki; pub mod pki;
pub mod preview;
pub mod routes; pub mod routes;
pub mod share; pub mod share;
pub mod time; pub mod time;
@@ -22,7 +23,7 @@ pub use error::{ValidationError, ValidationErrors};
pub use model::{ pub use model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES, HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES,
MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, MAX_UPSTREAMS, Model, Preview, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream,
UpstreamHost, UpstreamHost,
}; };
pub use validate::{SourceFile, load}; pub use validate::{SourceFile, load};
+14
View File
@@ -173,6 +173,20 @@ pub struct Host {
pub access_log: AccessLog, pub access_log: AccessLog,
/// Visitors must present a Domi device certificate (mTLS) that is on the allow list. /// Visitors must present a Domi device certificate (mTLS) that is on the allow list.
pub device_certs: bool, pub device_certs: bool,
/// Set when this host is a branch preview (see [`crate::preview`]). Control uses it; the
/// compilers never read it.
pub preview: Option<Preview>,
}
/// The `[preview]` table of a preview host: which branch of which project it shows, and
/// until when. Its host name's first label is always `preview::label(project, branch)`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Preview {
pub project: String,
pub branch: String,
/// Unix seconds; control removes the host after this.
pub expires_at: u64,
} }
/// The forward-auth endpoint (Authelia's `/api/authz/forward-auth`). /// The forward-auth endpoint (Authelia's `/api/authz/forward-auth`).
+66 -553
View File
@@ -2,8 +2,10 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this // License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The Domi CA (ROADMAP §1.1, §1.2, §1.8, §3): a small CA on rcgen. Pure: the caller passes //! The Domi CA (ROADMAP §1.1, §1.2, §1.8, §3), as Ianitor uses it. The CA itself lives in the
//! the time in and does every file read and write. Keys are ECDSA P-256 everywhere. //! shared crate `domi-pki` (Fabrica `docs/32_coherence.md`, T3a); this module is Ianitor's view of
//! it with Ianitor's names and messages, plus Ianitor's encrypted-key format. Pure: the caller
//! passes the time in and does every file read and write. Keys are ECDSA P-256 everywhere.
//! //!
//! ```text //! ```text
//! Domi PKI Root 10 years, pathLen 1 created offline, never on the server //! Domi PKI Root 10 years, pathLen 1 created offline, never on the server
@@ -22,41 +24,22 @@
//! - No certificate is ever issued past its issuer's `notAfter`. //! - No certificate is ever issued past its issuer's `notAfter`.
//! //!
//! The intermediate is never made from what a CSR asks for: only its public key and its //! The intermediate is never made from what a CSR asks for: only its public key and its
//! subject CN are taken; every extension comes from the profile here. //! subject CN are taken; every extension comes from the profile in `domi-pki`.
use std::fmt;
use base64::Engine as _; use base64::Engine as _;
use base64::engine::general_purpose::STANDARD; use base64::engine::general_purpose::STANDARD;
use rcgen::{
BasicConstraints, CertificateParams, CertificateSigningRequestParams, DistinguishedName,
DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyUsagePurpose, PKCS_ECDSA_P256_SHA256,
SerialNumber,
};
use ring::rand::{SecureRandom, SystemRandom}; use ring::rand::{SecureRandom, SystemRandom};
use time::OffsetDateTime;
/// Root: about 10 years. pub use domi_pki::{
pub const ROOT_DAYS: u32 = 3653; CertInfo, DEVICE_DAYS, EkuInfo, INTERMEDIATE_DAYS, INTERMEDIATE_OPENSSL_EXT, KeyPair,
/// Intermediate: about 1 year. KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem, match_code,
pub const INTERMEDIATE_DAYS: u32 = 365; openssl_sign_command, sha256_hex,
/// Server (tls = "domi") certificates. };
pub const SERVER_DAYS: u32 = 90;
/// Renew a server certificate when fewer than this many days are left.
pub const SERVER_RENEW_DAYS: u32 = 30;
/// Device (mTLS client) certificates.
pub const DEVICE_DAYS: u32 = 365;
/// Subject CN of the root.
pub const ROOT_CN: &str = "Domi PKI Root";
/// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this. /// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this.
pub const INTERMEDIATE_CN: &str = "Ianitor Domi Intermediate"; pub const INTERMEDIATE_CN: &str = domi_pki::IANITOR_INTERMEDIATE_CN;
/// Organisation on every certificate.
pub const ORG: &str = "Fabrica Domi";
/// PBKDF2-HMAC-SHA256 iterations for encrypted keys (OWASP 2023 figure). /// PBKDF2-HMAC-SHA256 iterations for encrypted keys (OWASP 2023 figure).
pub const KEY_KDF_ITERATIONS: u32 = 600_000; pub const KEY_KDF_ITERATIONS: u32 = 600_000;
/// Backdating of `notBefore`, for clocks that run a little late.
const BACKDATE_SECS: i64 = 300;
const DAY: i64 = 86_400;
// Split so that this file does not match the pre-commit hook itself. // Split so that this file does not match the pre-commit hook itself.
const ARMOR_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----"); const ARMOR_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----");
const ARMOR_END: &str = concat!("-----END IANITOR ENCRYPTED ", "PRIVATE KEY-----"); const ARMOR_END: &str = concat!("-----END IANITOR ENCRYPTED ", "PRIVATE KEY-----");
@@ -91,52 +74,27 @@ pub enum PkiError {
Build(String), Build(String),
} }
fn build(e: rcgen::Error) -> PkiError { impl From<domi_pki::PkiError> for PkiError {
PkiError::Build(e.to_string()) fn from(e: domi_pki::PkiError) -> PkiError {
use domi_pki::PkiError as D;
match e {
D::BadCertificate(s) => PkiError::BadCertificate(s),
D::BadCsr => PkiError::BadCsr,
D::CsrSubject => PkiError::CsrSubject,
D::BadKey | D::UnsupportedKey => PkiError::BadKey,
D::NotCa => PkiError::NotCa,
D::KeyMismatch => PkiError::KeyMismatch,
D::IssuerExpired => PkiError::IssuerExpired,
D::BadName(s) => PkiError::BadName(s),
D::Random => PkiError::Random,
D::Build(s) | D::Signer(s) => PkiError::Build(s),
other => PkiError::Build(other.to_string()),
} }
/// An ECDSA P-256 key pair. Never printed.
pub struct KeyPair(rcgen::KeyPair);
impl fmt::Debug for KeyPair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("KeyPair(…)")
}
}
impl KeyPair {
/// PKCS#8 PEM. Callers write it only to files with mode 0600 (or encrypt it).
pub fn serialize_pem(&self) -> String {
self.0.serialize_pem()
}
pub fn serialize_der(&self) -> Vec<u8> {
self.0.serialize_der()
}
pub fn from_pem(pem: &str) -> Result<KeyPair, PkiError> {
rcgen::KeyPair::from_pem(pem)
.map(KeyPair)
.map_err(|_| PkiError::BadKey)
}
pub fn from_der(der: &[u8]) -> Result<KeyPair, PkiError> {
rcgen::KeyPair::try_from(der)
.map(KeyPair)
.map_err(|_| PkiError::BadKey)
}
/// SubjectPublicKeyInfo DER.
pub fn public_key_der(&self) -> Vec<u8> {
use rcgen::PublicKeyData as _;
self.0.subject_public_key_info()
} }
} }
pub fn generate_key() -> Result<KeyPair, PkiError> { pub fn generate_key() -> Result<KeyPair, PkiError> {
rcgen::KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256) Ok(domi_pki::generate_key()?)
.map(KeyPair)
.map_err(build)
} }
fn random<const N: usize>() -> Result<[u8; N], PkiError> { fn random<const N: usize>() -> Result<[u8; N], PkiError> {
@@ -147,50 +105,12 @@ fn random<const N: usize>() -> Result<[u8; N], PkiError> {
Ok(b) Ok(b)
} }
fn serial() -> Result<SerialNumber, PkiError> {
let mut b = random::<16>()?;
// Positive and never shortened by DER (leading byte 0x01..=0x7f).
b[0] = (b[0] & 0x7f) | 0x01;
Ok(SerialNumber::from_slice(&b))
}
fn time(unix: i64) -> Result<OffsetDateTime, PkiError> {
OffsetDateTime::from_unix_timestamp(unix).map_err(|e| PkiError::Build(e.to_string()))
}
fn dn(cn: &str) -> DistinguishedName {
let mut d = DistinguishedName::new();
d.push(DnType::CommonName, cn);
d.push(DnType::OrganizationName, ORG);
d
}
/// A certificate name a person typed: 1 to 64 printable characters, no control characters.
fn check_display_name(name: &str) -> Result<(), PkiError> {
let n = name.chars().count();
if n == 0 || n > 64 || name.chars().any(char::is_control) || name.trim() != name {
return Err(PkiError::BadName(
"use 1 to 64 visible characters, no leading or trailing spaces".into(),
));
}
Ok(())
}
// ------------------------------------------------------------------ root (offline) // ------------------------------------------------------------------ root (offline)
/// Create the root: a self-signed CA, `pathLenConstraint 1`, about 10 years. For the offline /// Create the root: a self-signed CA, `pathLenConstraint 1`, about 10 years. For the offline
/// machine only (`ianitor-control ca init`); control never calls this on the server. /// machine only (`ianitor-control ca init`); control never calls this on the server.
pub fn create_root(now: i64) -> Result<(String, KeyPair), PkiError> { pub fn create_root(now: i64) -> Result<(String, KeyPair), PkiError> {
let key = generate_key()?; Ok(domi_pki::create_root_local(now)?)
let mut p = CertificateParams::default();
p.distinguished_name = dn(ROOT_CN);
p.is_ca = IsCa::Ca(BasicConstraints::Constrained(1));
p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
p.not_before = time(now - BACKDATE_SECS)?;
p.not_after = time(now + i64::from(ROOT_DAYS) * DAY)?;
p.serial_number = Some(serial()?);
let cert = p.self_signed(&key.0).map_err(build)?;
Ok((cert.pem(), key))
} }
/// Common name of [`no_device_placeholder`]. /// Common name of [`no_device_placeholder`].
@@ -198,46 +118,15 @@ pub const NO_DEVICE_CN: &str = "Ianitor placeholder: no device is allowed";
/// The allow list's only entry while no device is enrolled. Caddy refuses to load an empty /// The allow list's only entry while no device is enrolled. Caddy refuses to load an empty
/// leaf list (and with it the whole config), so the list is never empty: this self-signed /// leaf list (and with it the whole config), so the list is never empty: this self-signed
/// certificate's key is dropped right here, so no client can ever present it, and it is not /// certificate's key is dropped right away, so no client can ever present it, and it is not
/// issued by the Domi intermediate, so edge refuses it too. /// issued by the Domi intermediate, so edge refuses it too.
pub fn no_device_placeholder(now: i64) -> Result<String, PkiError> { pub fn no_device_placeholder(now: i64) -> Result<String, PkiError> {
let key = generate_key()?; Ok(domi_pki::placeholder_leaf(NO_DEVICE_CN, now)?)
let mut p = CertificateParams::default();
p.distinguished_name = dn(NO_DEVICE_CN);
p.is_ca = IsCa::ExplicitNoCa;
p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
p.not_before = time(now - BACKDATE_SECS)?;
p.not_after = time(now + 100 * 365 * DAY)?;
p.serial_number = Some(serial()?);
let cert = p.self_signed(&key.0).map_err(build)?;
drop(key);
Ok(cert.pem())
} }
/// A CSR for a new intermediate key (made by control on the server). /// A CSR for a new intermediate key (made by control on the server).
pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> { pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> {
let mut p = CertificateParams::default(); Ok(domi_pki::intermediate_csr(key, cn)?)
p.distinguished_name = dn(cn);
p.serialize_request(&key.0)
.map_err(build)?
.pem()
.map_err(build)
}
/// The extensions for signing an intermediate with openssl on the offline machine (the
/// accepted manual step until Custos can sign, docs/pki.md): the same profile as
/// [`sign_intermediate`]. Use with `openssl x509 -req … -days 365 -extfile <this file>`.
pub const INTERMEDIATE_OPENSSL_EXT: &str = "basicConstraints = critical, CA:TRUE, pathlen:0\n\
keyUsage = critical, keyCertSign, cRLSign, digitalSignature\n\
subjectKeyIdentifier = hash\n\
authorityKeyIdentifier = keyid:always\n";
/// The openssl command that signs a renewal on the offline machine (files named after the
/// request). OpenSSL 3 picks a random serial.
pub fn openssl_sign_command(base: &str) -> String {
format!(
"openssl x509 -req -in {base}.csr -CA domi-root.crt -CAkey domi-root.key -days {INTERMEDIATE_DAYS} -sha256 -extfile {base}.ext -out {base}.crt"
)
} }
/// Sign an intermediate CSR with the root (offline, or in Custos once it can). Only the CSR's /// Sign an intermediate CSR with the root (offline, or in Custos once it can). Only the CSR's
@@ -248,349 +137,81 @@ pub fn sign_intermediate(
csr_pem: &str, csr_pem: &str,
now: i64, now: i64,
) -> Result<String, PkiError> { ) -> Result<String, PkiError> {
let root = inspect(root_cert_pem)?; Ok(domi_pki::sign_intermediate(
if !root.is_ca { root_cert_pem,
return Err(PkiError::NotCa); root_key,
} csr_pem,
if public_key_der(root_cert_pem)? != root_key.public_key_der() { INTERMEDIATE_CN,
return Err(PkiError::KeyMismatch); now,
} )?)
if now < root.not_before || now >= root.not_after {
return Err(PkiError::IssuerExpired);
}
let csr = CertificateSigningRequestParams::from_pem(csr_pem).map_err(|_| PkiError::BadCsr)?;
let cn = csr
.params
.distinguished_name
.get(&DnType::CommonName)
.and_then(dn_text)
.ok_or(PkiError::CsrSubject)?;
if !cn.starts_with(INTERMEDIATE_CN)
|| cn.chars().count() > 64
|| cn.chars().any(char::is_control)
{
return Err(PkiError::CsrSubject);
}
let mut p = CertificateParams::default();
p.distinguished_name = dn(&cn);
p.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
p.key_usages = vec![
KeyUsagePurpose::KeyCertSign,
KeyUsagePurpose::CrlSign,
KeyUsagePurpose::DigitalSignature,
];
p.not_before = time(now - BACKDATE_SECS)?;
p.not_after = time((now + i64::from(INTERMEDIATE_DAYS) * DAY).min(root.not_after))?;
p.serial_number = Some(serial()?);
p.use_authority_key_identifier_extension = true;
let fresh = CertificateSigningRequestParams {
params: p,
public_key: csr.public_key,
};
let issuer = Issuer::from_ca_cert_pem(root_cert_pem, &root_key.0).map_err(build)?;
Ok(fresh.signed_by(&issuer).map_err(build)?.pem())
}
fn dn_text(v: &rcgen::DnValue) -> Option<String> {
match v {
rcgen::DnValue::Utf8String(s) => Some(s.clone()),
rcgen::DnValue::PrintableString(s) => Some(s.as_str().to_owned()),
_ => None,
}
} }
// ------------------------------------------------------------------ the intermediate // ------------------------------------------------------------------ the intermediate
/// The intermediate as control holds it: its certificate and its key, checked to belong /// The intermediate as control holds it: its certificate and its key, checked to belong
/// together and to be a CA. /// together and to be a CA.
pub struct Intermediate { #[derive(Debug)]
cert_pem: String, pub struct Intermediate(domi_pki::Intermediate);
key: KeyPair,
info: CertInfo,
}
impl fmt::Debug for Intermediate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Intermediate")
.field("subject", &self.info.subject_cn)
.field("not_after", &self.info.not_after)
.finish()
}
}
impl Intermediate { impl Intermediate {
pub fn new(cert_pem: &str, key: KeyPair) -> Result<Intermediate, PkiError> { pub fn new(cert_pem: &str, key: KeyPair) -> Result<Intermediate, PkiError> {
let first = first_pem(cert_pem)?; Ok(Intermediate(domi_pki::Intermediate::new(cert_pem, key)?))
let info = inspect(&first)?;
if !info.is_ca {
return Err(PkiError::NotCa);
}
if public_key_der(&first)? != key.public_key_der() {
return Err(PkiError::KeyMismatch);
}
Ok(Intermediate {
cert_pem: first,
key,
info,
})
} }
pub fn cert_pem(&self) -> &str { pub fn cert_pem(&self) -> &str {
&self.cert_pem self.0.cert_pem()
} }
pub fn not_after(&self) -> i64 { pub fn not_after(&self) -> i64 {
self.info.not_after self.0.not_after()
} }
pub fn info(&self) -> &CertInfo { pub fn info(&self) -> &CertInfo {
&self.info self.0.info()
} }
pub fn key(&self) -> &KeyPair { pub fn key(&self) -> &KeyPair {
&self.key self.0.key()
} }
fn issue(&self, mut p: CertificateParams, days: u32, now: i64) -> Result<Issued, PkiError> { /// The shared crate's intermediate.
if now < self.info.not_before || now >= self.info.not_after { pub fn inner(&self) -> &domi_pki::Intermediate {
return Err(PkiError::IssuerExpired); &self.0
}
let key = generate_key()?;
p.is_ca = IsCa::ExplicitNoCa;
p.not_before = time(now - BACKDATE_SECS)?;
p.not_after = time((now + i64::from(days) * DAY).min(self.info.not_after))?;
p.serial_number = Some(serial()?);
p.use_authority_key_identifier_extension = true;
let issuer = Issuer::from_ca_cert_pem(&self.cert_pem, &self.key.0).map_err(build)?;
let cert = p.signed_by(&key.0, &issuer).map_err(build)?;
let cert_pem = cert.pem();
let info = inspect(&cert_pem)?;
Ok(Issued {
chain_pem: format!("{cert_pem}{}", self.cert_pem),
key_pem: key.serialize_pem(),
key,
serial_hex: info.serial_hex.clone(),
sha256_hex: info.sha256_hex.clone(),
not_before: info.not_before,
not_after: info.not_after,
cert_pem,
})
} }
} }
/// A freshly issued leaf. pub use domi_pki::Issued;
pub struct Issued {
/// The leaf alone.
pub cert_pem: String,
/// Leaf, then the intermediate (what a server or a device presents).
pub chain_pem: String,
/// PKCS#8 PEM of the leaf's key.
pub key_pem: String,
pub key: KeyPair,
pub serial_hex: String,
/// SHA-256 of the leaf's DER, lowercase hex.
pub sha256_hex: String,
pub not_before: i64,
pub not_after: i64,
}
impl fmt::Debug for Issued {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Issued")
.field("serial", &self.serial_hex)
.field("not_after", &self.not_after)
.finish()
}
}
/// A server certificate for one hostname (`tls = "domi"`). The hostname must already be /// A server certificate for one hostname (`tls = "domi"`). The hostname must already be
/// validated by the schema; it is checked again here. /// validated by the schema; it is checked again here.
pub fn issue_server(int: &Intermediate, hostname: &str, now: i64) -> Result<Issued, PkiError> { pub fn issue_server(int: &Intermediate, hostname: &str, now: i64) -> Result<Issued, PkiError> {
let mut p = CertificateParams::new(vec![hostname.to_owned()]) Ok(domi_pki::issue_server(&int.0, hostname, now)?)
.map_err(|e| PkiError::BadName(e.to_string()))?;
p.distinguished_name = dn(hostname);
p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
int.issue(p, SERVER_DAYS, now)
} }
/// A device certificate (mTLS client) for a named device. /// A device certificate (mTLS client) for a named device.
pub fn issue_device(int: &Intermediate, name: &str, now: i64) -> Result<Issued, PkiError> { pub fn issue_device(int: &Intermediate, name: &str, now: i64) -> Result<Issued, PkiError> {
check_display_name(name)?; Ok(domi_pki::issue_device(&int.0, name, now)?)
let mut p = CertificateParams::default();
let mut d = DistinguishedName::new();
d.push(DnType::CommonName, name);
d.push(DnType::OrganizationName, ORG);
d.push(DnType::OrganizationalUnitName, "Domi devices");
p.distinguished_name = d;
p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
int.issue(p, DEVICE_DAYS, now)
} }
// ------------------------------------------------------------------ reading certificates // ------------------------------------------------------------------ reading certificates
/// What Ianitor needs to know about a certificate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CertInfo {
pub subject_cn: String,
pub issuer_cn: String,
pub not_before: i64,
pub not_after: i64,
pub is_ca: bool,
pub path_len: Option<u32>,
pub dns_names: Vec<String>,
pub serial_hex: String,
pub sha256_hex: String,
/// keyUsage: `None` when the extension is absent.
pub key_usage: Option<KeyUsageInfo>,
/// extendedKeyUsage: `None` when the extension is absent (any use).
pub eku: Option<EkuInfo>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyUsageInfo {
pub key_cert_sign: bool,
pub crl_sign: bool,
pub digital_signature: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EkuInfo {
pub any: bool,
pub server_auth: bool,
pub client_auth: bool,
}
fn ders(pem: &str) -> Result<Vec<Vec<u8>>, PkiError> {
let mut out = Vec::new();
for p in x509_parser::pem::Pem::iter_from_buffer(pem.as_bytes()) {
let p = p.map_err(|e| PkiError::BadCertificate(e.to_string()))?;
if p.label != "CERTIFICATE" {
return Err(PkiError::BadCertificate(format!(
"unexpected PEM block {}",
p.label
)));
}
out.push(p.contents);
}
if out.is_empty() {
return Err(PkiError::BadCertificate("no certificate in it".into()));
}
Ok(out)
}
/// The DER of every certificate in a PEM chain, in order. /// The DER of every certificate in a PEM chain, in order.
pub fn chain_der(pem: &str) -> Result<Vec<Vec<u8>>, PkiError> { pub fn chain_der(pem: &str) -> Result<Vec<Vec<u8>>, PkiError> {
ders(pem) Ok(domi_pki::chain_der(pem)?)
} }
/// The first certificate of a PEM chain, as PEM. /// The first certificate of a PEM chain, as PEM.
pub fn first_pem(pem: &str) -> Result<String, PkiError> { pub fn first_pem(pem: &str) -> Result<String, PkiError> {
let first = ders(pem)? Ok(domi_pki::first_pem(pem)?)
.into_iter()
.next()
.ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?;
Ok(der_to_pem(&first))
}
pub fn der_to_pem(der: &[u8]) -> String {
let b = STANDARD.encode(der);
let mut s = String::from("-----BEGIN CERTIFICATE-----\n");
for chunk in b.as_bytes().chunks(64) {
s.push_str(&String::from_utf8_lossy(chunk));
s.push('\n');
}
s.push_str("-----END CERTIFICATE-----\n");
s
}
fn parse(der: &[u8]) -> Result<x509_parser::certificate::X509Certificate<'_>, PkiError> {
let (rest, c) = x509_parser::parse_x509_certificate(der)
.map_err(|e| PkiError::BadCertificate(e.to_string()))?;
if !rest.is_empty() {
return Err(PkiError::BadCertificate("trailing bytes".into()));
}
Ok(c)
}
fn cn_of(name: &x509_parser::x509::X509Name<'_>) -> String {
name.iter_common_name()
.next()
.and_then(|c| c.as_str().ok())
.unwrap_or_default()
.to_owned()
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
/// SHA-256 of a DER blob, lowercase hex.
pub fn sha256_hex(der: &[u8]) -> String {
hex(ring::digest::digest(&ring::digest::SHA256, der).as_ref())
} }
/// Read the first certificate of a PEM chain. /// Read the first certificate of a PEM chain.
pub fn inspect(pem: &str) -> Result<CertInfo, PkiError> { pub fn inspect(pem: &str) -> Result<CertInfo, PkiError> {
let der = ders(pem)? Ok(domi_pki::inspect(pem)?)
.into_iter()
.next()
.ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?;
inspect_der(&der)
} }
pub fn inspect_der(der: &[u8]) -> Result<CertInfo, PkiError> { pub fn inspect_der(der: &[u8]) -> Result<CertInfo, PkiError> {
let c = parse(der)?; Ok(domi_pki::inspect_der(der)?)
let bc = c
.basic_constraints()
.map_err(|e| PkiError::BadCertificate(e.to_string()))?;
let (is_ca, path_len) = match bc {
Some(b) => (b.value.ca, b.value.path_len_constraint),
None => (false, None),
};
let dns_names = match c
.subject_alternative_name()
.map_err(|e| PkiError::BadCertificate(e.to_string()))?
{
Some(san) => san
.value
.general_names
.iter()
.filter_map(|g| match g {
x509_parser::extensions::GeneralName::DNSName(n) => Some((*n).to_owned()),
_ => None,
})
.collect(),
None => Vec::new(),
};
Ok(CertInfo {
subject_cn: cn_of(c.subject()),
issuer_cn: cn_of(c.issuer()),
not_before: c.validity().not_before.timestamp(),
not_after: c.validity().not_after.timestamp(),
is_ca,
path_len,
dns_names,
serial_hex: hex(c.raw_serial()),
sha256_hex: sha256_hex(der),
key_usage: c
.key_usage()
.map_err(|e| PkiError::BadCertificate(e.to_string()))?
.map(|k| KeyUsageInfo {
key_cert_sign: k.value.key_cert_sign(),
crl_sign: k.value.crl_sign(),
digital_signature: k.value.digital_signature(),
}),
eku: c
.extended_key_usage()
.map_err(|e| PkiError::BadCertificate(e.to_string()))?
.map(|e| EkuInfo {
any: e.value.any,
server_auth: e.value.server_auth,
client_auth: e.value.client_auth,
}),
})
} }
/// Why a signed certificate cannot be the Domi intermediate, or `None` when it can. It must /// Why a signed certificate cannot be the Domi intermediate, or `None` when it can. It must
@@ -598,102 +219,28 @@ pub fn inspect_der(der: &[u8]) -> Result<CertInfo, PkiError> {
/// allowed to issue both server and device certificates (no extendedKeyUsage, or one that /// allowed to issue both server and device certificates (no extendedKeyUsage, or one that
/// allows both), valid now, and no longer than the root. /// allows both), valid now, and no longer than the root.
pub fn intermediate_problem(cert_pem: &str, root_pem: &str, now: i64) -> Option<&'static str> { pub fn intermediate_problem(cert_pem: &str, root_pem: &str, now: i64) -> Option<&'static str> {
let Ok(info) = inspect(cert_pem) else { domi_pki::intermediate_problem(cert_pem, root_pem, INTERMEDIATE_CN, now)
return Some("not_certificate");
};
let Ok(root) = inspect(root_pem) else {
return Some("not_root");
};
if !issued_by(cert_pem, root_pem).unwrap_or(false) {
return Some("not_root");
}
if !info.is_ca || info.path_len != Some(0) || !info.subject_cn.starts_with(INTERMEDIATE_CN) {
return Some("not_ca");
}
if !info
.key_usage
.is_some_and(|k| k.key_cert_sign && k.crl_sign)
{
return Some("not_ca");
}
if info
.eku
.is_some_and(|e| !e.any && !(e.server_auth && e.client_auth))
{
return Some("eku");
}
if info.not_before > now + 300
|| info.not_after <= now
|| info.not_after > root.not_after
|| info.not_before < root.not_before - 300
{
return Some("dates");
}
None
} }
/// SubjectPublicKeyInfo DER of the first certificate. /// SubjectPublicKeyInfo DER of the first certificate.
pub fn public_key_der(pem: &str) -> Result<Vec<u8>, PkiError> { pub fn public_key_der(pem: &str) -> Result<Vec<u8>, PkiError> {
let der = ders(pem)? Ok(domi_pki::public_key_der(pem)?)
.into_iter()
.next()
.ok_or_else(|| PkiError::BadCertificate("no certificate in it".into()))?;
let c = parse(&der)?;
Ok(c.public_key().raw.to_vec())
} }
/// Is `child` (first certificate) signed by the key of `issuer` (first certificate), and /// Is `child` (first certificate) signed by the key of `issuer` (first certificate), and
/// does its issuer name match? A CA flag on the issuer is required. /// does its issuer name match? A CA flag on the issuer is required.
pub fn issued_by(child_pem: &str, issuer_pem: &str) -> Result<bool, PkiError> { pub fn issued_by(child_pem: &str, issuer_pem: &str) -> Result<bool, PkiError> {
let cd = ders(child_pem)? Ok(domi_pki::issued_by(child_pem, issuer_pem)?)
.into_iter()
.next()
.ok_or(PkiError::BadCertificate(String::new()))?;
let id = ders(issuer_pem)?
.into_iter()
.next()
.ok_or(PkiError::BadCertificate(String::new()))?;
let child = parse(&cd)?;
let issuer = parse(&id)?;
let ca = matches!(issuer.basic_constraints(), Ok(Some(b)) if b.value.ca);
Ok(ca
&& child.issuer() == issuer.subject()
&& child.verify_signature(Some(issuer.public_key())).is_ok())
}
// ------------------------------------------------------------------ match codes
/// The code both screens show for one request: SHA-256 of the request, first three bytes,
/// each mod 100, as `47 19 83` (see docs/custos-ticket.md).
pub fn match_code(request: &[u8]) -> String {
let d = ring::digest::digest(&ring::digest::SHA256, request);
let b = d.as_ref();
format!(
"{:02} {:02} {:02}",
b.first().copied().unwrap_or(0) % 100,
b.get(1).copied().unwrap_or(0) % 100,
b.get(2).copied().unwrap_or(0) % 100
)
} }
/// SubjectPublicKeyInfo DER of a CSR (to match a signed certificate to its request). /// SubjectPublicKeyInfo DER of a CSR (to match a signed certificate to its request).
pub fn csr_public_key_der(csr_pem: &str) -> Result<Vec<u8>, PkiError> { pub fn csr_public_key_der(csr_pem: &str) -> Result<Vec<u8>, PkiError> {
use x509_parser::prelude::FromDer; Ok(domi_pki::csr_public_key_der(csr_pem)?)
let der = csr_der(csr_pem)?;
let (_, csr) = x509_parser::certification_request::X509CertificationRequest::from_der(&der)
.map_err(|_| PkiError::BadCsr)?;
Ok(csr.certification_request_info.subject_pki.raw.to_vec())
} }
/// DER of the first PEM block of a CSR (for the match code). /// DER of the first PEM block of a CSR (for the match code).
pub fn csr_der(csr_pem: &str) -> Result<Vec<u8>, PkiError> { pub fn csr_der(csr_pem: &str) -> Result<Vec<u8>, PkiError> {
for p in x509_parser::pem::Pem::iter_from_buffer(csr_pem.as_bytes()) { Ok(domi_pki::csr_der(csr_pem)?)
let p = p.map_err(|_| PkiError::BadCsr)?;
if p.label == "CERTIFICATE REQUEST" {
return Ok(p.contents);
}
}
Err(PkiError::BadCsr)
} }
// ------------------------------------------------------------------ encrypted keys // ------------------------------------------------------------------ encrypted keys
@@ -781,7 +328,7 @@ pub fn decrypt_key(sealed: &str, password: &[u8]) -> Result<KeyPair, PkiError> {
&mut data, &mut data,
) )
.map_err(|_| PkiError::WrongPassword)?; .map_err(|_| PkiError::WrongPassword)?;
KeyPair::from_der(plain) Ok(KeyPair::from_der(plain)?)
} }
// ------------------------------------------------------------------ for tests // ------------------------------------------------------------------ for tests
@@ -799,55 +346,21 @@ pub mod testing {
name: &str, name: &str,
now: i64, now: i64,
) -> Result<String, PkiError> { ) -> Result<String, PkiError> {
let leaf_key = generate_key()?; Ok(domi_pki::testing::sign_as(issuer_pem, key, name, now)?)
let mut p = CertificateParams::new(vec![name.to_owned()]).map_err(build)?;
p.distinguished_name = dn(name);
p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
p.not_before = time(now - BACKDATE_SECS)?;
p.not_after = time(now + 30 * DAY)?;
let issuer = Issuer::from_ca_cert_pem(&first_pem(issuer_pem)?, key.0).map_err(build)?;
Ok(p.signed_by(&leaf_key.0, &issuer).map_err(build)?.pem())
} }
/// A CA below the intermediate (which pathLen 0 forbids). /// A CA below the intermediate (which pathLen 0 forbids).
pub fn sub_ca(int: &Intermediate, key: &KeyPair, now: i64) -> Result<String, PkiError> { pub fn sub_ca(int: &Intermediate, key: &KeyPair, now: i64) -> Result<String, PkiError> {
let mut p = CertificateParams::default(); Ok(domi_pki::testing::sub_ca(int.inner(), key, now)?)
p.distinguished_name = dn("Sub CA");
p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
p.key_usages = vec![KeyUsagePurpose::KeyCertSign];
p.not_before = time(now - BACKDATE_SECS)?;
p.not_after = time(now + 30 * DAY)?;
let issuer = Issuer::from_ca_cert_pem(int.cert_pem(), &int.key.0).map_err(build)?;
Ok(p.signed_by(&key.0, &issuer).map_err(build)?.pem())
} }
/// A CSR that asks for far too much. /// A CSR that asks for far too much.
pub fn greedy_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> { pub fn greedy_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> {
let mut p = CertificateParams::new(vec!["www.example.com".to_owned()]).map_err(build)?; Ok(domi_pki::testing::greedy_csr(key, cn)?)
p.distinguished_name = dn(cn);
p.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
p.not_after = time(4_000_000_000)?;
p.serialize_request(&key.0)
.map_err(build)?
.pem()
.map_err(build)
} }
/// Flip one byte inside the CSR's signed part. /// Flip one byte inside the CSR's signed part.
pub fn tamper_csr(csr_pem: &str) -> String { pub fn tamper_csr(csr_pem: &str) -> String {
let Ok(mut der) = csr_der(csr_pem) else { domi_pki::testing::tamper_csr(csr_pem)
return csr_pem.to_owned();
};
if let Some(b) = der.get_mut(40) {
*b ^= 0x01;
}
let b = STANDARD.encode(der);
let mut s = String::from("-----BEGIN CERTIFICATE REQUEST-----\n");
for chunk in b.as_bytes().chunks(64) {
s.push_str(&String::from_utf8_lossy(chunk));
s.push('\n');
}
s.push_str("-----END CERTIFICATE REQUEST-----\n");
s
} }
} }
+149
View File
@@ -0,0 +1,149 @@
// 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/.
//! Branch previews (Fabrica docs/32_coherence.md, T4): every branch of a project gets the host
//! `<branch>--<project>.<preview domain>`. Branch and project names come from a git host and
//! are hostile input; this module turns them into one safe DNS label.
//!
//! The label is `<branch part>--<project part>`, at most 62 characters:
//! - each part is the name lowercased, with every run of other characters than `a-z0-9`
//! turned into one `-`, trimmed of dashes (the project part uses only the repository name,
//! the text after the last `/` or `:`);
//! - when that lost anything (case, a character, the owner, length) the part gets `-` and 6
//! hex digits of SHA-256 of the whole original name, so two names that would read the same
//! never share a host (`feature/login` and `feature-login`, `Main` and `main`);
//! - a branch part shorter than 3 characters is also suffixed, so `--` never lands in the
//! label's positions 3 and 4 (reserved for IDNA; Let's Encrypt refuses such labels).
//!
//! Parts never contain `--`, so the separator is unambiguous. Names that cannot be a git
//! branch or a Fabrica project (control characters, too long, empty) are refused, not mangled.
use std::fmt;
/// Longest branch name accepted, in bytes (git allows more; no real branch is near this).
pub const MAX_BRANCH_BYTES: usize = 255;
/// Longest project name accepted (Fabrica's `project` field).
pub const MAX_PROJECT_CHARS: usize = 128;
/// The branch part of the label is at most this long.
pub const BRANCH_PART: usize = 40;
/// The project part of the label is at most this long.
pub const PROJECT_PART: usize = 20;
const HASH_HEX: usize = 6;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PreviewError {
Branch(&'static str),
Project(&'static str),
Domain(String),
}
impl fmt::Display for PreviewError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PreviewError::Branch(r) => write!(f, "the branch name {r}"),
PreviewError::Project(r) => write!(f, "the project name {r}"),
PreviewError::Domain(r) => write!(f, "the preview host name is not usable: {r}"),
}
}
}
impl std::error::Error for PreviewError {}
fn check_branch(b: &str) -> Result<(), PreviewError> {
if b.is_empty() {
return Err(PreviewError::Branch("is empty"));
}
if b.len() > MAX_BRANCH_BYTES {
return Err(PreviewError::Branch("is longer than 255 bytes"));
}
if b.chars().any(char::is_control) {
return Err(PreviewError::Branch("contains a control character"));
}
Ok(())
}
fn check_project(p: &str) -> Result<(), PreviewError> {
if p.is_empty() || p.chars().count() > MAX_PROJECT_CHARS {
return Err(PreviewError::Project("must be 1 to 128 characters"));
}
if !p
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._/:-".contains(&c))
{
return Err(PreviewError::Project(
"may only use letters, digits, '.', '_', '/', ':' and '-'",
));
}
if repo_name(p).bytes().all(|c| !c.is_ascii_alphanumeric()) {
return Err(PreviewError::Project("has no repository name"));
}
Ok(())
}
/// The repository name: what follows the last `/` or `:` (`github:acme/web` → `web`).
fn repo_name(p: &str) -> &str {
p.rsplit(['/', ':']).next().unwrap_or(p)
}
/// Lowercase LDH with dash runs collapsed and trimmed.
fn slug(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_lowercase());
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
}
while out.ends_with('-') {
out.pop();
}
out
}
fn short_hash(s: &str) -> String {
let d = ring::digest::digest(&ring::digest::SHA256, s.as_bytes());
let mut h = String::with_capacity(HASH_HEX);
for b in d.as_ref().iter().take(HASH_HEX / 2) {
h.push_str(&format!("{b:02x}"));
}
h
}
/// `slug` cut to `max`, with the hash of `original` appended when the slug is not exactly
/// `shown` or is shorter than `min`.
fn part(shown: &str, original: &str, max: usize, min: usize) -> String {
let s = slug(shown);
if s == shown && s.len() <= max && s.len() >= min && original == shown {
return s;
}
let keep = max - HASH_HEX - 1;
let mut cut: String = s.chars().take(keep).collect();
while cut.ends_with('-') {
cut.pop();
}
let h = short_hash(original);
if cut.is_empty() {
h
} else {
format!("{cut}-{h}")
}
}
/// The DNS label of a branch's preview.
pub fn label(project: &str, branch: &str) -> Result<String, PreviewError> {
check_branch(branch)?;
check_project(project)?;
let b = part(branch, branch, BRANCH_PART, 3);
let p = part(repo_name(project), project, PROJECT_PART, 1);
Ok(format!("{b}--{p}"))
}
/// The preview's host name under `domain`, checked like any host name.
pub fn hostname(project: &str, branch: &str, domain: &str) -> Result<String, PreviewError> {
crate::validate::check_hostname(domain).map_err(|r| PreviewError::Domain(r.to_owned()))?;
let h = format!("{}.{domain}", label(project, branch)?);
crate::validate::check_hostname(&h).map_err(|r| PreviewError::Domain(r.to_owned()))?;
Ok(h)
}
+42 -1
View File
@@ -15,7 +15,7 @@ use crate::error::{ValidationError as E, ValidationErrors, reason as r};
use crate::model::{ use crate::model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model, HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model,
Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost, Preview, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost,
}; };
/// One route file handed in by the caller (core does no I/O). /// One route file handed in by the caller (core does no I/O).
@@ -129,6 +129,16 @@ struct RawHost {
request_headers: Vec<RawRule>, request_headers: Vec<RawRule>,
#[serde(default)] #[serde(default)]
response_headers: Vec<RawRule>, response_headers: Vec<RawRule>,
preview: Option<RawPreview>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPreview {
project: String,
branch: String,
/// Signed so that 0 and negative numbers get a typed error instead of a serde one.
expires_at: i64,
} }
// ------------------------------------------------------------------ entry point // ------------------------------------------------------------------ entry point
@@ -511,6 +521,36 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
errors.push(E::ProofWithoutSignIn { file: f() }); errors.push(E::ProofWithoutSignIn { file: f() });
} }
let preview = raw.preview.and_then(|p| {
let bad = |reason: String| E::BadPreview { file: f(), reason };
let expires_at = match u64::try_from(p.expires_at) {
Ok(e) if e > 0 => e,
_ => {
errors.push(bad("expires_at must be a time in Unix seconds".into()));
return None;
}
};
match crate::preview::label(&p.project, &p.branch) {
Ok(label) => {
if raw.hostname.split('.').next() != Some(label.as_str()) {
errors.push(bad(format!(
"the host name of this branch's preview must start with \"{label}.\""
)));
return None;
}
}
Err(e) => {
errors.push(bad(e.to_string()));
return None;
}
}
Some(Preview {
project: p.project,
branch: p.branch,
expires_at,
})
});
if errors.len() != before { if errors.len() != before {
return None; return None;
} }
@@ -533,6 +573,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
RawAccessLog::Off => AccessLog::Off, RawAccessLog::Off => AccessLog::Off,
RawAccessLog::Truncated => AccessLog::Truncated, RawAccessLog::Truncated => AccessLog::Truncated,
}, },
preview,
}) })
} }
+301
View File
@@ -0,0 +1,301 @@
// 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/.
//! Preview host names (T4, written before the code): `<branch>--<project>.<preview domain>`.
//! Branch and project names come from a git host and are hostile: every one must map to a
//! safe DNS label, two different branches must never share a host, and the preview table of
//! a host file must agree with its host name.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::BTreeMap;
use ianitor_core::preview::{self, PreviewError};
use ianitor_core::{SourceFile, load};
/// A label a public CA and every resolver accept: LDH, 1–63, no leading or trailing dash, and
/// no `--` in positions 3 and 4 (reserved for IDNA A-labels, refused by Let's Encrypt).
fn assert_safe_label(l: &str) {
assert!(!l.is_empty() && l.len() <= 63, "length of {l:?}");
assert!(
l.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-'),
"{l:?} is not lowercase LDH"
);
assert!(
!l.starts_with('-') && !l.ends_with('-'),
"{l:?} has an edge dash"
);
assert!(
l.get(2..4) != Some("--"),
"{l:?} has -- in positions 3 and 4"
);
}
#[test]
fn plain_names_stay_readable() {
assert_eq!(
preview::label("mnovak/Arca", "main").unwrap(),
"main--arca-4a93cc"
);
assert_eq!(preview::label("shop", "fix-42").unwrap(), "fix-42--shop");
assert_eq!(
preview::hostname("shop", "fix-42", "preview.example.org").unwrap(),
"fix-42--shop.preview.example.org"
);
}
#[test]
fn hostile_branch_names_map_to_safe_labels() {
let long = "a".repeat(250);
let dots = "x.".repeat(100);
let hostile: &[&str] = &[
"main",
"Main",
"feature/login",
"feature//login",
"feature.login",
"..",
"...hidden",
"v1.2.3",
"ab",
"xn",
"a",
"-",
"--",
"_",
"fix/ünïcødé",
"日本語のブランチ",
"emoji-🦊-branch",
"Ⅻ-roman",
"fi-ligature",
"\u{200b}zero-width",
"right-to-left-\u{202e}gnp.exe",
"has space and ~^:?*[",
"semi;colon&amp<script>",
"../../etc/passwd",
"%2e%2e%2f",
"CAPS_AND_UNDERSCORES",
&long,
&dots,
"xn--80ak6aa92e",
"a--b",
"end-",
"-start",
];
for b in hostile {
let l = preview::label("team/web-app", b).unwrap_or_else(|e| panic!("{b:?}: {e}"));
assert_safe_label(&l);
let host = preview::hostname("team/web-app", b, "preview.example.org").unwrap();
assert!(host.ends_with(".preview.example.org"));
// The host is a valid host-file name: core accepts a preview file for it.
let text = preview_file(&host, "team/web-app", b);
load_one(&host, &text).unwrap_or_else(|e| panic!("{b:?}: {e}"));
}
}
#[test]
fn different_branches_never_share_a_label() {
// Pairs a naive slug would merge.
let pairs = [
("feature/login", "feature-login"),
("feature.login", "feature-login"),
("Main", "main"),
("fix/ü", "fix/ö"),
("a/b", "a_b"),
("x", "X"),
];
for (a, b) in pairs {
assert_ne!(
preview::label("p", a).unwrap(),
preview::label("p", b).unwrap(),
"{a:?} and {b:?}"
);
}
// Long branches that differ only after the cut.
let a = format!("{}-one", "release".repeat(10));
let b = format!("{}-two", "release".repeat(10));
assert_ne!(
preview::label("p", &a).unwrap(),
preview::label("p", &b).unwrap()
);
// And a broad sweep: many similar names, all distinct.
let mut seen = BTreeMap::new();
for i in 0..2000 {
for b in [
format!("feature/{i}"),
format!("feature-{i}"),
format!("Feature/{i}"),
] {
let l = preview::label("p", &b).unwrap();
assert_safe_label(&l);
if let Some(prev) = seen.insert(l.clone(), b.clone()) {
panic!("{prev:?} and {b:?} both map to {l}");
}
}
}
}
#[test]
fn same_input_same_label() {
for b in ["main", "feature/ünï", "x".repeat(300).as_str()] {
if b.len() > preview::MAX_BRANCH_BYTES {
continue;
}
assert_eq!(
preview::label("p/q", b).unwrap(),
preview::label("p/q", b).unwrap()
);
}
}
#[test]
fn unusable_names_are_refused_not_mangled() {
let too_long = "b".repeat(preview::MAX_BRANCH_BYTES + 1);
let bad_branches = [
"",
"tab\there",
"with\nnewline",
"nul\0byte",
"bell\u{7}",
too_long.as_str(),
];
for b in bad_branches {
assert!(
matches!(preview::label("p", b), Err(PreviewError::Branch(_))),
"{b:?}"
);
}
let bad_projects = [
"",
"/",
"owner/",
"has space",
"semi;colon",
"ü/name",
&"p".repeat(129),
];
for p in bad_projects {
assert!(
matches!(preview::label(p, "main"), Err(PreviewError::Project(_))),
"{p:?}"
);
}
// A preview domain must be a hostname, and the whole name must fit DNS.
assert!(matches!(
preview::hostname("p", "main", "bad domain"),
Err(PreviewError::Domain(_))
));
let deep = format!("{}.example.org", "d".repeat(60) + &".d".repeat(90));
assert!(preview::hostname("p", "main", &deep).is_err());
}
#[test]
fn project_names_from_every_git_host_work() {
for p in [
"mnovak/Arca",
"github:acme/web",
"gitlab-work:group/sub/app",
"app",
"Org.Name/repo.js",
] {
let l = preview::label(p, "main").unwrap();
assert_safe_label(&l);
}
// Same repo name under two owners: different hosts.
assert_ne!(
preview::label("alice/app", "main").unwrap(),
preview::label("bob/app", "main").unwrap()
);
}
fn preview_file(host: &str, project: &str, branch: &str) -> String {
let mut t = toml::Table::new();
t.insert("hostname".into(), host.into());
t.insert(
"upstreams".into(),
toml::Value::Array(vec!["http://10.0.0.5:8080".into()]),
);
t.insert("tls".into(), "domi".into());
let mut p = toml::Table::new();
p.insert("project".into(), project.into());
p.insert("branch".into(), branch.into());
p.insert("expires_at".into(), toml::Value::Integer(1_900_000_000));
t.insert("preview".into(), toml::Value::Table(p));
toml::to_string(&t).unwrap()
}
fn load_one(host: &str, text: &str) -> Result<ianitor_core::Model, ianitor_core::ValidationErrors> {
let name = format!("hosts/{host}.toml");
load(
&SourceFile {
name: "ianitor.toml",
contents: "",
},
&[SourceFile {
name: &name,
contents: text,
}],
)
}
#[test]
fn the_model_carries_the_preview() {
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
let m = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
let p = m.hosts()[0].preview.as_ref().expect("a preview");
assert_eq!(
(p.project.as_str(), p.branch.as_str(), p.expires_at),
("shop", "fix-42", 1_900_000_000)
);
}
#[test]
fn a_preview_table_must_match_its_host_name() {
// A file cannot claim to be another branch's preview, or name a host its label does not.
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
let e = load_one(&host, &preview_file(&host, "shop", "other")).unwrap_err();
assert!(e.to_string().contains("preview"), "{e}");
let e = load_one(
"plain.pv.example.org",
&preview_file("plain.pv.example.org", "shop", "fix-42"),
)
.unwrap_err();
assert!(e.to_string().contains("preview"), "{e}");
// Unknown keys and bad values in the table are refused like everywhere else.
let text = preview_file(&host, "shop", "fix-42").replace("expires_at", "expires");
assert!(load_one(&host, &text).is_err());
let text = preview_file(&host, "shop", "fix-42").replace("1900000000", "0");
assert!(load_one(&host, &text).is_err());
}
#[test]
fn compilers_ignore_the_preview_table() {
// The preview metadata never reaches an engine: both outputs equal those of the same
// host without it.
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
let with = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
let text = preview_file(&host, "shop", "fix-42");
let without_text: String = text.split("[preview]").next().unwrap().to_owned();
let without = load_one(&host, &without_text).unwrap();
let o = ianitor_core::compile::CompileOptions {
http_listen: "0.0.0.0:80".parse().unwrap(),
https_listen: "0.0.0.0:443".parse().unwrap(),
cert_dir: "/var/lib/ianitor/certs".into(),
state_dir: "/var/lib/ianitor".into(),
access_log: "/var/log/ianitor/access.log".into(),
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
};
assert_eq!(
ianitor_core::compile::edge(&with, &o).unwrap(),
ianitor_core::compile::edge(&without, &o).unwrap()
);
assert_eq!(
ianitor_core::compile::caddy(&with, &o).unwrap(),
ianitor_core::compile::caddy(&without, &o).unwrap()
);
}
+9
View File
@@ -180,6 +180,15 @@ pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError>
Ok(server) Ok(server)
} }
/// For running edge inside a test process on Windows (the differential suite with Windows
/// paths, T4). Pingora on Windows stops only on Ctrl-C, so `stop` is ignored and the server
/// lives until the test process ends. Ianitor does not ship edge on Windows (Caddy mode).
#[cfg(windows)]
pub fn run_until(server: Server, stop: tokio::sync::oneshot::Receiver<()>) {
drop(stop);
server.run(pingora::server::RunArgs::default());
}
/// Run until `stop` resolves (or is dropped). For running edge inside a test process. /// Run until `stop` resolves (or is dropped). For running edge inside a test process.
#[cfg(unix)] #[cfg(unix)]
pub fn run_until(server: Server, stop: tokio::sync::oneshot::Receiver<()>) { pub fn run_until(server: Server, stop: tokio::sync::oneshot::Receiver<()>) {
+5
View File
@@ -391,6 +391,10 @@ impl ProxyHttp for EdgeProxy {
ctx: &mut Ctx, ctx: &mut Ctx,
) -> Result<()> { ) -> Result<()> {
let Some(host) = &ctx.host else { return Ok(()) }; let Some(host) = &ctx.host else { return Ok(()) };
// Response rules are for HTTP answers, not the switch to a websocket: Caddy leaves a
// `101` as the upstream sent it, and so does edge (found by the T4 preview fixture in
// the differential suite: `X-Robots-Tag` on a websocket upgrade).
if resp.status.as_u16() != 101 {
apply(&host.response_ops, |n, v| { apply(&host.response_ops, |n, v| {
match v { match v {
Some(v) => resp.insert_header(n.clone(), v.clone())?, Some(v) => resp.insert_header(n.clone(), v.clone())?,
@@ -400,6 +404,7 @@ impl ProxyHttp for EdgeProxy {
} }
Ok(()) Ok(())
})?; })?;
}
// Defence in depth: never hand a secret back to a client, even if the upstream echoes it. // Defence in depth: never hand a secret back to a client, even if the upstream echoes it.
if !host.secret_values.is_empty() { if !host.secret_values.is_empty() {
let leaking: Vec<http::HeaderName> = resp let leaking: Vec<http::HeaderName> = resp
+5 -1
View File
@@ -22,7 +22,11 @@ rustPlatform.buildRustPackage {
]; ];
}; };
cargoLock.lockFile = ../../Cargo.lock; cargoLock = {
lockFile = ../../Cargo.lock;
# domi-pki, the shared Domi CA (Cargo.toml pins tag v1.0.0): the NAR hash of its tree at that tag.
outputHashes."domi-pki-1.0.0" = "sha256-JdknFJ5cxsI1/MtWmvsItoE6f7znJjUr4C/rwUEz9i4=";
};
# libz-ng-sys (Pingora's compression) builds zlib-ng with CMake. # libz-ng-sys (Pingora's compression) builds zlib-ng with CMake.
nativeBuildInputs = [ cmake ]; nativeBuildInputs = [ cmake ];
dontUseCmakeConfigure = true; dontUseCmakeConfigure = true;
+41 -1
View File
@@ -145,11 +145,51 @@ 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 | 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. | | 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-17: The Domi CA moved to the shared crate domi-pki (Fabrica docs/32_coherence.md, T3a).**
- **Changed:** `crates/core/src/pki.rs` is now Ianitor's view of [domi-pki](https://gitea.marek-novak.cz/mnovak/domi-pki)
v1.0.0 (git tag in Cargo.toml): the same public API, the same error messages and the same encrypted-key format
(which stays here: it is Ianitor's storage). Fabrica issues Legatus agent certificates from the same crate under a
second intermediate. `deploy/nixos/package.nix` gets `cargoLock.outputHashes."domi-pki-1.0.0"` (the NAR hash of the
tag's tree, computed with a script checked against a known flake.lock narHash). core no longer depends on rcgen,
x509-parser and time directly.
- **Verified:** Rust on Windows only (WSL2 Debian has no disk: `E:\WSL\Debian\ext4.vhdx` is missing): core 103
(pki 15, unchanged tests), control 21, edge 31 and diff 2 (the Linux-only targets are skip stubs there), testkit 1:
the same counts as before the move.
- **Not verified:** `nix build .#ianitor`, `nix flake check`, the Linux-only Rust suites.
- **Deployed:** nothing.
- **Next step:** T4 (its own session) runs the Linux suites and the Nix build first.
**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.** **2026-11-08: Phase 3, web UI, PKI, NixOS.**
- **Changed:** - **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. - 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.
+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.
+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`);
+1
View File
@@ -15,6 +15,7 @@ tokio.workspace = true
serde_json.workspace = true serde_json.workspace = true
rustls.workspace = true rustls.workspace = true
rcgen.workspace = true rcgen.workspace = true
toml.workspace = true
[dev-dependencies] [dev-dependencies]
ianitor-control = { path = "../../crates/control" } ianitor-control = { path = "../../crates/control" }
+83 -5
View File
@@ -7,9 +7,12 @@
//! to Caddy (the `caddy` binary running the generated JSON); status, selected headers and //! to Caddy (the `caddy` binary running the generated JSON); status, selected headers and
//! body are compared. Everything listens on 127.0.0.1. //! body are compared. Everything listens on 127.0.0.1.
//! //!
//! It runs on Linux and on Windows. On Windows the paths in both configs are Windows paths
//! (`F:/…/certs/x.crt`, Caddy's `{file.F:/…/creds/api_key}`), which is what Windows Server's
//! Caddy mode serves from (T4); Pingora runs in-process there only as the reference.
//!
//! Test code: panics are failures. //! Test code: panics are failures.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::BTreeMap; use std::collections::BTreeMap;
@@ -50,6 +53,46 @@ fn host(name: &str, body: &str) -> (String, String) {
) )
} }
/// The preview domain of the fixtures, and two branch previews in it (T4): one with a plain
/// branch name, one with a hostile one (mapped to a hashed label).
pub const PREVIEW_DOMAIN: &str = "pv.test";
pub const PREVIEW_PLAIN: &str = "fix-42--shop.pv.test";
/// The host name of the hostile-branch preview.
pub fn preview_hostile() -> &'static str {
static H: std::sync::OnceLock<String> = std::sync::OnceLock::new();
H.get_or_init(|| {
ianitor_core::preview::hostname("github:acme/Web.App", "feature/Ünï ../x", PREVIEW_DOMAIN)
.expect("a preview host name")
})
}
/// A preview host file exactly as control writes it (`ianitor_control::previews::spec`).
fn preview_host(project: &str, branch: &str, upstream: &str) -> (String, String) {
let name = ianitor_core::preview::hostname(project, branch, PREVIEW_DOMAIN).unwrap();
let mut t = toml::Table::new();
t.insert("hostname".into(), name.clone().into());
t.insert(
"upstreams".into(),
toml::Value::Array(vec![upstream.into()]),
);
t.insert("tls".into(), "domi".into());
let mut rule = toml::Table::new();
rule.insert("action".into(), "set".into());
rule.insert("name".into(), "X-Robots-Tag".into());
rule.insert("value".into(), "noindex, nofollow".into());
t.insert(
"response_headers".into(),
toml::Value::Array(vec![toml::Value::Table(rule)]),
);
let mut p = toml::Table::new();
p.insert("project".into(), project.into());
p.insert("branch".into(), branch.into());
p.insert("expires_at".into(), toml::Value::Integer(4_000_000_000));
t.insert("preview".into(), toml::Value::Table(p));
(format!("hosts/{name}.toml"), toml::to_string(&t).unwrap())
}
impl Env { impl Env {
pub async fn start() -> Env { pub async fn start() -> Env {
let app = Echo::start("app").await; let app = Echo::start("app").await;
@@ -117,7 +160,15 @@ impl Env {
"device.test", "device.test",
&format!("upstreams = [\"{}\"]\ndevice_certs = true\n", app.url()), &format!("upstreams = [\"{}\"]\ndevice_certs = true\n", app.url()),
), ),
preview_host("shop", "fix-42", &app.url()),
preview_host("github:acme/Web.App", "feature/Ünï ../x", &ws.url()),
]; ];
assert!(
hosts
.iter()
.any(|(f, _)| f == &format!("hosts/{PREVIEW_PLAIN}.toml")),
"the plain preview fixture is {PREVIEW_PLAIN}"
);
let sources: Vec<SourceFile> = hosts let sources: Vec<SourceFile> = hosts
.iter() .iter()
.map(|(n, c)| SourceFile { .map(|(n, c)| SourceFile {
@@ -171,13 +222,16 @@ impl Env {
} }
pub fn options(&self, engine: &str) -> CompileOptions { pub fn options(&self, engine: &str) -> CompileOptions {
// On Windows these are drive paths (F:\\…), written with forward slashes as control
// writes them (`ianitor_core::compile::windows_path`).
let w = |p: String| compile::windows_path(&p);
CompileOptions { CompileOptions {
http_listen: local(free_port()), http_listen: local(free_port()),
https_listen: local(free_port()), https_listen: local(free_port()),
cert_dir: self.dir.str("certs"), cert_dir: w(self.dir.str("certs")),
state_dir: self.dir.str(&format!("state-{engine}")), state_dir: w(self.dir.str(&format!("state-{engine}"))),
access_log: self.dir.str(&format!("logs/{engine}-access.log")), access_log: w(self.dir.str(&format!("logs/{engine}-access.log"))),
caddy_credentials_dir: self.dir.str("creds"), caddy_credentials_dir: w(self.dir.str("creds")),
caddy_admin: None, caddy_admin: None,
caddy_admin_socket: None, caddy_admin_socket: None,
trusted_proxies: Vec::new(), trusted_proxies: Vec::new(),
@@ -445,6 +499,30 @@ pub fn corpus() -> Vec<Case> {
Req::get(p, "https://evil.test/x"), Req::get(p, "https://evil.test/x"),
), ),
http("HTTP redirects to HTTPS", Req::get(p, "/a/b?c=d")), http("HTTP redirects to HTTPS", Req::get(p, "/a/b?c=d")),
https(
"preview: plain branch",
PREVIEW_PLAIN,
Req::get(PREVIEW_PLAIN, "/a?b=c"),
),
http(
"preview: HTTP redirects to HTTPS",
Req::get(PREVIEW_PLAIN, "/x"),
),
https(
"preview: unknown branch of the preview domain",
PREVIEW_PLAIN,
Req::get("main--shop.pv.test", "/"),
),
https(
"preview: hostile branch",
preview_hostile(),
Req::get(preview_hostile(), "/"),
),
ws(
"preview: websocket on a hostile branch",
preview_hostile(),
vec![],
),
http("HTTP unknown host", Req::get("unknown.test", "/")), http("HTTP unknown host", Req::get("unknown.test", "/")),
http( http(
"HTTP unknown ACME token", "HTTP unknown ACME token",
+2 -11
View File
@@ -7,17 +7,8 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(not(unix))] // Runs on Linux and on Windows (with Windows paths; see the crate's docs).
#[test] mod both {
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
file!()
);
}
#[cfg(unix)]
mod unix {
use ianitor_diff::{ use ianitor_diff::{
Action, Env, break_caddy, break_edge, compile_pair, corpus, run_cases, run_corpus, settle, Action, Env, break_caddy, break_edge, compile_pair, corpus, run_cases, run_corpus, settle,
start_caddy, start_edge, start_caddy, start_edge,
+6 -1
View File
@@ -126,8 +126,13 @@ pub fn find_binary(name: &str) -> Option<PathBuf> {
return Some(PathBuf::from(p)); return Some(PathBuf::from(p));
} }
let path = std::env::var_os("PATH")?; let path = std::env::var_os("PATH")?;
let file = if cfg!(windows) {
format!("{name}.exe")
} else {
name.to_owned()
};
std::env::split_paths(&path) std::env::split_paths(&path)
.map(|d| d.join(name)) .map(|d| d.join(&file))
.find(|p| p.is_file()) .find(|p| p.is_file())
} }