Compare commits

..

31 Commits

Author SHA1 Message Date
mnovak a626c2559f [docs] ROADMAP: the v0.2.0 release run waits for Mark's Custos card 2026-11-19 02:22:16 +01:00
mnovak 7aa8b0ea62 [repo] Merge: feature/fabrica-onboarding (Fabrica: Ianitor onboarded, Aula page, e2e showcase, tests, 0.2.0, PR #11) 2026-11-19 01:57:11 +01:00
mnovak 805b4b8db5 [repo] Fabrica: the release sets PLAYWRIGHT_BROWSERS_PATH on F: for the videos' ffmpeg 2026-11-19 01:55:20 +01:00
mnovak ec4a0086b9 [web] E2E: the suite is type-checked with Node's types, apart from the UI's 2026-11-19 01:50:09 +01:00
mnovak 6c11acdc6d [repo] Release: 0.2.0 2026-11-19 01:38:54 +01:00
mnovak 82339f098f [repo] Fabrica: aula: true, the Aula page, the source archive, tests.yaml and the e2e pipeline 2026-11-19 01:37:46 +01:00
mnovak 76a56311cf [web] E2E: Playwright flows recorded and the Aula shots, on the demo control plane at a fixed instant 2026-11-19 01:36:02 +01:00
mnovak a212d5d421 [docs] Fabrica: the six onboarding items for Ianitor, the release's download and the Aula entry 2026-11-19 01:34:58 +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
mnovak 7322bbd856 [docs] Roadmap: Phase 3 status and handover 2026-11-08 12:57:24 +01:00
mnovak 0213021bb1 [control] Fix round 4: a device change during an engine switch is never skipped silently (devices_problem until the serving engine is told), and every switch ends by telling the engine that serves, also after going back 2026-11-08 12:48:57 +01:00
mnovak c45dafa2a3 [tests] Tests first, fix round 4: a revocation during a switch to Caddy, and during a failed switch away from Caddy, is in force when the switch ends (red) 2026-11-08 12:40:24 +01:00
mnovak 4d87537a76 [control] Fix round 3: revocations never wait for an apply (files and edge at once; under Caddy the reload is left to the end of a running trial), confirmed before the deadline is claimed, the guard marks a trial expired only after a verified load and retries, caddy-revert clears a stale deadline when Pingora serves 2026-11-08 12:28:35 +01:00
mnovak 09b8313a04 [tests] Tests first, fix round 3: a revocation during a watch is in force at once (Pingora) or when the apply ends (Caddy), a device revoked under Caddy is refused, caddy-revert with Pingora serving clears a stale deadline (red) 2026-11-08 12:21:36 +01:00
mnovak 057abbc954 [web] Design re-check: the engine chip closes its popover, Show details on every pause, popover grammar, share links off while Caddy serves, renewal copy 2026-11-08 12:04:14 +01:00
mnovak 457aea86ca [repo] NixOS and docs: ianitor-caddy-guard with caddy-fallback, caddy-revert after every control stop, admin socket only for control, Caddy trial deadline in the engine-switch VM test, trusted proxies stay off beside Caddy 2026-11-08 12:04:14 +01:00
mnovak 23a283ece9 [control] Fix round 2: Caddy rereads its files on every load and the served certificate is checked, Caddy trials get a deadline outside control (caddy-guard, caddy-revert), the watch under Caddy judges upstreams as edge does, a reload of Caddy during the watch is noticed and device changes wait for the apply, stricter root key scan, IPv4-mapped trusted proxies 2026-11-08 12:04:13 +01:00
mnovak ba3a060b2e [tests] Tests first, fix round 2: same caddy.json reload rereads certificates, forward-auth hosts kept under Caddy as under edge, crash mid-trial under Caddy, Caddy reloaded during the watch, watching crash point, caddy-revert after a crash, TLS 1.2 device after a bad ALPN (red) 2026-11-08 11:48:10 +01:00
mnovak 503916492d [web] Design review: last row's menu not clipped, Hostname focused after loading, popover closes on Esc and outside click, phone engine chip in the top bar, paused and needs-attention copy with Restore in the panel, change bar offers and countdown, focus after share and kept, fingerprint check when signing by hand, draft kept through sign-in 2026-11-08 11:21:44 +01:00
80 changed files with 4221 additions and 931 deletions
+2
View File
@@ -0,0 +1,2 @@
# Local Fabrica runs: records, logs and artifacts (Fabrica core docs/FORMATS.md)
runs/
+15
View File
@@ -0,0 +1,15 @@
# Ianitor Domi declares itself to Fabrica (Fabrica core docs/FORMATS.md, "Fabrica: the app"; docs/fabrica.md): 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, which is also how it updates. Its Aula page comes from the release of a `v*` tag
# (.fabrica/artifex/release.yaml), started on the hub for the pushed tag: no desktop part, as Ianitor has no installer
# to bump and tag. Fabrica's Apps screen shows one card: Deploy, then the Custos card. The colour is the murex accent
# (packages/ui/src/tokens.css, --accent).
name: Ianitor
icon: globe
color: "#e0a3dc"
aula: true
tagPrefix: v
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
+15
View File
@@ -0,0 +1,15 @@
# Ianitor Domi: the web UI's e2e suite on Fabrica's e2e runner (docs/fabrica.md part 6; Fabrica docs/20_tests.md,
# docs/31_runners_here.md): the built UI against the demo control plane, Playwright headless in the installed Edge,
# the records, traces and videos kept with the run. Manual: no push webhook reaches the hub yet. The e2e runner's
# runner.json sets PLAYWRIGHT_BROWSERS_PATH (Playwright's ffmpeg for the videos; on D: or F:, never C:).
name: e2e
on:
manual: true
runner: windows-e2e
steps:
- id: install
run: pnpm install --frozen-lockfile
- id: web
needs: [install]
run: fabrica tests run --target web
artifacts: [".fabrica/runs/tests/**"]
+66
View File
@@ -0,0 +1,66 @@
# Ianitor Domi: the Gitea release of a v* tag (docs/release.md, docs/fabrica.md). Ianitor ships no binary (the server
# builds it with Nix and the deploy pipeline switches it in), so a release is the source archive of the tag, its notes,
# the screenshots of the web UI and the Aula page, all 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>).
# The web UI's e2e suite (apps/web/playwright.config.ts) runs the main flows and takes the pictures in the installed
# Edge against the demo control plane with invented data, at a fixed instant; `fabrica aula shots` checks and copies
# them (.fabrica/aula.yaml, `file:` shots) and `fabrica aula page` builds the landing page from them and the brief.
# Playwright's ffmpeg (the flows' videos) is in PLAYWRIGHT_BROWSERS_PATH, set here so the step does not depend on the
# runner's environment: F:\ms-playwright on Mark's PC, never C:. Nothing is downloaded during a release; a runner
# without it fails the e2e step with Playwright's "Executable doesn't exist" naming the path.
name: release
on:
tag: "v*"
manual: true
runner: windows
env:
PLAYWRIGHT_BROWSERS_PATH: 'F:\ms-playwright'
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: e2e
needs: [check, test]
run: pnpm --filter web test:e2e
- id: pictures
needs: [e2e]
run: pnpm --filter web aula:shots
- id: source
needs: [version]
run: node scripts/pack-source.mjs ${{ version }}
artifacts: ["target/release/ianitor-*-src.tar.gz"]
- id: notes
run: fabrica notes
artifacts: ["target/notes/release-notes.md", "target/notes/release-notes.json"]
- id: shots
needs: [pictures]
run: fabrica aula shots
artifacts: ["target/aula/aula-*.png", "target/aula/aula.json"]
- id: page
needs: [notes, shots]
run: fabrica aula page
artifacts: ["target/aula/aula-page.json", "target/aula/aula-page.html"]
- id: approve
needs: [source, page]
approve: "Publish Ianitor ${{ tag }}: its source, notes and screenshots?"
- id: publish
needs: [approve]
publish:
gitea-release: true
files:
- "**/ianitor-*-src.tar.gz"
- "**/release-notes.md"
- "**/release-notes.json"
- "**/aula-*.png"
- "**/aula.json"
- "**/aula-page.json"
sums: domi-release
+26
View File
@@ -0,0 +1,26 @@
# Ianitor Domi's Aula page (docs/fabrica.md part 2, part 5; Fabrica docs/09_aula_pages.md, docs/19_web_shots.md).
# Every picture is taken by the web UI's own e2e suite (`pnpm --filter web aula:shots`, apps/web/e2e/specs/aula.spec.ts):
# the built UI in Edge against the demo control plane (apps/web/tests/demo.ts: hostnames under .test, addresses in the
# documentation ranges, people ada and felix), 1440 x 900, at a fixed instant in Europe/Prague. `fabrica aula shots`
# checks each file and publishes it as aula-<name>.png with aula.json; it starts no browser of its own.
shots:
- name: hosts
title: Every host, its health and where it sends traffic
section: Hosts
file: target/e2e/aula/hosts.png
- name: host
title: Editing a host
section: Hosts
file: target/e2e/aula/host.png
- name: engine
title: Pingora serving, Caddy ready as the fallback
section: Engines
file: target/e2e/aula/engine.png
- name: history
title: "History: going back to a kept version"
section: Changes
file: target/e2e/aula/history.png
- name: certificates
title: The Domi CA and the device certificates
section: Certificates
file: target/e2e/aula/certificates.png
+9
View File
@@ -0,0 +1,9 @@
A reverse proxy for a home server where every change is tried, watched and undone if it fails.
Each host says in plain words where its traffic goes, which certificate it uses and whether visitors sign in first. A change is checked, tried and watched for a minute, and goes back on its own if a host stops answering. Pingora serves, Caddy stands by built from the same routes, and a small Domi certificate authority issues the certificates for home-only hosts and devices.
- hosts: Every host with its health, its certificate and where it sends traffic.
- host: A host in plain words: upstreams, certificate, sign-in and health check.
- engine: Pingora serving, with Caddy built from the same routes and compared host by host.
- history: Every kept version in history, and exactly what restoring one would change.
- certificates: The Domi intermediate and the device certificates for phones, laptops and apps.
+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).
+13
View File
@@ -0,0 +1,13 @@
Ianitor 0.2.0 gives Ianitor its own page on Aula.
- **The Domi CA from the shared crate domi-pki.** Ianitor's certificate authority is now the shared crate domi-pki
1.0.0, which Fabrica also uses. It keeps the same certificates, messages and key format.
- **A page on Aula** with a short description, five captioned screenshots, these notes, and the source of the version
as its download. All of them are under a `SHA256SUMS` signed by domi-release.
- **Screenshots and videos from the tests.** The web UI's flows run in a real browser against an invented home
server at a fixed time: add a host, undo, restore, share a link, switch the engine and issue a device certificate.
Each flow is recorded. The same run takes the screenshots, so they are the same in every release.
- **Tested in Fabrica.** The flows are Fabrica's `web` test target and its `e2e` pipeline.
Updates stay a deploy. Fabrica's Deploy moves the server to the new commit and switches back if the health check
does not answer.
@@ -0,0 +1,15 @@
---
id: j4yav1
title: Turn on the visual gate against v0.2.0
status: todo
priority: normal
labels: [fabrica, release]
created: 2026-11-19T01:25:43+01:00
updated: 2026-11-19T01:25:43+01:00
doc: docs/fabrica.md
---
Add Fabrica's visual step (docs/28_visual.md part 6) to .fabrica/artifex/release.yaml after shots: fabrica visual compare --shots target/aula --out target/visual --before ${{ tag }} --forge https://gitea.marek-novak.cz/mnovak/ianitor, custos: [gitea-token], and approve needs visual. Waits one release because v0.1.0's shots were taken at a moving clock, so every shot would differ (docs/fabrica.md part 5).
## Log
- 2026-11-19T01:25:43+01:00 mnovak: created
@@ -0,0 +1,15 @@
---
id: jd3x1h
title: Publish the showcase videos on Aula
status: todo
priority: normal
labels: [fabrica, aula]
created: 2026-11-19T01:25:17+01:00
updated: 2026-11-19T01:25:17+01:00
doc: docs/fabrica.md
---
The e2e suite records each main flow as target/e2e/videos/<flow>.webm (docs/fabrica.md part 5). Once Fabrica's docs/37 (aula.yaml `videos:`) is on Fabrica main, list them in .fabrica/aula.yaml, add **/aula-*.webm to the release's publish files and to Aula's entry if needed, and check the limits (WebM, at most 8 MiB and 60 s each, at most 6).
## Log
- 2026-11-19T01:25:17+01:00 mnovak: created
+11
View File
@@ -0,0 +1,11 @@
# Ianitor Domi's Playwright tests (docs/fabrica.md part 6; Fabrica docs/20_tests.md): the web UI's main flows on the
# built UI and the demo control plane (apps/web/playwright.config.ts, project `web`), each recorded as a video.
# `fabrica tests run`, or Tests in the Fabrica app; the e2e pipeline (.fabrica/artifex/e2e.yaml) runs the same target
# on the e2e runner. No android target: Ianitor has no Android build. The Rust suites run in WSL2 and the Nix build.
dir: apps/web
gate: [web]
targets:
- name: web
kind: web
title: The web UI's main flows
project: web
+48
View File
@@ -0,0 +1,48 @@
# Ianitor Domi
*Ianitor* (Latin: the doorkeeper) is the reverse proxy of a home server. It decides which name goes to which
service, with which certificate, and who has to sign in first. Every change is tried before it stays.
- **Hosts in plain words.** Add a host, say where its traffic goes, and pick a Domi or Let's Encrypt certificate.
Choose whether visitors sign in first (Authelia forward-auth). Each host is checked for health and shows as
healthy, degraded or down.
- **Changes that undo themselves.** Every change is compiled, tried, and watched for 60 seconds. If a host stops
answering, the change 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.** Cloudflare's Pingora serves. Caddy is built from the same routes, compared with Pingora host by
host, and can take over at runtime in about two seconds.
- **The Domi certificate authority.** It issues certificates for hosts reached only from home, and device
certificates (mTLS) for phones, computers and Domi apps. They come from an intermediate whose root stays offline.
- **Share links**, signed and time-limited, for a single host.
- **Every action in three clicks or fewer**, in a dark web UI that only the signed-in owner reaches.
## For whom
For someone who runs services at home (a wiki, photos, music, cameras) and wants each one to have a name, a
certificate and a sign-in, without editing a proxy's config by hand and without a change that breaks the house.
## Installing
Ianitor runs on NixOS. There is nothing to download and run: the server builds it from source with Nix.
1. Add the flake `git+https://gitea.marek-novak.cz/mnovak/Ianitor.git` as an input of the server's flake, and
import its module `nixosModules.ianitor`.
2. Set `services.ianitor`: `enable`, the edge's listen addresses, the routes repository, the share-link key file
and, for the Domi CA, `pki`. Keys and passwords come from files the system provides (sops, systemd
credentials), never from the Nix store. Then rebuild.
3. Open the UI's name in a browser and sign in through Authelia.
Ianitor can run beside an existing Caddy first, taking over one host at a time. Updates are a deploy: the server's
flake input moves to the new commit and the system switches, and switches back if the health check does not answer.
## System requirements
- NixOS on x86_64 Linux, with ports 80 and 443 for the edge.
- Authelia for sign-in to the UI and to the hosts that ask for it.
- A git server for the routes repository (any that takes a push over HTTPS).
## The files on this page
`ianitor-<version>-src.tar.gz` is the source of this version: every file in the repository at its tag. The
server's Nix build is made from the same tree. It is listed in `SHA256SUMS`, which verifies with domi-release.
The screenshots show invented hosts on an invented home server.
+10 -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,15 @@ 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
pnpm --filter web test:e2e # the web UI's flows in Edge on demo data, recorded -> target/e2e/videos (docs/fabrica.md)
pnpm --filter web aula:shots # the Aula screenshots from the same suite -> target/e2e/aula; then `fabrica aula shots`
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 +36,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
+21 -8
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"
@@ -1289,7 +1304,7 @@ dependencies = [
[[package]] [[package]]
name = "ianitor-control" name = "ianitor-control"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"axum", "axum",
"base64 0.22.1", "base64 0.22.1",
@@ -1316,26 +1331,24 @@ dependencies = [
[[package]] [[package]]
name = "ianitor-core" name = "ianitor-core"
version = "0.1.0" version = "0.2.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]]
name = "ianitor-diff" name = "ianitor-diff"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"ianitor-control", "ianitor-control",
"ianitor-core", "ianitor-core",
@@ -1349,7 +1362,7 @@ dependencies = [
[[package]] [[package]]
name = "ianitor-edge" name = "ianitor-edge"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"async-trait", "async-trait",
@@ -1377,7 +1390,7 @@ dependencies = [
[[package]] [[package]]
name = "ianitor-testkit" name = "ianitor-testkit"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"bytes", "bytes",
"futures-util", "futures-util",
+3 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"] members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.2.0"
edition = "2024" edition = "2024"
rust-version = "1.89" rust-version = "1.89"
license = "MPL-2.0" license = "MPL-2.0"
@@ -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"
+6
View File
@@ -0,0 +1,6 @@
// 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 suite's instant: the demo's answers and the page's Date both read it (a Monday morning in Prague). */
export const CLOCK = "2026-11-16T09:30:00+01:00";
+64
View File
@@ -0,0 +1,64 @@
// 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/.
// What every e2e test gets: the demo started over, the page's clock at the suite's instant, `open`
// for a page of the UI, and afterwards a check that nothing the page showed looks real
// (tests/demo.ts realLooking: names outside .test, addresses outside the documentation ranges).
// A test with a `video` annotation has its recording kept as target/e2e/videos/<name>.webm.
import { mkdirSync } from "node:fs";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { test as base, expect, type Page } from "@playwright/test";
import { realLooking } from "../tests/demo";
import { CLOCK } from "./clock";
export const REPO = resolve(fileURLToPath(new URL(".", import.meta.url)), "../../..");
export const TARGET = join(REPO, "target", "e2e");
function url(): string {
const u = process.env.IANITOR_E2E_URL;
if (!u) throw new Error("IANITOR_E2E_URL is not set: run the suite through playwright.config.ts (its global setup serves the demo)");
return u;
}
/** Every text, field value and link the page shows (the body: the head's links are the build's own files). */
async function shown(page: Page): Promise<string[]> {
return page.evaluate(() => {
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.body.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("input, textarea").forEach((i) => out.push(i.value));
document.body.querySelectorAll("[href]").forEach((a) => out.push(a.getAttribute("href") ?? ""));
return out;
});
}
export const test = base.extend<{ open: (path: string) => Promise<void> }>({
open: async ({ page, request }, use) => {
const res = await request.post(`${url()}/__demo/reset`);
expect(res.status()).toBe(204);
await page.clock.setFixedTime(new Date(CLOCK));
await use(async (path: string) => {
await page.goto(url() + path);
});
},
});
test.afterEach(async ({ page }, info) => {
const video = info.annotations.find((a) => a.type === "video")?.description;
if (!page.isClosed()) {
const seen = (await shown(page)).flatMap(realLooking);
expect(seen, "the page showed something that looks real").toEqual([]);
}
const rec = page.video();
if (video && rec && info.status === info.expectedStatus) {
await page.close();
const dir = join(TARGET, "videos");
mkdirSync(dir, { recursive: true });
await rec.saveAs(join(dir, `${video}.webm`));
}
});
export { expect };
+113
View File
@@ -0,0 +1,113 @@
// 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 e2e suite's server (Playwright's global setup): builds the web UI (Vite, production) into a
// fresh temporary folder and serves it on 127.0.0.1 at a free port, with /api/v1 answered by the
// demo control plane (tests/demo.ts) at the suite's fixed instant. Any other path falls back to
// index.html, as in production. POST /__demo/reset starts the demo over (each test starts from the
// same invented server). The address reaches the tests as IANITOR_E2E_URL. Nothing here listens on
// anything but loopback, and the temporary folder is removed when the run ends.
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
import { createServer, type IncomingMessage, type Server } from "node:http";
import { tmpdir } from "node:os";
import { extname, join, normalize, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "vite";
import { demoApi } from "../tests/demo";
import { clock } from "../tests/mockApi";
import { CLOCK } from "./clock";
const web = resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
const TYPES: Record<string, string> = {
".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 body(req: IncomingMessage): Promise<Record<string, unknown>> {
return new Promise((ok) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
req.on("end", () => {
try {
ok(chunks.length ? (JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record<string, unknown>) : {});
} catch {
ok({});
}
});
});
}
function serve(dist: string): Promise<Server> {
const index = readFileSync(join(dist, "index.html"));
let api = demoApi();
const server = createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
if (url.pathname === "/__demo/reset" && req.method === "POST") {
api = demoApi();
res.writeHead(204).end();
return;
}
if (url.pathname === "/api/v1" || url.pathname.startsWith("/api/v1/")) {
void body(req).then((b) => {
const a = api(req.method ?? "GET", url.pathname.slice("/api/v1".length) + url.search, b);
res.writeHead(a.status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
res.end(a.text ?? undefined);
});
return;
}
let path: string;
try {
path = decodeURIComponent(url.pathname);
} catch {
res.writeHead(400).end();
return;
}
const file = normalize(join(dist, path));
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));
});
}
export default async function setup(): Promise<() => Promise<void>> {
clock.fixed = Date.parse(CLOCK);
const tmp = mkdtempSync(join(tmpdir(), "ianitor-e2e-"));
const remove = () => rmSync(tmp, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
let server: Server;
try {
const dist = join(tmp, "dist");
await build({ root: web, logLevel: "warn", build: { outDir: dist, emptyOutDir: true } });
server = await serve(dist);
} catch (e) {
remove();
throw e;
}
const addr = server.address();
if (!addr || typeof addr === "string") throw new Error("the demo server has no port");
process.env.IANITOR_E2E_URL = `http://127.0.0.1:${addr.port}`;
console.log(`e2e: the built UI and the demo control plane on ${process.env.IANITOR_E2E_URL}`);
return async () => {
server.closeAllConnections();
await new Promise<void>((r) => server.close(() => r()));
remove();
};
}
+28
View File
@@ -0,0 +1,28 @@
// 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): each shot of tests/demo.ts SHOTS, 1440 × 900 at
// scale 1, saved as target/e2e/aula/<name>.png. .fabrica/aula.yaml lists the same files, which
// `fabrica aula shots` checks and publishes as aula-<name>.png with aula.json.
import { mkdirSync } from "node:fs";
import { join } from "node:path";
import { SHOTS } from "../../tests/demo";
import { TARGET, expect, test } from "../fixtures";
const dir = join(TARGET, "aula");
for (const shot of SHOTS) {
test(`aula: ${shot.name}`, async ({ page, open }) => {
await open(shot.path);
for (const sel of shot.click ?? []) await page.locator(sel).first().click();
await expect(page.locator(shot.wait).first()).toBeAttached();
// Nothing still loading, the fonts in, two frames drawn and transitions over.
await expect(page.locator("[aria-busy=true]")).toHaveCount(0);
await page.evaluate(() => document.fonts.ready.then(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))));
await page.waitForTimeout(400);
mkdirSync(dir, { recursive: true });
await page.screenshot({ path: join(dir, `${shot.name}.png`), animations: "disabled", caret: "hide" });
});
}
+116
View File
@@ -0,0 +1,116 @@
// 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 main flows of ROADMAP §4 in a real browser, on the built UI and the demo control plane, with
// the clicks counted as in the smoke test (tests/flows.test.ts). Each is recorded: the showcase
// videos (docs/fabrica.md part 5) are target/e2e/videos/<name>.webm.
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../fixtures";
function counter() {
let n = 0;
return {
click: async (l: Locator) => {
n++;
await l.click();
},
get count() {
return n;
},
};
}
/** A beat for the viewer of the video, so a screen is seen before the next click. */
const beat = (page: Page) => page.waitForTimeout(700);
const nav = (page: Page) => page.getByRole("navigation", { name: "Main" }).first();
test("Add a host: + Host → fill → Apply = 2 clicks, kept", { annotation: { type: "video", description: "add-host" } }, async ({ page, open }) => {
const c = counter();
await open("/");
await expect(page.getByRole("button", { name: "More for wiki.home.test" })).toBeVisible();
await beat(page);
await c.click(page.getByRole("button", { name: "Add a host" }));
await page.getByLabel("Hostname").pressSequentially("notes.home.test");
await page.getByLabel("Send traffic to").fill("http://192.0.2.60:8080");
await beat(page);
await c.click(page.getByRole("button", { name: "Apply" }));
await expect(page.locator("dialog.ia-panel")).toHaveCount(0, { timeout: 10_000 });
await expect(page.getByRole("button", { name: "More for notes.home.test" })).toBeVisible();
await beat(page);
expect(c.count).toBe(2);
});
test("Undo the last change = 1 click", { annotation: { type: "video", description: "undo" } }, async ({ page, open }) => {
const c = counter();
await open("/");
const undo = page.getByRole("button", { name: /^Undo: Added recipes\.home\.test/ });
await expect(undo).toBeVisible();
await beat(page);
const sent = page.waitForRequest((r) => r.method() === "POST" && r.url().endsWith("/api/v1/undo"));
await c.click(undo);
expect((await sent).postDataJSON()).toMatchObject({ target_change_id: "ch_0008" });
await beat(page);
expect(c.count).toBe(1);
});
test("Restore: History → pick → Restore = 3 clicks", { annotation: { type: "video", description: "restore" } }, async ({ page, open }) => {
const c = counter();
await open("/");
await expect(page.getByRole("button", { name: "Add a host" })).toBeVisible();
await c.click(nav(page).getByRole("link", { name: "History" }));
await beat(page);
await c.click(page.getByRole("button", { name: /Turned share links on for wiki\.home\.test/ }));
await expect(page.getByRole("button", { name: "Restore this version" })).toBeVisible();
await beat(page);
const sent = page.waitForRequest((r) => r.method() === "POST" && r.url().endsWith("/api/v1/restore"));
await c.click(page.getByRole("button", { name: "Restore this version" }));
await sent;
await beat(page);
expect(c.count).toBe(3);
});
test("Share link: ⋯ → Share link → Copy = 3 clicks, 7 days", { annotation: { type: "video", description: "share-link" } }, async ({ page, context, open }) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
const c = counter();
await open("/");
await c.click(page.getByRole("button", { name: "More for wiki.home.test" }));
const minted = page.waitForRequest((r) => r.method() === "POST" && r.url().endsWith("/share-links"));
await c.click(page.getByRole("menuitem", { name: /Share link/ }));
expect((await minted).postDataJSON()).toMatchObject({ expires_in_s: 604800 });
const copy = page.getByRole("button", { name: "Copy link" });
await expect(copy).not.toHaveAttribute("aria-disabled", /.*/);
await beat(page);
await c.click(copy);
await expect(page.getByText("Copied")).toBeVisible();
await beat(page);
expect(c.count).toBe(3);
});
test("Switch engine: engine chip → Switch to Caddy = 2 clicks", { annotation: { type: "video", description: "engine" } }, async ({ page, open }) => {
const c = counter();
await open("/");
await c.click(page.getByRole("button", { name: /^Engine: Pingora/ }));
await expect(page.getByRole("button", { name: "Switch to Caddy" })).toBeVisible();
await beat(page);
await c.click(page.getByRole("button", { name: "Switch to Caddy" }));
await expect(page.getByText("Now serving with Caddy.")).toBeVisible({ timeout: 10_000 });
await beat(page);
expect(c.count).toBe(2);
});
test("Device certificate: Certificates → + Device → Issue = 3 clicks", { annotation: { type: "video", description: "device-certificate" } }, async ({ page, open }) => {
const c = counter();
await open("/");
await expect(page.getByRole("button", { name: "Add a host" })).toBeVisible();
await c.click(nav(page).getByRole("link", { name: "Certificates" }));
await beat(page);
await c.click(page.getByRole("button", { name: "Add a device certificate" }));
await page.getByLabel("Device name").fill("felix's tablet");
await c.click(page.getByRole("button", { name: "Issue" }));
await expect(page.getByLabel("Match code 47 19 83")).toBeVisible();
expect(c.count).toBe(3);
await expect(page.getByRole("button", { name: "Show QR code" })).toBeVisible({ timeout: 10_000 });
await beat(page);
});
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"types": ["node"],
"noEmit": true,
"allowImportingTsExtensions": false
},
"include": ["./**/*.ts", "../playwright.config.ts", "../tests/demo.ts", "../tests/mockApi.ts"]
}
+7 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "web", "name": "web",
"version": "0.1.0", "version": "0.2.0",
"private": true, "private": true,
"license": "MPL-2.0", "license": "MPL-2.0",
"description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.", "description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.",
@@ -8,17 +8,21 @@
"scripts": { "scripts": {
"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 && tsc -p e2e/tsconfig.json",
"test": "vitest run" "test": "vitest run",
"test:e2e": "playwright test --project=web",
"aula:shots": "playwright test --project=aula"
}, },
"dependencies": { "dependencies": {
"@ianitor/ui": "workspace:*" "@ianitor/ui": "workspace:*"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "1.56.1",
"@sveltejs/vite-plugin-svelte": "^5.0.3", "@sveltejs/vite-plugin-svelte": "^5.0.3",
"@testing-library/svelte": "^5.2.6", "@testing-library/svelte": "^5.2.6",
"@testing-library/user-event": "^14.6.1", "@testing-library/user-event": "^14.6.1",
"@tsconfig/svelte": "^5.0.4", "@tsconfig/svelte": "^5.0.4",
"@types/node": "^22.20.5",
"jsdom": "^26.0.0", "jsdom": "^26.0.0",
"svelte": "^5.20.0", "svelte": "^5.20.0",
"svelte-check": "^4.1.4", "svelte-check": "^4.1.4",
+51
View File
@@ -0,0 +1,51 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The web UI's end-to-end suite (docs/fabrica.md, part 5): the built UI in a real browser against
// the demo control plane (tests/demo.ts, invented data only), served on 127.0.0.1 by e2e/serve.ts.
// Two projects:
// web the main flows of ROADMAP §4, each recorded as a video (target/e2e/videos/<flow>.webm);
// Fabrica's `web` target (.fabrica/tests.yaml) and its e2e pipeline run this one.
// aula the release's screenshots (target/e2e/aula/<name>.png), which `fabrica aula shots` checks
// and publishes (.fabrica/aula.yaml, `file:` shots).
// Every page is drawn at a fixed instant in a fixed zone, so two takes of a screen are the same.
// On Windows the browser is the installed Edge (PW_CHANNEL names another, e.g. chrome): nothing is
// downloaded. Elsewhere it is Playwright's own Chromium. Videos need Playwright's ffmpeg, which lives
// in PLAYWRIGHT_BROWSERS_PATH (on F: on Mark's PC, never C:).
import { defineConfig, devices } from "@playwright/test";
const channel = process.env.PW_CHANNEL ?? (process.platform === "win32" ? "msedge" : undefined);
// Fabrica's live view (Fabrica docs/20_tests.md part 3): the port its Tests page watches.
const devtools = process.env.FABRICA_TESTS_DEVTOOLS ? [`--remote-debugging-port=${process.env.FABRICA_TESTS_DEVTOOLS}`] : [];
const desktop = {
...devices["Desktop Chrome"],
...(channel ? { channel } : {}),
viewport: { width: 1440, height: 900 },
deviceScaleFactor: 1,
locale: "en-GB",
timezoneId: "Europe/Prague",
launchOptions: { args: ["--lang=en-GB", ...devtools] },
};
export default defineConfig({
testDir: "e2e/specs",
outputDir: "../../target/e2e/results",
globalSetup: "./e2e/serve.ts",
fullyParallel: false,
workers: 1,
retries: 0,
forbidOnly: !!process.env.CI,
// Generous: the release PC runs several apps' suites at once, and a loaded PC types and draws slowly
// (one Edge start took 45 s there, one flow 72 s). A real hang still ends.
timeout: 180_000,
expect: { timeout: 15_000 },
reporter: [["list"]],
use: { trace: "retain-on-failure" },
projects: [
{ name: "web", testMatch: "flows.spec.ts", use: { ...desktop, video: { mode: "on", size: { width: 1440, height: 900 } } } },
{ name: "aula", testMatch: "aula.spec.ts", use: desktop },
],
});
+16 -2
View File
@@ -7,6 +7,8 @@
import { onMount } from "svelte"; import { onMount } from "svelte";
import { Button, Dialog, Icon } from "@ianitor/ui"; import { Button, Dialog, Icon } from "@ianitor/ui";
import type { IconName } from "@ianitor/ui"; import type { IconName } from "@ianitor/ui";
import EngineChip from "./components/EngineChip.svelte";
import EnginePopover from "./components/EnginePopover.svelte";
import TopBanners from "./components/TopBanners.svelte"; import TopBanners from "./components/TopBanners.svelte";
import { app, navigate, refresh, startPolling } from "./lib/app.svelte"; import { app, navigate, refresh, startPolling } from "./lib/app.svelte";
import { remembered } from "./lib/applies"; import { remembered } from "./lib/applies";
@@ -72,7 +74,12 @@
function signIn() { function signIn() {
const w = window.open("/signed-in", "ianitor-sign-in"); const w = window.open("/signed-in", "ianitor-sign-in");
if (!w) location.href = `/signed-in?back=${encodeURIComponent(app.path)}`; if (!w) {
// The new tab was blocked: this tab goes to the sign-in, so an open form is saved first
// (sessionStorage, this tab only) and comes back after it (§10).
window.dispatchEvent(new Event("ianitor:save-draft"));
location.href = `/signed-in?back=${encodeURIComponent(app.path)}`;
}
} }
async function signedInAgain() { async function signedInAgain() {
@@ -99,7 +106,7 @@
{#if app.overview?.site?.auth_logout_url}<a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a>{/if} {#if app.overview?.site?.auth_logout_url}<a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a>{/if}
</div> </div>
</nav> </nav>
<header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span></header> <header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span>{#if app.phone}<EngineChip />{/if}</header>
<main id="main" tabindex="-1"> <main id="main" tabindex="-1">
<TopBanners /> <TopBanners />
{#if route.view === "hosts"} {#if route.view === "hosts"}
@@ -121,6 +128,13 @@
</nav> </nav>
</div> </div>
{#if app.panel?.kind === "engine"}
<EnginePopover onclose={() => {
app.panel = null;
document.querySelector<HTMLElement>("[data-engine-chip]")?.focus();
}} />
{/if}
<div class="ia-toasts" role="status" aria-live="polite"> <div class="ia-toasts" role="status" aria-live="polite">
{#each app.toasts as t (t.id)}<div class="ia-toast"><Icon name="check" />{t.text}</div>{/each} {#each app.toasts as t (t.id)}<div class="ia-toast"><Icon name="check" />{t.text}</div>{/each}
</div> </div>
+34 -9
View File
@@ -4,10 +4,10 @@
<script lang="ts"> <script lang="ts">
// Handoff §7.4 and §7.5: the last-change bar with Undo (1 click), and the reverted / not // Handoff §7.4 and §7.5: the last-change bar with Undo (1 click), and the reverted / not
// applied banner that stands in for its first line. // applied banner that stands in for its first line.
import { Banner, Button, Icon, Progress } from "@ianitor/ui"; import { Banner, Button, Details, Icon, Progress } from "@ianitor/ui";
import { ApiError, call, del, newKey, post, sentence } from "../lib/api"; import { ApiError, call, del, newKey, post, sentence } from "../lib/api";
import { app, refresh, secondsLeft, toast } from "../lib/app.svelte"; import { app, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { firstSentence, when } from "../lib/format"; import { atTime, firstSentence, when } from "../lib/format";
import type { ApplyView } from "../lib/types"; import type { ApplyView } from "../lib/types";
let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props(); let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props();
@@ -21,7 +21,7 @@
let pushing = $state(false); let pushing = $state(false);
const dismissKey = $derived(last ? `apply:${last.id}` : ""); const dismissKey = $derived(last ? `apply:${last.id}` : "");
function runningHeading(summary: string, a: ApplyView | null): string { function runningHeading(summary: string, a: { kind: string; hosts: string[]; summary: string } | null): string {
if (!a) return summary; if (!a) return summary;
const h = a.hosts[0] ?? ""; const h = a.hosts[0] ?? "";
switch (a.kind) { switch (a.kind) {
@@ -29,6 +29,8 @@
case "remove": return `Removing ${h}`; case "remove": return `Removing ${h}`;
case "edit": return `Changing ${h}`; case "edit": return `Changing ${h}`;
case "share_links": return `Turning on share links for ${h}`; case "share_links": return `Turning on share links for ${h}`;
case "undo": return `Undoing: ${a.summary.replace(/^Undid: /, "")}`;
case "restore": return a.summary.replace(/^Restored /, "Restoring ");
default: return summary; default: return summary;
} }
} }
@@ -85,7 +87,29 @@
}); });
const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed"); const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed");
const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null); const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null);
const watchLeft = $derived(last?.watch ? secondsLeft(last.watch.ends_at) : null); // Ticks every second on the local clock (§7.2), not only on the 5 s poll.
const watchLeft = $derived(
active?.watch_ends_at ? secondsLeft(active.watch_ends_at) : active?.seconds_left != null ? active.seconds_left : null,
);
// The outcome's offer, by code (§7.5).
const offer = $derived.by(() => {
const c = last?.reason?.code ?? "";
if (/^apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
if (/^apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: last?.reason?.field ?? undefined };
if (/^apply\.failed\.(reload|build|edge_unreachable)$/.test(c)) return null;
if (last?.attempted_host) return { label: "Edit and try again", field: last?.reason?.field ?? undefined };
return null;
});
const pushLine = $derived.by(() => {
const p = last?.push;
const remote = "Gitea";
switch (p?.error_code) {
case "push.failed.rejected": return `Kept, but ${remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server.`;
case "push.failed.auth": return `Kept, but ${remote} refused Ianitor's access key. Check the key in Custos.`;
default: return `Kept, but not yet saved to ${remote}: ${remote} did not answer.${p?.next_try_at ? ` Ianitor tries again ${atTime(p.next_try_at, app.now)}.` : " Ianitor tries again by itself."}`;
}
});
const canPushNow = $derived(pushFailed && last?.push?.error_code !== "push.failed.rejected");
</script> </script>
{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)} {#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)}
@@ -93,8 +117,9 @@
<Banner tone="notice" ondismiss={() => (app.dismissed = [...app.dismissed, dismissKey])}> <Banner tone="notice" ondismiss={() => (app.dismissed = [...app.dismissed, dismissKey])}>
{#snippet title()}<span class="ia-status" data-s="reverted"><Icon name="undo" /><span class="word">{last.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet} {#snippet title()}<span class="ia-status" data-s="reverted"><Icon name="undo" /><span class="word">{last.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
{#if parts[1]}Reason: {parts[1]}{/if} {#if parts[1]}Reason: {parts[1]}{/if}
{#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")}<Details detail={last.reason.detail} />{/if}
{#snippet actions()} {#snippet actions()}
{#if last.attempted_host}<Button variant="outline" onclick={() => onedit(last, last.reason?.field ?? undefined)}>Edit and try again</Button>{/if} {#if offer}<Button variant="outline" onclick={() => onedit(last, offer?.field)}>{offer.label}</Button>{/if}
{/snippet} {/snippet}
</Banner> </Banner>
{/if} {/if}
@@ -104,8 +129,8 @@
{#if active} {#if active}
<div class="grow"> <div class="grow">
<div class="ia-status" data-s="running"><Icon name="clock" /><span class="word">{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"}</span> <div class="ia-status" data-s="running"><Icon name="clock" /><span class="word">{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"}</span>
<span>{runningHeading(active.summary, last && last.id === active.id ? last : null)}</span></div> <span>{runningHeading(active.summary, active.kind ? active : null)}</span></div>
<div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : `${watchLeft ?? active.seconds_left ?? 0} s left`}</div> <div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : active.state === "watching" ? `${watchLeft ?? 0} s left` : "Checking and loading the change"}</div>
{#if active.state === "watching" && watchLeft != null} {#if active.state === "watching" && watchLeft != null}
{@const total = o?.site?.watch_seconds ?? 60} {@const total = o?.site?.watch_seconds ?? 60}
<Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" /> <Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" />
@@ -116,7 +141,7 @@
<div class="grow"> <div class="grow">
{#if last.state === "kept"} {#if last.state === "kept"}
<div><span class="ia-status" data-s="kept"><Icon name="check" /><span class="word">kept</span></span> {last.summary}</div> <div><span class="ia-status" data-s="kept"><Icon name="check" /><span class="word">kept</span></span> {last.summary}</div>
<div class="ia-sub" class:warn={pushFailed}>{pushFailed ? "Kept, but not yet saved to Gitea. Ianitor tries again by itself." : keptLine}</div> <div class="ia-sub" class:warn={pushFailed}>{pushFailed ? pushLine : keptLine}</div>
{:else if undo?.target} {:else if undo?.target}
<div>Undo: {undo.target.summary}</div> <div>Undo: {undo.target.summary}</div>
{/if} {/if}
@@ -125,7 +150,7 @@
{#if undoReason}<div class="ia-sub" id="undo-reason">{undoReason}</div>{/if} {#if undoReason}<div class="ia-sub" id="undo-reason">{undoReason}</div>{/if}
{#if !undo?.target}<div class="ia-sub">Nothing to undo yet.</div>{/if} {#if !undo?.target}<div class="ia-sub">Nothing to undo yet.</div>{/if}
</div> </div>
{#if pushFailed}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if} {#if canPushNow}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if}
{#if undo?.target} {#if undo?.target}
<Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available} <Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available}
describedby={undoReason ? "undo-reason" : undefined} describedby={undoReason ? "undo-reason" : undefined}
+29
View File
@@ -0,0 +1,29 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §2.4: the engine chip (click 1 of the switch). On the main screen's header on a
// desktop, in the top bar on a phone (§2.16).
import { Icon } from "@ianitor/ui";
import { app } from "../lib/app.svelte";
const o = $derived(app.overview);
const engineName = $derived(o?.engine.running === "caddy" ? "Caddy" : "Pingora");
const engineLabel = $derived(
o?.engine.state === "switching" ? "Engine: switching" : `Engine: ${engineName}${o?.engine.state === "stopped" ? ", not answering" : ""}. Change engine`,
);
</script>
{#if o}
<button type="button" class="ia-engine" data-engine-chip aria-haspopup="dialog" aria-expanded={app.panel?.kind === "engine"} aria-label={engineLabel}
onclick={() => (app.panel = app.panel?.kind === "engine" ? null : { kind: "engine" })}>
{#if o.engine.state === "switching"}<Icon name="clock" /> Engine Switching…{:else}
<span class="ia-status" data-s={o.engine.state === "stopped" ? "down" : "healthy"}><span class="ia-dot"></span></span>
<small class="desktop">Engine</small> {engineName}{#if o.engine.running === "caddy"} <small>(fallback)</small>{/if}{/if}
<Icon name="chevron" />
</button>
{/if}
<style>
@media (max-width: 719.98px) { .desktop { display: none; } }
</style>
+25 -11
View File
@@ -4,11 +4,11 @@
<script lang="ts"> <script lang="ts">
// Handoff §9: the engine popover. Click 1 is the chip, click 2 "Switch to Caddy" (the popover // Handoff §9: the engine popover. Click 1 is the chip, click 2 "Switch to Caddy" (the popover
// is the confirmation). The switch runs in control; this polls GET /engine until it ends. // is the confirmation). The switch runs in control; this polls GET /engine until it ends.
import { onDestroy } from "svelte"; import { onDestroy, onMount } from "svelte";
import { Banner, Button, Dialog, Icon, Progress } from "@ianitor/ui"; import { Banner, Button, Details, Dialog, Icon, Progress } from "@ianitor/ui";
import { call, get, newKey, sentence } from "../lib/api"; import { call, get, newKey, sentence } from "../lib/api";
import { app, refresh } from "../lib/app.svelte"; import { app, refresh } from "../lib/app.svelte";
import { when } from "../lib/format"; import { whenInline } from "../lib/format";
import type { EngineView } from "../lib/types"; import type { EngineView } from "../lib/types";
let { onclose }: { onclose: () => void } = $props(); let { onclose }: { onclose: () => void } = $props();
@@ -23,7 +23,17 @@
let timer: ReturnType<typeof setTimeout> | undefined; let timer: ReturnType<typeof setTimeout> | undefined;
onDestroy(() => clearTimeout(timer)); onDestroy(() => clearTimeout(timer));
const activeLinks = $derived(app.overview?.hosts.filter((h) => h.share_links).length ?? 0); let activeLinks = $state(0);
onMount(async () => {
try {
const l = await get<{ items: { state: string }[] }>("/share-links", { quiet: true });
activeLinks = l.items.filter((x) => x.state === "active").length;
} catch {
/* the count is only a hint */
}
});
const fr = $derived(e?.fallback_ready ?? null);
const differs = $derived(fr ? fr.compared - fr.matched : 0);
const notReady = $derived(running === "pingora" && !e?.fallback_ready?.built_at); const notReady = $derived(running === "pingora" && !e?.fallback_ready?.built_at);
const disabledReason = $derived(!e?.switchable ? "This server does not let Ianitor switch engines." : notReady ? "Caddy is not ready: its settings have not been built yet." : null); const disabledReason = $derived(!e?.switchable ? "This server does not let Ianitor switch engines." : notReady ? "Caddy is not ready: its settings have not been built yet." : null);
@@ -62,17 +72,21 @@
} }
</script> </script>
<Dialog title="Serving with {name}" kind="popover" modal={false} {onclose}> <Dialog title={e?.state === "stopped" ? `${name} is not answering` : `Serving with ${name}`} kind="popover" modal={false} escape={!switching} toggle="[data-engine-chip]" {onclose}>
<p class="ia-label">Engine</p> <p class="ia-label">Engine</p>
{#if e?.state === "stopped"} {#if e?.state === "stopped"}
<p><strong>{name} is not answering.</strong> Visitors may not reach any host. Switching to {other} is the quickest way back.</p> <p>Visitors may not reach any host. Switching to {other} is the quickest way back.</p>
{:else} {:else}
<p class="ia-text2"> <p class="ia-text2">
{#if e?.since}Since {when(e.since, app.now)}. {/if} {#if e?.since}Since {whenInline(e.since, app.now)}. {/if}
{#if running === "pingora"} {#if running === "pingora"}
{#if notReady}Caddy is not ready: its settings have not been built yet.{:else}Caddy is ready with the same routes: built {when(e?.fallback_ready?.built_at, app.now)}{e?.fallback_ready?.current ? "" : " (it is rebuilt from the current routes when you switch)"}.{/if} {#if notReady}Caddy is not ready: its settings have not been built yet.{:else if differs > 0}Caddy was built {whenInline(fr?.built_at, app.now)} with the same routes, but {differs} of {fr?.compared} {fr?.compared === 1 ? "host" : "hosts"} {differs === 1 ? "behaves" : "behave"} differently on it.{:else}Caddy is ready with the same routes: built {whenInline(fr?.built_at, app.now)}{fr?.compared ? (fr.compared === 1 ? ", and the host behaves the same" : `, and all ${fr.compared} hosts behave the same`) : ""}.{/if}
{#if !notReady && !fr?.current} It is rebuilt from the current routes when you switch.{/if}
{:else}Pingora is ready with the same routes.{/if} {:else}Pingora is ready with the same routes.{/if}
</p> </p>
{#if running === "pingora" && !notReady && fr?.differences.length}
<Details detail={fr.differences.join("\n")} />
{/if}
{/if} {/if}
<div class="ia-card"> <div class="ia-card">
<p><strong>What happens</strong></p> <p><strong>What happens</strong></p>
@@ -81,10 +95,10 @@
<li>Open connections close; videos and uploads in progress restart.</li> <li>Open connections close; videos and uploads in progress restart.</li>
<li>Hosts and certificates stay the same.</li> <li>Hosts and certificates stay the same.</li>
{#if running === "pingora"} {#if running === "pingora"}
<li>Share links stop working while Caddy serves: visitors with a link get the normal sign-in. They work again when you switch back.{#if activeLinks} Hosts with share links: {activeLinks}.{/if}</li> <li>Share links stop working while Caddy serves: visitors with a link get the normal sign-in. They work again when you switch back.{#if activeLinks}{" "}{activeLinks === 1 ? "1 share link is" : `${activeLinks} share links are`} active.{/if}</li>
<li>Changes wait while Caddy serves; switch back to make them.</li> <li>Changes keep working: Ianitor tries each one on Caddy and undoes it if a host stops answering.</li>
{:else} {:else}
<li>Share links work again, and changes can be made again.</li> <li>Share links work again.</li>
{/if} {/if}
<li>This page may lose contact for a few seconds.</li> <li>This page may lose contact for a few seconds.</li>
</ul> </ul>
+2 -2
View File
@@ -89,7 +89,7 @@
} }
const blocked = $derived(changesBlocked()); const blocked = $derived(changesBlocked());
const shareReason = $derived(!app.overview?.site?.share_links_available ? (underCaddy ? "Share links are paused while Caddy serves." : "Share links are not set up on this server.") : null); const shareReason = $derived(!app.overview?.site?.share_links_available ? (underCaddy ? "Share links are off while Caddy serves." : "Share links are not set up on this server.") : null);
</script> </script>
<div class="ia-list" role="table" aria-label="Hosts"> <div class="ia-list" role="table" aria-label="Hosts">
@@ -111,7 +111,7 @@
<span class="ia-sub phone">{w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}</span> <span class="ia-sub phone">{w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}</span>
</span> </span>
<span role="cell" class="desktop"> <span role="cell" class="desktop">
<span>{h.upstreams[0] ?? ""}</span>{#if h.upstreams.length > 1} <span class="ia-muted">+{h.upstreams.length - 1} more</span>{/if} <span>{h.upstreams[0] ?? ""}</span>{#if h.upstreams.length > 1}{" "}<span class="ia-muted">+{h.upstreams.length - 1} more</span>{/if}
<span class="ia-sub" class:problem={s.problem} style="display:block">{running.includes(h.hostname) ? "Changing now · " : ""}{s.text}</span> <span class="ia-sub" class:problem={s.problem} style="display:block">{running.includes(h.hostname) ? "Changing now · " : ""}{s.text}</span>
{#if h.certificate.state === "pending"}<span class="ia-sub" style="display:block">Waiting for Let's Encrypt to issue the certificate.</span>{/if} {#if h.certificate.state === "pending"}<span class="ia-sub" style="display:block">Waiting for Let's Encrypt to issue the certificate.</span>{/if}
{#if h.certificate.state === "failed"} {#if h.certificate.state === "failed"}
+3 -1
View File
@@ -52,7 +52,9 @@
function pick(it: Item) { function pick(it: Item) {
if (it.reason) return; if (it.reason) return;
close(false); // Focus back on More first: a dialog the item opens returns focus there when it closes
// (§2.9), not to a menu item that no longer exists.
close(true);
it.run(); it.run();
} }
+46 -7
View File
@@ -8,7 +8,7 @@
import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui"; import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui";
import ApplyProgress from "./ApplyProgress.svelte"; import ApplyProgress from "./ApplyProgress.svelte";
import { ApiError, call, del, get, newKey, sentence } from "../lib/api"; import { ApiError, call, del, get, newKey, sentence } from "../lib/api";
import { app, changesBlocked, refresh, toast } from "../lib/app.svelte"; import { app, changesBlocked, refresh, restoreLastKept, toast } from "../lib/app.svelte";
import { FINAL, follow } from "../lib/applies"; import { FINAL, follow } from "../lib/applies";
import { firstSentence } from "../lib/format"; import { firstSentence } from "../lib/format";
import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types"; import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types";
@@ -62,6 +62,8 @@
// ---- the apply // ---- the apply
let apply = $state<ApplyView | null>(null); let apply = $state<ApplyView | null>(null);
let restoring = $state(false);
let restoreProblem = $state<string | null>(null);
let phase = $state<"form" | "progress">("form"); let phase = $state<"form" | "progress">("form");
let stop: (() => void) | undefined; let stop: (() => void) | undefined;
let closeTimer: ReturnType<typeof setTimeout> | undefined; let closeTimer: ReturnType<typeof setTimeout> | undefined;
@@ -128,16 +130,43 @@
rev = app.overview?.rev ?? null; rev = app.overview?.rev ?? null;
if (!signinOk) host.auth = "none"; if (!signinOk) host.auth = "none";
} }
loading = false; // A form saved before this tab went to sign in comes back (App.svelte, signIn).
if (focusField) { try {
if (focusField.startsWith("health_check")) more = true; const raw = sessionStorage.getItem(DRAFT);
setTimeout(() => document.getElementById(fieldId(focusField))?.focus(), 0); const d = raw ? (JSON.parse(raw) as { hostname: string; host: typeof host }) : null;
if (d && d.hostname === (hostname ?? "") && !resume) {
Object.assign(host, d.host);
more = more || d.host.hc || d.host.req.length > 0 || d.host.resp.length > 0;
}
sessionStorage.removeItem(DRAFT);
} catch {
/* no storage: nothing to bring back */
} }
loading = false;
if (phase === "form") {
// The Dialog focused its heading while this said "Loading…": now the first field
// (Hostname; Send traffic to when editing), so typing right after opening works.
const f = focusField ?? (hostname ? "upstreams[0]" : "hostname");
if (f.startsWith("health_check")) more = true;
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
}
window.addEventListener("ianitor:save-draft", saveDraft);
}); });
const DRAFT = "ianitor-draft";
function saveDraft() {
if (phase !== "form") return;
try {
sessionStorage.setItem(DRAFT, JSON.stringify({ hostname: hostname ?? "", host: $state.snapshot(host) }));
} catch {
/* no storage */
}
}
onDestroy(() => { onDestroy(() => {
stop?.(); stop?.();
clearTimeout(closeTimer); clearTimeout(closeTimer);
if (typeof window !== "undefined") window.removeEventListener("ianitor:save-draft", saveDraft);
}); });
function fieldId(f: string): string { function fieldId(f: string): string {
@@ -226,6 +255,7 @@
function onApply(a: ApplyView) { function onApply(a: ApplyView) {
apply = a; apply = a;
if (a.state === "kept") { if (a.state === "kept") {
if (a.kind !== "remove") app.focusHost = a.hosts[0] ?? null;
closeTimer = setTimeout(() => onclose(), 1500); closeTimer = setTimeout(() => onclose(), 1500);
} }
} }
@@ -291,6 +321,10 @@
return `Removing ${h}`; return `Removing ${h}`;
case "share_links": case "share_links":
return `Turning on share links for ${h}`; return `Turning on share links for ${h}`;
case "undo":
return `Undoing: ${apply.summary.replace(/^Undid: /, "")}`;
case "restore":
return apply.summary.replace(/^Restored /, "Restoring ");
default: default:
return `Changing ${h}`; return `Changing ${h}`;
} }
@@ -321,7 +355,7 @@
{#if apply.state === "kept"} {#if apply.state === "kept"}
<Banner tone="kept"> <Banner tone="kept">
{#snippet title()}<span class="ia-status" data-s="kept"><span class="word">kept</span></span> <strong>{apply?.hosts[0] ?? name}</strong> {apply?.kind === "remove" ? "is removed." : "is live."}{/snippet} {#snippet title()}<span class="ia-status" data-s="kept"><span class="word">kept</span></span> <strong>{apply?.hosts[0] ?? name}</strong> {apply?.kind === "remove" ? "is removed." : "is live."}{/snippet}
{apply.reason?.message ?? ""}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if} {(apply.reason?.message ?? "").replace(/^\S+ is (live|removed)\.\s*/, "")}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if}
</Banner> </Banner>
{:else if apply.state === "reverted" || apply.state === "failed"} {:else if apply.state === "reverted" || apply.state === "failed"}
{@const parts = firstSentence(apply.reason?.message ?? "")} {@const parts = firstSentence(apply.reason?.message ?? "")}
@@ -337,7 +371,12 @@
{#if apply.reason?.detail}<Details detail={apply.reason.detail} />{/if} {#if apply.reason?.detail}<Details detail={apply.reason.detail} />{/if}
<p class="ia-hint">Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.</p> <p class="ia-hint">Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.</p>
{:else if apply.state === "needs_attention"} {:else if apply.state === "needs_attention"}
<Banner tone="down" live="alert">{#snippet title()}<strong>Ianitor could not undo a failed change.</strong>{/snippet}{apply.reason?.message}</Banner> <Banner tone="down" live="alert">{#snippet title()}<strong>Ianitor could not undo a failed change.</strong>{/snippet}{apply.reason?.message}
{#if restoreProblem}<p role="status">{restoreProblem}</p>{/if}
{#snippet actions()}
{#if app.overview?.undo?.target}<Button variant="primary" pending={restoring} onclick={async () => { restoring = true; restoreProblem = await restoreLastKept(); restoring = false; }}>Restore the last kept version</Button>{/if}
{/snippet}
</Banner>
{/if} {/if}
{:else} {:else}
<form id="host-form" onsubmit={submit} novalidate> <form id="host-form" onsubmit={submit} novalidate>
@@ -46,8 +46,7 @@
{@const r = i.renewal} {@const r = i.renewal}
<Banner tone="notice" label="Domi intermediate certificate"> <Banner tone="notice" label="Domi intermediate certificate">
{#snippet title()} {#snippet title()}
<span tabindex="-1">Sign the renewal on the offline computer. Check that it shows the same code:</span> <span tabindex="-1">Sign the renewal on the offline computer. The next page has the files, the command and a fingerprint to check.</span>
<span class="code" aria-label="Match code {r.match_code}">{r.match_code}</span>
{/snippet} {/snippet}
The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if} The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if}
{#snippet actions()} {#snippet actions()}
@@ -58,12 +57,9 @@
{:else if i?.banner} {:else if i?.banner}
<Banner tone={i.state === "due" ? "notice" : "down"} label="Domi intermediate certificate"> <Banner tone={i.state === "due" ? "notice" : "down"} label="Domi intermediate certificate">
{#snippet title()}<strong>{i.banner?.message}</strong>{/snippet} {#snippet title()}<strong>{i.banner?.message}</strong>{/snippet}
{i.state === "missing" ? "Setting it up makes a request that the Domi root signs on the offline computer." : "Renewing makes a request that the Domi root signs; check the match code on both screens."} {i.state === "missing" ? "Setting it up makes a request that the Domi root signs on the offline computer." : "Renewing makes a request that the Domi root signs on the offline computer."}
{#if problem} {problem}{/if} {#if problem} {problem}{/if}
{#snippet actions()}<Button variant="outline" onclick={renew} {pending}>{i.state === "missing" ? "Set up" : "Renew"}</Button>{/snippet} {#snippet actions()}<Button variant="outline" onclick={renew} {pending}>{i.state === "missing" ? "Set up" : "Renew"}</Button>{/snippet}
</Banner> </Banner>
{/if} {/if}
<style>
.code { font-family: var(--font-inscription); font-size: 1.4rem; letter-spacing: 0.16em; color: var(--accent-strong); margin-left: 8px; }
</style>
+5 -5
View File
@@ -17,8 +17,9 @@
let { hostname, onclose }: { hostname: string; onclose: () => void } = $props(); let { hostname, onclose }: { hostname: string; onclose: () => void } = $props();
const row = $derived(app.overview?.hosts.find((h) => h.hostname === hostname)); // Known before the Dialog mounts, so its focus lands on Copy link (§2.9), not the title.
let on = $state(false); // svelte-ignore state_referenced_locally
let on = $state(!!app.overview?.hosts.find((h) => h.hostname === hostname)?.share_links);
let link = $state<MintedLink | null>(null); let link = $state<MintedLink | null>(null);
let minting = $state(false); let minting = $state(false);
let copied = $state(false); let copied = $state(false);
@@ -33,10 +34,9 @@
let usingPassword = $state(false); let usingPassword = $state(false);
let turning = $state<ApplyView | null>(null); let turning = $state<ApplyView | null>(null);
let stopFollow: (() => void) | undefined; let stopFollow: (() => void) | undefined;
let secretBox: HTMLInputElement | undefined = $state(); let secretBox: HTMLTextAreaElement | undefined = $state();
onMount(() => { onMount(() => {
on = !!row?.share_links;
if (on) void mint(); if (on) void mint();
}); });
onDestroy(() => stopFollow?.()); onDestroy(() => stopFollow?.());
@@ -122,7 +122,7 @@
{#if link?.warning}<p class="ia-hint">{link.warning.message}</p>{/if} {#if link?.warning}<p class="ia-hint">{link.warning.message}</p>{/if}
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if} {#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if link} {#if link}
<input bind:this={secretBox} class="ia-secret" readonly value={link.url} aria-label="Share link" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} /> <textarea bind:this={secretBox} class="ia-secret" readonly value={link.url} aria-label="Share link" onfocus={(e) => (e.currentTarget as HTMLTextAreaElement).select()}></textarea>
{:else if minting} {:else if minting}
<p class="ia-muted">Making the link…</p> <p class="ia-muted">Making the link…</p>
{/if} {/if}
+36 -23
View File
@@ -5,31 +5,42 @@
// Handoff §2.8 order: paused / needs attention, lost contact, health unavailable, the Caddy // Handoff §2.8 order: paused / needs attention, lost contact, health unavailable, the Caddy
// notice, then (on Hosts) the intermediate banner. First on every screen. // notice, then (on Hosts) the intermediate banner. First on every screen.
import { Banner, Button, Details } from "@ianitor/ui"; import { Banner, Button, Details } from "@ianitor/ui";
import { post, sentence } from "../lib/api"; import { app, refresh, restorable as canRestore, restoreLastKept } from "../lib/app.svelte";
import { app, refresh } from "../lib/app.svelte"; import { atTime, whenInline } from "../lib/format";
import { when } from "../lib/format";
import type { ApplyView } from "../lib/types";
const o = $derived(app.overview); const o = $derived(app.overview);
let restoring = $state(false); let restoring = $state(false);
let problem = $state<string | null>(null); let problem = $state<string | null>(null);
const restorable = $derived( const restorable = $derived(canRestore());
!!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target,
async function restore() {
restoring = true;
problem = await restoreLastKept();
restoring = false;
}
// §7.6: the bold line and line 2 by the pause's underlying code.
const pause = $derived.by(() => {
const code = o?.paused_reason ?? "";
const message = o?.paused?.message ?? "";
if (code === "apply.needs_attention")
return { bold: "Ianitor could not undo a failed change.", line2: "Visitors are served the last good settings, but the routes repository still has the change. Restore the last kept version to make them match again.", extra: "" };
if (code === "control.files_unwritten")
return { bold: "The change is live, but Ianitor could not save the proxy settings to disk.", line2: "Changes are paused until Ianitor restarts and saves them. Restoring the last kept version also clears this.", extra: "On the server: sudo systemctl restart ianitor-control" };
// control.paused wraps the reason: "Changes are paused: <reason>"; show the reason itself.
const own = message.replace(/^Changes are paused: /, "");
if (/^(repo|file|site)\./.test(code))
return { bold: own, line2: `Fix the file in the ${o?.repo?.name ?? "routes"} repository; Ianitor picks it up by itself.`, extra: "" };
return { bold: own, line2: "", extra: "" };
});
// "Show details" for every pause (§7.6): the server's detail, the restart command, or the
// full message when there is nothing more.
const pauseDetail = $derived(
[o?.paused_detail, pause.extra].filter(Boolean).join("\n") || (o?.paused ? (o.paused.message ?? "") : ""),
); );
async function restoreLastKept() {
if (!o?.undo?.target) return;
restoring = true;
try {
const a = await post<{ apply: ApplyView }>("/restore", { change_id: o.undo.target.change_id, base_rev: o.rev });
app.panel = { kind: "host", resume: a.apply.id };
} catch (e) {
problem = sentence(e);
} finally {
restoring = false;
}
}
async function retry() { async function retry() {
await refresh(); await refresh();
@@ -38,11 +49,13 @@
{#if o?.paused} {#if o?.paused}
<Banner tone="down" live="alert"> <Banner tone="down" live="alert">
{#snippet title()}<span class="ia-status" data-s="down"><span class="word">{restorable ? "needs attention" : "paused"}</span></span> <strong>{o.paused?.message}</strong>{/snippet} {#snippet title()}<span class="ia-status" data-s="down"><span class="word">{o.paused_reason === "apply.needs_attention" ? "needs attention" : "paused"}</span></span> <strong>{pause.bold}</strong>{/snippet}
{#if restorable && o.undo?.target}Goes back to "{o.undo.target.summary}" from {when(o.undo.target.kept_at, app.now)}. It is checked like any change.{/if} {#if pause.line2}<span class="line2">{pause.line2}</span>{/if}
{#if problem} {problem}{/if} {#if restorable && o.undo?.target}<p class="ia-hint">Goes back to "{o.undo.target.summary}" from {whenInline(o.undo.target.kept_at, app.now)}. It is checked like any change.</p>{/if}
{#if problem}<p role="status">{problem}</p>{/if}
{#if pauseDetail}<Details detail={pauseDetail} />{/if}
{#snippet actions()} {#snippet actions()}
{#if restorable}<Button variant="primary" onclick={restoreLastKept} pending={restoring}>Restore the last kept version</Button>{/if} {#if restorable}<Button variant="primary" onclick={restore} pending={restoring}>Restore the last kept version</Button>{/if}
{/snippet} {/snippet}
</Banner> </Banner>
{/if} {/if}
@@ -50,7 +63,7 @@
{#if app.lostContact} {#if app.lostContact}
<Banner tone="down" live="alert"> <Banner tone="down" live="alert">
{#snippet title()}<strong>{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."}</strong>{/snippet} {#snippet title()}<strong>{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."}</strong>{/snippet}
Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {when(new Date(app.lastUpdated).toISOString(), app.now)}.{/if} Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {atTime(new Date(app.lastUpdated).toISOString(), app.now)}.{/if}
{#snippet actions()}<Button onclick={retry}>Try again now</Button>{/snippet} {#snippet actions()}<Button onclick={retry}>Try again now</Button>{/snippet}
</Banner> </Banner>
{/if} {/if}
+31 -1
View File
@@ -5,7 +5,7 @@
// Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state, // Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state,
// the server clock offset and toasts. No business logic: everything shown comes from control. // the server clock offset and toasts. No business logic: everything shown comes from control.
import { call, setClientEvents } from "./api"; import { call, newKey, sentence, setClientEvents } from "./api";
import type { Overview } from "./types"; import type { Overview } from "./types";
export interface Toast { export interface Toast {
@@ -31,6 +31,10 @@ export const app = $state({
switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null }, switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null },
/** A renewal just installed (handoff §13.5). */ /** A renewal just installed (handoff §13.5). */
renewedUntil: null as null | string, renewedUntil: null as null | string,
/** After a kept add or edit: the row whose More button gets focus (§7.5). */
focusHost: null as string | null,
/** Narrower than 720 px (the phone layout, handoff §5.2). */
phone: false,
/** Panels the main screen opens (add/edit host, share, engine). */ /** Panels the main screen opens (add/edit host, share, engine). */
panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" }, panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" },
}); });
@@ -135,6 +139,12 @@ export function navigate(path: string): void {
app.path = path; app.path = path;
} }
if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
const mq = window.matchMedia("(max-width: 719.98px)");
app.phone = mq.matches;
mq.addEventListener?.("change", (e) => (app.phone = e.matches));
}
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
window.addEventListener("popstate", () => { window.addEventListener("popstate", () => {
app.path = location.pathname + location.search; app.path = location.pathname + location.search;
@@ -148,3 +158,23 @@ export function changesBlocked(): string | null {
if (o?.paused) return "Changes are paused."; if (o?.paused) return "Changes are paused.";
return null; return null;
} }
/** "Restore the last kept version" (handoff §7.6): start it and show its progress in a panel.
* Returns the sentence to show when it could not start. */
export async function restoreLastKept(): Promise<string | null> {
const o = app.overview;
if (!o?.undo?.target) return null;
try {
const a = await call<{ apply: { id: string } }>("POST", "/restore", { change_id: o.undo.target.change_id, base_rev: o.rev }, { idem: newKey() });
if (a.data) app.panel = { kind: "host", resume: a.data.apply.id };
return null;
} catch (e) {
return sentence(e);
}
}
/** Whether the pause can be cleared by restoring the last kept version. */
export function restorable(): boolean {
const o = app.overview;
return !!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target;
}
+6 -1
View File
@@ -6,7 +6,7 @@
// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it. // runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it.
import { get } from "./api"; import { get } from "./api";
import { refresh } from "./app.svelte"; import { app, refresh } from "./app.svelte";
import type { ApplyView } from "./types"; import type { ApplyView } from "./types";
export const FINAL = ["kept", "reverted", "failed", "needs_attention"]; export const FINAL = ["kept", "reverted", "failed", "needs_attention"];
@@ -36,6 +36,11 @@ export function follow(id: string, onupdate: (a: ApplyView) => void, every = 100
remember(id); remember(id);
const tick = async () => { const tick = async () => {
if (stopped) return; if (stopped) return;
if (app.signedOut) {
// No requests while signed out (the overview poll stops too); look again shortly.
timer = setTimeout(tick, every);
return;
}
try { try {
const a = await get<ApplyView>(`/applies/${encodeURIComponent(id)}`); const a = await get<ApplyView>(`/applies/${encodeURIComponent(id)}`);
if (stopped) return; if (stopped) return;
+18 -2
View File
@@ -25,6 +25,21 @@ export function when(iso: string | null | undefined, now = Date.now()): string {
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`; return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`;
} }
/** Inside a sentence: "today 14:02", "yesterday 21:14", "5 Nov 21:14". */
export function whenInline(iso: string | null | undefined, now = Date.now()): string {
return when(iso, now).replace(/^(Today|Yesterday)/, (s) => s.toLowerCase());
}
/** After "at" / "on": "at 14:03", "yesterday at 21:14", "on 5 Nov at 21:14", "on 5 Nov 2025". */
export function atTime(iso: string | null | undefined, now = Date.now()): string {
const w = when(iso, now);
if (!w) return "";
if (w.startsWith("Today ")) return `at ${w.slice(6)}`;
if (w.startsWith("Yesterday ")) return `yesterday at ${w.slice(10)}`;
const m = /^(\d+ \w+) (\d\d:\d\d)$/.exec(w);
return m ? `on ${m[1]} at ${m[2]}` : `on ${w}`;
}
/** "14 November 2026 at 14:20". */ /** "14 November 2026 at 14:20". */
export function longDate(iso: string | null | undefined, withTime = true): string { export function longDate(iso: string | null | undefined, withTime = true): string {
if (!iso) return ""; if (!iso) return "";
@@ -57,12 +72,13 @@ export function ago(iso: string | null | undefined, now: number): string {
return duration((now - Date.parse(iso)) / 1000) + " ago"; return duration((now - Date.parse(iso)) / 1000) + " ago";
} }
/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1). */ /** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1); short (phone, §5.2): "5 healthy, 1 degraded, 1 down". */
export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }): string { export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }, short = false): string {
const parts = [`${c.healthy} healthy`]; const parts = [`${c.healthy} healthy`];
if (c.degraded) parts.push(`${c.degraded} degraded`); if (c.degraded) parts.push(`${c.degraded} degraded`);
if (c.down) parts.push(`${c.down} down`); if (c.down) parts.push(`${c.down} down`);
if (c.unknown) parts.push(`${c.unknown} not checked`); if (c.unknown) parts.push(`${c.unknown} not checked`);
if (short) return parts.join(", ");
return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`; return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`;
} }
+5 -2
View File
@@ -113,6 +113,7 @@ export interface PkiRequest {
device_id: string | null; device_id: string | null;
name: string | null; name: string | null;
csr_pem: string | null; csr_pem: string | null;
csr_sha256?: string | null;
not_after: string | null; not_after: string | null;
message_code: string; message_code: string;
message: string; message: string;
@@ -136,7 +137,7 @@ export interface EngineView {
since: string | null; since: string | null;
target: string | null; target: string | null;
switchable: boolean; switchable: boolean;
fallback_ready: { built_at: string | null; current: boolean } | null; fallback_ready: { built_at: string | null; current: boolean; compared: number; matched: number; differences: string[] } | null;
last_error: Reason | null; last_error: Reason | null;
notes: Blocked[]; notes: Blocked[];
} }
@@ -154,12 +155,13 @@ export interface Overview {
engine: EngineView; engine: EngineView;
last_apply: ApplyView | null; last_apply: ApplyView | null;
undo: UndoView; undo: UndoView;
active_apply: { id: string; state: string; summary: string; seconds_left: number | null; queued: number } | null; active_apply: { id: string; state: string; summary: string; seconds_left: number | null; kind: string; hosts: string[]; watch_ends_at: string | null; queued: number } | null;
repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null; repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null;
intermediate: IntermediateView | null; intermediate: IntermediateView | null;
site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean; auth_logout_url?: string | null } | null; site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean; auth_logout_url?: string | null } | null;
paused: Blocked | null; paused: Blocked | null;
paused_reason: string | null; paused_reason: string | null;
paused_detail?: string | null;
health_error: Blocked | null; health_error: Blocked | null;
rev: string | null; rev: string | null;
viewer?: { name: string; via: string } | null; viewer?: { name: string; via: string } | null;
@@ -234,6 +236,7 @@ export interface CertsView {
root: { offline: boolean; subject: string; not_after: string; sha256: string }; root: { offline: boolean; subject: string; not_after: string; sha256: string };
devices: DeviceRow[]; devices: DeviceRow[];
device_lifetime_days: number; device_lifetime_days: number;
device_valid_until: string | null;
server_lifetime_days: number; server_lifetime_days: number;
approval: string; approval: string;
requests: PkiRequest[]; requests: PkiRequest[];
+10 -6
View File
@@ -11,7 +11,7 @@
import IntermediateBanner from "../components/IntermediateBanner.svelte"; import IntermediateBanner from "../components/IntermediateBanner.svelte";
import { ApiError, del, get, post, sentence } from "../lib/api"; import { ApiError, del, get, post, sentence } from "../lib/api";
import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte"; import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { shortDate, when } from "../lib/format"; import { atTime, shortDate } from "../lib/format";
import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types"; import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types";
let { newDevice }: { newDevice: boolean } = $props(); let { newDevice }: { newDevice: boolean } = $props();
@@ -120,7 +120,11 @@
} }
const lifetime = $derived(certs?.device_lifetime_days ?? 365); const lifetime = $derived(certs?.device_lifetime_days ?? 365);
const until = $derived(shortDate(new Date(Date.now() + lifetime * 86_400_000).toISOString())); // The server caps it at the intermediate's end (Q7); without one it cannot issue anyway.
const until = $derived(shortDate(certs?.device_valid_until ?? new Date(Date.now() + lifetime * 86_400_000).toISOString()));
const capped = $derived(
!!certs?.device_valid_until && Date.parse(certs.device_valid_until) < Date.now() + (lifetime - 1) * 86_400_000,
);
const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => { const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => {
switch (certs?.intermediate?.state) { switch (certs?.intermediate?.state) {
case "ok": return ["healthy", "valid"]; case "ok": return ["healthy", "valid"];
@@ -187,18 +191,18 @@
<p class="ia-hint" id="device-name-h">Shown in this list and inside the certificate.</p> <p class="ia-hint" id="device-name-h">Shown in this list and inside the certificate.</p>
</div> </div>
<Segmented legend="What is it" name="kind" bind:value={kind} options={[{ value: "phone", label: "Phone or tablet" }, { value: "computer", label: "Computer" }, { value: "app", label: "Domi app" }]} /> <Segmented legend="What is it" name="kind" bind:value={kind} options={[{ value: "phone", label: "Phone or tablet" }, { value: "computer", label: "Computer" }, { value: "app", label: "Domi app" }]} />
<p class="ia-hint">Valid for {lifetime} days, until {until}. It lets this device into hosts that ask for a Domi device certificate.</p> <p class="ia-hint">{#if capped}Valid until {until}, when the Domi intermediate certificate ends (renew it to issue for a full year).{:else}Valid for {lifetime} days, until {until}.{/if} It lets this device into hosts that ask for a Domi device certificate.</p>
</form> </form>
{:else if request.state === "waiting"} {:else if request.state === "waiting"}
<p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p> <p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p>
<p>Approve it on the server, and only if it shows the same code:</p> <p>Custos cannot approve device certificates yet, so approve it on the server, and only if it shows the same code:</p>
<p class="ia-code" aria-label="Match code {request.match_code}">{request.match_code}</p> <p class="ia-code" aria-label="Match code {request.match_code}">{request.match_code}</p>
{#if request.approve_command}<p class="ia-hint">Run on the server:</p><pre class="ia-secret ia-cmd">{request.approve_command}</pre>{/if} {#if request.approve_command}<p class="ia-hint">Run on the server:</p><pre class="ia-secret ia-cmd">{request.approve_command}</pre>{/if}
<p class="ia-muted">The request stays open for {Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")}. Nothing is issued until it is approved.</p> <p class="ia-muted">The request stays open for 10 minutes ({Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")} left). Nothing is issued until it is approved.</p>
<div><Button onclick={cancelRequest}>Cancel request</Button></div> <div><Button onclick={cancelRequest}>Cancel request</Button></div>
<span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span> <span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span>
{:else if issuedDevice} {:else if issuedDevice}
<Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved at {when(request?.approved_at, app.now)}.{/snippet}</Banner> <Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved {atTime(request?.approved_at, app.now)}.{/snippet}</Banner>
<div class="buttons"> <div class="buttons">
<Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button> <Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button>
<Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button> <Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button>
+1 -2
View File
@@ -9,7 +9,7 @@
import HostPanel from "../components/HostPanel.svelte"; import HostPanel from "../components/HostPanel.svelte";
import { get, post, sentence } from "../lib/api"; import { get, post, sentence } from "../lib/api";
import { app, changesBlocked, navigate } from "../lib/app.svelte"; import { app, changesBlocked, navigate } from "../lib/app.svelte";
import { FIELD_LABEL, fieldValue, longDate, when } from "../lib/format"; import { FIELD_LABEL, fieldValue, when } from "../lib/format";
import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types"; import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types";
let { host, pick }: { host?: string; pick?: string } = $props(); let { host, pick }: { host?: string; pick?: string } = $props();
@@ -163,7 +163,6 @@
{#if editFrom} {#if editFrom}
<HostPanel prefill={editFrom} hostname={undefined} onclose={() => { editFrom = null; void load(); }} /> <HostPanel prefill={editFrom} hostname={undefined} onclose={() => { editFrom = null; void load(); }} />
{/if} {/if}
<span class="sr-only">{longDate(entry?.at)}</span>
<style> <style>
.cols { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; } .cols { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; }
+15 -24
View File
@@ -3,16 +3,17 @@
- file, You can obtain one at https://mozilla.org/MPL/2.0/. --> - file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts"> <script lang="ts">
// Handoff §5: the main screen. // Handoff §5: the main screen.
import { Banner, Button, Icon } from "@ianitor/ui"; import { tick } from "svelte";
import { Banner, Button } from "@ianitor/ui";
import ChangeBar from "../components/ChangeBar.svelte"; import ChangeBar from "../components/ChangeBar.svelte";
import EnginePopover from "../components/EnginePopover.svelte"; import EngineChip from "../components/EngineChip.svelte";
import HostList from "../components/HostList.svelte"; import HostList from "../components/HostList.svelte";
import HostPanel from "../components/HostPanel.svelte"; import HostPanel from "../components/HostPanel.svelte";
import IntermediateBanner from "../components/IntermediateBanner.svelte"; import IntermediateBanner from "../components/IntermediateBanner.svelte";
import ShareDialog from "../components/ShareDialog.svelte"; import ShareDialog from "../components/ShareDialog.svelte";
import { call, newKey, post, sentence } from "../lib/api"; import { call, newKey, post, sentence } from "../lib/api";
import { app, changesBlocked, navigate, refresh, toast } from "../lib/app.svelte"; import { app, changesBlocked, navigate, refresh, toast } from "../lib/app.svelte";
import { countsSentence, when } from "../lib/format"; import { atTime, countsSentence } from "../lib/format";
import type { ApplyView, HostSpec } from "../lib/types"; import type { ApplyView, HostSpec } from "../lib/types";
let { route }: { route: { newHost: boolean; edit?: string } } = $props(); let { route }: { route: { newHost: boolean; edit?: string } } = $props();
@@ -25,12 +26,18 @@
const panelOpen = $derived(route.newHost || !!route.edit || app.panel?.kind === "host"); const panelOpen = $derived(route.newHost || !!route.edit || app.panel?.kind === "host");
const blocked = $derived(changesBlocked()); const blocked = $derived(changesBlocked());
function closePanel() { async function closePanel() {
prefill = null; prefill = null;
focusField = undefined; focusField = undefined;
if (app.panel?.kind === "host") app.panel = null; if (app.panel?.kind === "host") app.panel = null;
if (route.newHost || route.edit) navigate("/"); if (route.newHost || route.edit) navigate("/");
void refresh(); await refresh();
const h = app.focusHost;
app.focusHost = null;
if (h) {
await tick();
document.querySelector<HTMLElement>(`[aria-label="More for ${h.replace(/["\\]/g, "")}"]`)?.focus();
}
} }
async function remove(h: string) { async function remove(h: string) {
@@ -62,27 +69,15 @@
} }
} }
const engineName = $derived(o?.engine.running === "caddy" ? "Caddy" : "Pingora");
const engineLabel = $derived(
o?.engine.state === "switching" ? "Engine: switching" : `Engine: ${engineName}${o?.engine.state === "stopped" ? ", not answering" : ""}. Change engine`,
);
</script> </script>
<div class="head"> <div class="head">
<div> <div>
<h1 class="ia-display">Hosts</h1> <h1 class="ia-display">Hosts</h1>
{#if o}<p class="ia-text2">{countsSentence(o.counts)}</p>{/if} {#if o}<p class={app.phone ? "ia-sub" : "ia-text2"}>{countsSentence(o.counts, app.phone)}</p>{/if}
</div> </div>
<div class="actions"> <div class="actions">
{#if o} {#if !app.phone}<EngineChip />{/if}
<button type="button" class="ia-engine" aria-haspopup="dialog" aria-expanded={app.panel?.kind === "engine"} aria-label={engineLabel}
onclick={() => (app.panel = app.panel?.kind === "engine" ? null : { kind: "engine" })}>
{#if o.engine.state === "switching"}<Icon name="clock" /> Engine Switching…{:else}
<span class="ia-status" data-s={o.engine.state === "stopped" ? "down" : "healthy"}><span class="ia-dot"></span></span>
<small class="desktop">Engine</small> {engineName}{#if o.engine.running === "caddy"} <small>(fallback)</small>{/if}{/if}
<Icon name="chevron" />
</button>
{/if}
<Button variant="primary" icon="plus" label="Add a host" disabled={!!blocked} describedby={blocked ? "add-blocked" : undefined} onclick={() => navigate("/hosts/new")}>Host</Button> <Button variant="primary" icon="plus" label="Add a host" disabled={!!blocked} describedby={blocked ? "add-blocked" : undefined} onclick={() => navigate("/hosts/new")}>Host</Button>
{#if blocked}<span class="sr-only" id="add-blocked">{blocked}</span>{/if} {#if blocked}<span class="sr-only" id="add-blocked">{blocked}</span>{/if}
</div> </div>
@@ -115,7 +110,7 @@
<hr class="ia-ornament" /> <hr class="ia-ornament" />
<p class="ia-muted footer"> <p class="ia-muted footer">
Routes live in the {o.repo.name} repository, one file per host. Routes live in the {o.repo.name} repository, one file per host.
{#if o.repo.last_push_at}Last pushed to Gitea at {when(o.repo.last_push_at, app.now)}.{/if} {#if o.repo.last_push_at}Last pushed to Gitea {atTime(o.repo.last_push_at, app.now)}.{/if}
{#if o.repo.unpushed}{o.repo.unpushed} changes not yet pushed.{/if} {#if o.repo.unpushed}{o.repo.unpushed} changes not yet pushed.{/if}
<button type="button" class="domi-btn link" onclick={() => navigate("/history")}>See history</button> <button type="button" class="domi-btn link" onclick={() => navigate("/history")}>See history</button>
</p> </p>
@@ -129,13 +124,9 @@
{#if app.panel?.kind === "share"} {#if app.panel?.kind === "share"}
<ShareDialog hostname={app.panel.hostname} onclose={() => { app.panel = null; void refresh(); }} /> <ShareDialog hostname={app.panel.hostname} onclose={() => { app.panel = null; void refresh(); }} />
{/if} {/if}
{#if app.panel?.kind === "engine"}
<EnginePopover onclose={() => (app.panel = null)} />
{/if}
<style> <style>
.head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 16px; } .head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 16px; }
.actions { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; } .actions { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
.footer { text-align: center; } .footer { text-align: center; }
@media (max-width: 719.98px) { .desktop { display: none; } }
</style> </style>
+24 -6
View File
@@ -16,6 +16,20 @@
let pending = $state(false); let pending = $state(false);
let starting = $state(false); let starting = $state(false);
const base = $derived(r?.file_base ?? `domi-intermediate-${new Date().toISOString().slice(0, 10)}`); const base = $derived(r?.file_base ?? `domi-intermediate-${new Date().toISOString().slice(0, 10)}`);
const signCmd = $derived(r?.approve_command ?? `openssl x509 -req -in ${base}.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile ${base}.ext -out ${base}.crt`);
const checkCmd = $derived(`openssl req -in ${base}.csr -outform DER | openssl dgst -sha256`);
let copied = $state(false);
// Groups of 8, easier to compare by eye; openssl prints it without spaces.
const group = (h: string) => h.match(/.{1,8}/g)?.join(" ") ?? h;
async function copy(text: string) {
try {
await navigator.clipboard.writeText(text);
copied = true;
setTimeout(() => (copied = false), 3000);
} catch {
err = "Your browser did not allow copying. Select the command and copy it.";
}
}
function save(text: string, name: string, type: string) { function save(text: string, name: string, type: string) {
const url = URL.createObjectURL(new Blob([text], { type })); const url = URL.createObjectURL(new Blob([text], { type }));
@@ -88,15 +102,19 @@
<p class="ia-label">Step 1</p> <p class="ia-label">Step 1</p>
<h2 class="ia-h3">Download the request</h2> <h2 class="ia-h3">Download the request</h2>
<p class="ia-text2">This file asks the Domi root to sign a new intermediate certificate. It holds no secret.</p> <p class="ia-text2">This file asks the Domi root to sign a new intermediate certificate. It holds no secret.</p>
<p>Check that the offline computer shows the same code: <span class="ia-code small" aria-label="Match code {r.match_code}">{r.match_code}</span></p> <div class="row"><Button icon="download" onclick={download}>Download the request (.csr)</Button><Button icon="download" onclick={downloadExt}>Download the signing settings (.ext)</Button></div>
<div class="row"><Button icon="copy" onclick={download}>Download the request (.csr)</Button><Button icon="copy" onclick={downloadExt}>Download the signing settings (.ext)</Button></div>
</section> </section>
<section class="step"> <section class="step">
<p class="ia-label">Step 2</p> <p class="ia-label">Step 2</p>
<h2 class="ia-h3">Sign it on the offline computer</h2> <h2 class="ia-h3">Sign it on the offline computer</h2>
<p class="ia-text2">Copy both files to the offline computer that holds the Domi root, then run:</p> <p class="ia-text2">Copy both files to the offline computer that holds the Domi root.</p>
<pre class="ia-secret ia-cmd">{r.approve_command ?? `openssl x509 -req -in ${base}.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile ${base}.ext -out ${base}.crt`}</pre> <p class="ia-text2">First check that the request is the one this server made. This prints its fingerprint:</p>
<p class="ia-muted">Before signing, check that the request is the one this page shows: <code>openssl req -in {base}.csr -noout -subject</code>. (On a computer with Ianitor installed, <code>ianitor-control ca sign</code> does the same and shows the match code.)</p> <pre class="ia-secret ia-cmd">{checkCmd}</pre>
{#if r.csr_sha256}<p>openssl must print the same fingerprint as this page: <span class="ia-cmd fp" aria-label="Fingerprint {r.csr_sha256}">{group(r.csr_sha256)}</span></p>{/if}
<p class="ia-text2">Then sign it:</p>
<pre class="ia-secret ia-cmd">{signCmd}</pre>
<div class="row"><Button icon="copy" onclick={() => copy(signCmd)}>Copy command</Button>{#if copied}<span class="ia-status" data-s="kept" role="status"><Icon name="check" />Copied</span>{/if}</div>
<p class="ia-muted">On a computer with Ianitor installed, <code>ianitor-control ca sign</code> signs it instead and shows the match code {r.match_code}.</p>
</section> </section>
<section class="step"> <section class="step">
<p class="ia-label">Step 3</p> <p class="ia-label">Step 3</p>
@@ -121,5 +139,5 @@
<style> <style>
.row { display: flex; gap: 8px; flex-wrap: wrap; } .row { display: flex; gap: 8px; flex-wrap: wrap; }
.step { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; } .step { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
.small { font-size: 1.4rem; } .fp { word-break: break-all; color: var(--accent-strong); }
</style> </style>
+5 -5
View File
@@ -8,7 +8,7 @@
import { Banner, Button, Dialog, Segmented } from "@ianitor/ui"; import { Banner, Button, Dialog, Segmented } from "@ianitor/ui";
import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api"; import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api";
import { app, navigate, toast } from "../lib/app.svelte"; import { app, navigate, toast } from "../lib/app.svelte";
import { shortDate, when } from "../lib/format"; import { longDate, shortDate, whenInline } from "../lib/format";
import type { CreatedToken, ShareLink, TokenRow } from "../lib/types"; import type { CreatedToken, ShareLink, TokenRow } from "../lib/types";
let { tab }: { tab: string } = $props(); let { tab }: { tab: string } = $props();
@@ -164,7 +164,7 @@
<div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel"> <div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel">
{#if tab === "general"} {#if tab === "general"}
<p class="ia-label">Routes repository</p> <p class="ia-label">Routes repository</p>
<p>{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + when(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</p> <p>{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + whenInline(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</p>
<p class="ia-label">Health watch after apply</p> <p class="ia-label">Health watch after apply</p>
<p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p> <p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p>
<p class="ia-label">Signed in</p> <p class="ia-label">Signed in</p>
@@ -186,7 +186,7 @@
<div class="grow"> <div class="grow">
<span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span> <span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span>
<span class="ia-sub" style="display:block"> <span class="ia-sub" style="display:block">
{#if revoked[t.id]}Revoked {when(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${when(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if} {#if revoked[t.id]}Revoked {whenInline(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${whenInline(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if}
</span> </span>
</div> </div>
{#if !revoked[t.id] && !t.revoked_at} {#if !revoked[t.id] && !t.revoked_at}
@@ -221,7 +221,7 @@
{#each active as l (l.id)} {#each active as l (l.id)}
<li> <li>
<div class="grow"><strong>{l.hostname}</strong>{l.path_prefix !== "/" ? l.path_prefix : ""} <div class="grow"><strong>{l.hostname}</strong>{l.path_prefix !== "/" ? l.path_prefix : ""}
<span class="ia-sub" style="display:block">Made {when(l.created_at, app.now)} · expires {when(l.expires_at, app.now)}{l.has_password ? " · password" : ""}</span></div> <span class="ia-sub" style="display:block">Made {whenInline(l.created_at, app.now)} · expires {whenInline(l.expires_at, app.now)}{l.has_password ? " · password" : ""}</span></div>
<Button small onclick={() => stop(l)}>Stop this link</Button> <Button small onclick={() => stop(l)}>Stop this link</Button>
</li> </li>
{/each} {/each}
@@ -255,7 +255,7 @@
<Button variant={tokenCopied ? "quiet" : "primary"} icon="copy" onclick={copyToken} data-autofocus>{tokenCopied ? "Copy again" : "Copy token"}</Button> <Button variant={tokenCopied ? "quiet" : "primary"} icon="copy" onclick={copyToken} data-autofocus>{tokenCopied ? "Copy again" : "Copy token"}</Button>
</div> </div>
{#if tokenCopied}<p role="status">Copied. Paste it into Custos now. Ianitor cannot show it again.</p>{/if} {#if tokenCopied}<p role="status">Copied. Paste it into Custos now. Ianitor cannot show it again.</p>{/if}
<p class="ia-muted">{made.expires_at ? `Expires on ${shortDate(made.expires_at)}.` : "Never expires."}</p> <p class="ia-muted">{made.expires_at ? `Expires on ${longDate(made.expires_at, false)}.` : "Never expires."}</p>
{#if askClose} {#if askClose}
<p role="alert">Close without copying? The token cannot be shown again. <p role="alert">Close without copying? The token cannot be shown again.
<Button small onclick={() => (askClose = false)}>Go back</Button> <Button small variant="danger" onclick={() => closeToken(true)}>Close anyway</Button></p> <Button small onclick={() => (askClose = false)}>Go back</Button> <Button small variant="danger" onclick={() => closeToken(true)}>Close anyway</Button></p>
+80
View File
@@ -0,0 +1,80 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// 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, realLooking } from "./demo";
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([]);
});
}
});
+291
View File
@@ -0,0 +1,291 @@
// 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, nowMs, 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(nowMs() + 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(added: Json[] = []): Json {
const list = [...hosts(), ...added];
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. A host added in the
* demo (the e2e suite's Add host flow) is listed from then on, healthy, with the upstream it was
* given; a device certificate request carries the name it was asked with. */
export function demoRoutes(): Route[] {
const m = newMock();
const added: Json[] = [];
let device = "";
const request = (state: "waiting" | "approved"): Json => ({
request_id: "pr_dev",
kind: "device",
state,
match_code: "47 19 83",
created_at: at(-5),
expires_at: at(600),
approved_at: state === "approved" ? at(0) : null,
device_id: state === "approved" ? "dv_1" : null,
name: device,
csr_pem: null,
not_after: state === "approved" ? at(365 * DAY) : null,
message_code: state === "approved" ? "pki.issued" : "pki.waiting.manual",
message: state === "approved" ? `${device} has a certificate.` : "Approve it on the server with the match code.",
approve_command: state === "approved" ? null : "ianitor-control pki approve 47 19 83",
problem: null,
});
return [
["GET", /^\/overview$/, () => [200, overview(added)]],
["POST", /^\/hosts$/, (_, b) => {
const h = b.host as Json;
const name = String(h.hostname);
m.state.hostsAdded.push(name);
const ups = Array.isArray(h.upstreams) ? h.upstreams.map(String) : [];
added.push(demoHost(name, ups, { state: "healthy", latency: 11 }, { added_at: at(0) }));
return [202, { apply: apply("ch_new", "queued", `Added ${name}`, [name]) }];
}],
["POST", /^\/certs\/devices$/, (_, b) => {
device = String(b.name ?? "");
return [202, request("waiting")];
}],
["GET", /^\/pki-requests\/pr_dev$/, () => [200, request("approved")]],
// A share link whose token cannot be read as a name (the stand-in's `ish1.abc` would be).
["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_demo", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.4f9c2a7e1b0d`, expires_at: at(7 * DAY), path_prefix: "/", has_password: false, warning: null }]],
["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(m),
];
}
/** 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);
}
// What the demo may show (demo.test.ts, and the e2e suite on every page it visits).
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. */
export 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;
}
+35 -1
View File
@@ -146,7 +146,8 @@ describe("ROADMAP §4 flows, clicks counted", () => {
start(); start();
await click(await screen.findByRole("button", { name: "Renew" })); await click(await screen.findByRole("button", { name: "Renew" }));
await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true)); await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true));
await screen.findByLabelText("Match code 47 19 83"); // The renewal is waiting: the banner says where to sign it (no code to compare with openssl).
await screen.findByRole("button", { name: "Sign it by hand" });
expect(clicks).toBe(1); expect(clicks).toBe(1);
}); });
@@ -176,6 +177,39 @@ describe("focus", () => {
await user.keyboard("recipes.home.test"); await user.keyboard("recipes.home.test");
expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("recipes.home.test"); expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("recipes.home.test");
}); });
it("the share dialog opens on Copy link and gives focus back to the row's More button", async () => {
start();
const more = await screen.findByRole("button", { name: "More for wiki.home.test" });
await click(more);
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
const copy = await screen.findByRole("button", { name: "Copy link" });
await waitFor(() => expect(document.activeElement).toBe(copy));
// jsdom fires no cancel event on Esc for a modal dialog: close it with its button.
await click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("button", { name: "Copy link" })).toBeNull());
await waitFor(() => expect(document.activeElement).toBe(more));
});
it("the engine popover closes with Esc and focus goes back to the chip", async () => {
start();
const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
await click(chip);
await screen.findByRole("button", { name: "Switch to Caddy" });
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
expect(document.activeElement).toBe(screen.getByRole("button", { name: /^Engine: Pingora/ }));
});
it("a click on the engine chip while its popover is open closes it", async () => {
start();
const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
await click(chip);
await screen.findByRole("button", { name: "Switch to Caddy" });
await new Promise((r) => setTimeout(r, 10));
await click(chip);
await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
});
}); });
describe("sign-in and contact", () => { describe("sign-in and contact", () => {
+38 -18
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>;
@@ -19,10 +20,13 @@ export interface Mock {
}; };
} }
const now = () => new Date().toISOString(); /** The stand-in's clock: the real one, or a fixed instant (the e2e suite's, so two takes of a screen match). */
const later = (s: number) => new Date(Date.now() + s * 1000).toISOString(); export const clock: { fixed: number | null } = { fixed: null };
export const nowMs = () => clock.fixed ?? Date.now();
const now = () => new Date(nowMs()).toISOString();
const later = (s: number) => new Date(nowMs() + 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 +41,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 +62,30 @@ function apply(id: string, state: string, summary: string, hosts: string[]) {
}; };
} }
export function installMock(): Mock { /** One API call: method, the path after /api/v1, and its answer as [status, body]. */
const m: Mock = { export type Route = [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]];
export function newMock(): Mock {
return {
calls: [], calls: [],
state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] }, state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] },
}; };
}
/** The first route that matches answers, with server_time added as control does; else control's 404. */
export function respond(routes: Route[], method: string, path: string, body: Json): { status: number; text: string | null } {
for (const [mm, re, f] of routes) {
const match = path.match(re);
if (mm === method && match) {
const [status, data] = f(match, body);
const withTime = data && typeof data === "object" ? { ...(data as Json), server_time: now() } : data;
return { status, text: status === 204 ? null : JSON.stringify(withTime) };
}
}
return { status: 404, text: JSON.stringify({ error: { code: "request.not_found", message: "There is no such API call.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "x" }) };
}
export function mockRoutes(m: Mock): Route[] {
const overview = (): Json => ({ const overview = (): Json => ({
counts: { hosts: 2 + m.state.hostsAdded.length, healthy: 2, degraded: 0, down: 0, unknown: 0 }, counts: { hosts: 2 + m.state.hostsAdded.length, healthy: 2, degraded: 0, down: 0, unknown: 0 },
hosts: [host("wiki.home.test", true), host("photos.home.test", false), ...m.state.hostsAdded.map((h) => host(h, false))], hosts: [host("wiki.home.test", true), host("photos.home.test", false), ...m.state.hostsAdded.map((h) => host(h, false))],
@@ -73,7 +95,7 @@ export function installMock(): Mock {
since: now(), since: now(),
target: null, target: null,
switchable: true, switchable: true,
fallback_ready: { built_at: now(), current: true }, fallback_ready: { built_at: now(), current: true, compared: 3, matched: 3, differences: ["Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."] },
last_error: null, last_error: null,
notes: [], notes: [],
}, },
@@ -108,7 +130,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 +174,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 +186,8 @@ export function installMock(): Mock {
const method = (init?.method ?? "GET").toUpperCase(); const method = (init?.method ?? "GET").toUpperCase();
const body = init?.body ? JSON.parse(String(init.body)) : {}; const body = init?.body ? JSON.parse(String(init.body)) : {};
m.calls.push({ method, path, body }); m.calls.push({ method, path, body });
for (const [mm, re, f] of routes) { const a = respond(routes, method, path, body);
const match = path.match(re); return new Response(a.text, { status: a.status, headers: { "Content-Type": "application/json" } });
if (mm === method && match) {
const [status, data] = f(match, body);
const withTime = data && typeof data === "object" ? { ...(data as Json), server_time: now() } : data;
return new Response(status === 204 ? null : JSON.stringify(withTime), { status, headers: { "Content-Type": "application/json" } });
}
}
return new Response(JSON.stringify({ error: { code: "request.not_found", message: "There is no such API call.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "x" }), { status: 404, headers: { "Content-Type": "application/json" } });
}) as typeof fetch; }) as typeof fetch;
return m; return m;
+1
View File
@@ -281,6 +281,7 @@ pub async fn overview(
intermediate: super::pki::intermediate_view(c), intermediate: super::pki::intermediate_view(c),
site, site,
paused_reason: c.effective_pause().map(|p| p.code), paused_reason: c.effective_pause().map(|p| p.code),
paused_detail: c.effective_pause().and_then(|p| p.detail),
paused: c.effective_pause().map(|p| Blocked { paused: c.effective_pause().map(|p| Blocked {
code: "control.paused".into(), code: "control.paused".into(),
message: message("control.paused", &messages::params([("reason", p.message)])), message: message("control.paused", &messages::params([("reason", p.message)])),
+2
View File
@@ -544,6 +544,8 @@ pub struct Overview {
/// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`, /// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`,
/// `repo.unreadable`, …), so the UI can offer the right action. /// `repo.unreadable`, …), so the UI can offer the right action.
pub paused_reason: Option<String>, pub paused_reason: Option<String>,
/// The technical detail behind the pause, for "Show details" (never a secret).
pub paused_detail: Option<String>,
/// Set when control cannot read health from edge (`health.unavailable`). /// Set when control cannot read health from edge (`health.unavailable`).
pub health_error: Option<Blocked>, pub health_error: Option<Blocked>,
pub rev: Option<String>, pub rev: Option<String>,
+269
View File
@@ -0,0 +1,269 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The deadline of a trial under Caddy (QC round 2, B2; the Phase 2 guarantee that an
//! unconfirmed change never outlives control). Edge drops a trial by itself when control does
//! not confirm it in time; Caddy has no such clock, so two things outside control's own process
//! stand in for it:
//!
//! - `ianitor-control caddy-revert` (systemd `ExecStopPost=` of ianitor-control, so it runs
//! after every stop, a crash included): with a trial out, Caddy goes back to caddy.json (the
//! last good config) at once;
//! - `ianitor-control caddy-guard` (its own unit next to caddy-fallback, so a hung control is
//! covered too): once a second, it reverts a trial whose deadline has passed.
//!
//! Control *arms* the deadline (`caddy-trial.json` in its state dir) before it loads a trial,
//! and *claims* it (an atomic rename) right after its journal says `confirmed`; the guard
//! takes it with the same kind of rename (to `.reverting`, then `.expired` once Caddy is
//! verified on caddy.json; given back if the load fails, so it is tried again). A crash between
//! `confirmed` and the claim leaves both: the guard and caddy-revert see `confirmed` and leave
//! the trial to recovery, which promotes it. Whoever renames first wins, so a trial is either confirmed by control or
//! reverted by the guard, never both. caddy.json itself is only ever written with a confirmed
//! config, so loading it is always safe.
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::config::Config;
use crate::records::Journal;
use crate::util::{read_json, write_json};
pub const DEADLINE_FILE: &str = "caddy-trial.json";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TrialDeadline {
pub apply_id: String,
/// Unix seconds.
pub deadline: u64,
}
fn path(state_dir: &Path, suffix: &str) -> PathBuf {
state_dir.join(format!("{DEADLINE_FILE}{suffix}"))
}
/// Before a trial goes into Caddy.
pub fn arm(state_dir: &Path, apply_id: &str, deadline: u64) -> Result<(), String> {
write_json(
&path(state_dir, ""),
&TrialDeadline {
apply_id: apply_id.to_owned(),
deadline,
},
)
}
/// Control, before it confirms: `true` if it got the deadline first (the guard has not
/// reverted the trial), `false` if the guard did.
pub fn claim(state_dir: &Path) -> bool {
let claimed = path(state_dir, ".claimed");
if std::fs::rename(path(state_dir, ""), &claimed).is_err() {
return false;
}
let _ = std::fs::remove_file(claimed);
true
}
/// After a trial is reverted (or at start): nothing is out any more.
pub fn disarm(state_dir: &Path) {
for s in ["", ".claimed", ".expired", ".reverting"] {
let _ = std::fs::remove_file(path(state_dir, s));
}
}
pub fn armed(state_dir: &Path) -> Option<TrialDeadline> {
read_json(&path(state_dir, "")).ok().flatten()
}
/// Whether control's journal says the change is confirmed (then it is being promoted and
/// caddy.json will hold it; nothing to revert).
fn confirmed(state_dir: &Path) -> bool {
read_json::<Journal>(&state_dir.join("journal.json"))
.ok()
.flatten()
.is_some_and(|j| j.stage == "confirmed" || j.stage == "promoted")
}
/// What to do now, for a deadline file as found (pure, for the tests).
#[derive(Debug, PartialEq, Eq)]
pub enum Verdict {
Nothing,
Revert,
}
pub fn verdict(armed: Option<&TrialDeadline>, confirmed: bool, now: u64, at_stop: bool) -> Verdict {
match armed {
Some(d) if !confirmed && (at_stop || now > d.deadline) => Verdict::Revert,
_ => Verdict::Nothing,
}
}
/// Whether Caddy is the engine that serves (the engine file; Pingora without `[engine]`).
fn caddy_serves(cfg: &Config) -> bool {
cfg.engine
.as_ref()
.is_some_and(|e| crate::switch::read_engine_file(&e.file) == "caddy")
}
/// A revert that stopped half way (the guard died while loading) counts as armed again.
fn resume_half_done(dir: &Path) {
let reverting = path(dir, ".reverting");
if reverting.exists() && !path(dir, "").exists() {
let _ = std::fs::rename(reverting, path(dir, ""));
}
}
/// Take the deadline away from control (rename to `.reverting`), load the last good
/// caddy.json and check that Caddy runs it; only then is the deadline marked expired. If the
/// load fails, the deadline is given back, so the next try (or control's own claim, while
/// Caddy still runs the trial) decides.
async fn revert(cfg: &Config, why: &str) -> Result<bool, String> {
let dir = &cfg.state_dir;
let reverting = path(dir, ".reverting");
if std::fs::rename(path(dir, ""), &reverting).is_err() {
// Control claimed it a moment ago: it confirms; nothing to do.
return Ok(false);
}
let loaded = async {
let sock = cfg
.caddy_compile()
.caddy_admin_socket
.clone()
.ok_or("no caddy_admin_socket is configured")?;
let text = std::fs::read(&cfg.caddy.config)
.map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?;
crate::caddy_link::load(Path::new(&sock), &text).await?;
if !crate::caddy_link::runs(Path::new(&sock), &text).await? {
return Err("Caddy took caddy.json but does not run it".to_owned());
}
Ok::<_, String>(())
}
.await;
match loaded {
Ok(()) => {
let _ = std::fs::rename(&reverting, path(dir, ".expired"));
log::warn!(target: "ianitor::caddy-guard", "{why}: Caddy is back on the last good config");
Ok(true)
}
Err(e) => {
let _ = std::fs::rename(&reverting, path(dir, ""));
Err(format!("{why}, but Caddy could not be put back yet: {e}"))
}
}
}
/// `ianitor-control caddy-revert`: after control stops, a trial still out goes back at once
/// (retried a few times, 1, 2, 4 and 8 s apart). With another engine serving there is no
/// Caddy trial: a deadline left behind is cleared and nothing fails.
pub async fn revert_after_stop(cfg: &Config) -> Result<bool, String> {
let dir = &cfg.state_dir;
if !caddy_serves(cfg) {
disarm(dir);
return Ok(false);
}
resume_half_done(dir);
let mut wait = 1;
loop {
let r = match verdict(
armed(dir).as_ref(),
confirmed(dir),
crate::util::now(),
true,
) {
Verdict::Revert => revert(cfg, "control stopped with a trial loaded into Caddy").await,
Verdict::Nothing => Ok(false),
};
match r {
Err(e) if wait <= 8 => {
log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {wait} s");
tokio::time::sleep(std::time::Duration::from_secs(wait)).await;
wait *= 2;
}
other => return other,
}
}
}
/// One tick of `ianitor-control caddy-guard`.
pub async fn tick(cfg: &Config) -> Result<bool, String> {
let dir = &cfg.state_dir;
if !caddy_serves(cfg) {
return Ok(false);
}
resume_half_done(dir);
match verdict(
armed(dir).as_ref(),
confirmed(dir),
crate::util::now(),
false,
) {
Verdict::Revert => revert(cfg, "a trial under Caddy passed its deadline unconfirmed").await,
Verdict::Nothing => Ok(false),
}
}
/// `ianitor-control caddy-guard`: forever, once a second; after a failed revert it tries
/// again with a growing pause (2, 4, … 30 s).
pub async fn run(cfg: Config) -> Result<(), String> {
log::info!(target: "ianitor::caddy-guard", "watching {} for trials under Caddy", cfg.state_dir.display());
let mut pause = 1u64;
loop {
match tick(&cfg).await {
Ok(_) => pause = 1,
Err(e) => {
pause = (pause * 2).min(30);
log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {pause} s");
}
}
tokio::time::sleep(std::time::Duration::from_secs(pause)).await;
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
fn d(deadline: u64) -> TrialDeadline {
TrialDeadline {
apply_id: "ch_1".into(),
deadline,
}
}
#[test]
fn the_guard_reverts_only_an_unconfirmed_trial_past_its_deadline() {
assert_eq!(verdict(None, false, 100, false), Verdict::Nothing);
assert_eq!(verdict(Some(&d(100)), false, 100, false), Verdict::Nothing);
assert_eq!(verdict(Some(&d(100)), false, 101, false), Verdict::Revert);
assert_eq!(verdict(Some(&d(100)), true, 500, false), Verdict::Nothing);
}
#[test]
fn after_a_stop_an_unconfirmed_trial_goes_back_at_once() {
assert_eq!(verdict(Some(&d(1000)), false, 1, true), Verdict::Revert);
assert_eq!(verdict(Some(&d(1000)), true, 1, true), Verdict::Nothing);
assert_eq!(verdict(None, false, 1, true), Verdict::Nothing);
}
#[test]
fn control_and_the_guard_cannot_both_have_the_deadline() {
let dir = std::env::temp_dir().join(format!("ianitor-guard-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
arm(&dir, "ch_1", 10).unwrap();
assert_eq!(armed(&dir), Some(d(10)));
// The guard took it (as `revert` does): control's claim fails.
std::fs::rename(path(&dir, ""), path(&dir, ".expired")).unwrap();
assert!(!claim(&dir));
disarm(&dir);
// Control claims first: nothing is left for the guard.
arm(&dir, "ch_1", 10).unwrap();
assert!(claim(&dir));
assert!(armed(&dir).is_none());
assert!(std::fs::rename(path(&dir, ""), path(&dir, ".expired")).is_err());
disarm(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
}
+230 -22
View File
@@ -4,7 +4,9 @@
//! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep //! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep
//! working under Caddy): loading a config through Caddy's admin API on its Unix socket //! working under Caddy): loading a config through Caddy's admin API on its Unix socket
//! (`POST /load`, the whole JSON), and probing a host *through* Caddy for the health watch. //! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host
//! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch,
//! judged like edge's), and the certificate Caddy serves.
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::Path; use std::path::Path;
@@ -13,20 +15,14 @@ use std::time::{Duration, Instant};
const TIMEOUT: Duration = Duration::from_secs(10); const TIMEOUT: Duration = Duration::from_secs(10);
/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the /// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked).
/// old one). async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec<u8>), String> {
pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
#[cfg(unix)] #[cfg(unix)]
{ {
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
let head = format!(
"POST /load HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n",
config.len()
);
let exchange = async { let exchange = async {
let mut s = tokio::net::UnixStream::connect(socket).await?; let mut s = tokio::net::UnixStream::connect(socket).await?;
s.write_all(head.as_bytes()).await?; s.write_all(request).await?;
s.write_all(config).await?;
let mut buf = Vec::new(); let mut buf = Vec::new();
s.read_to_end(&mut buf).await?; s.read_to_end(&mut buf).await?;
Ok::<_, std::io::Error>(buf) Ok::<_, std::io::Error>(buf)
@@ -35,29 +31,69 @@ pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
.await .await
.map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())? .map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())?
.map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?; .map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?;
let text = String::from_utf8_lossy(&buf); let split = buf
let status: u16 = text .windows(4)
.position(|w| w == b"\r\n\r\n")
.ok_or("no answer from Caddy's admin API")?;
let head = String::from_utf8_lossy(&buf[..split]);
let status: u16 = head
.split(' ') .split(' ')
.nth(1) .nth(1)
.and_then(|s| s.parse().ok()) .and_then(|s| s.parse().ok())
.ok_or("no answer from Caddy's admin API")?; .ok_or("no answer from Caddy's admin API")?;
if (200..300).contains(&status) { Ok((status, buf[split + 4..].to_vec()))
Ok(())
} else {
let body = text.split("\r\n\r\n").nth(1).unwrap_or("").trim();
Err(format!(
"Caddy refused the config ({status}): {}",
body.chars().take(400).collect::<String>()
))
}
} }
#[cfg(not(unix))] #[cfg(not(unix))]
{ {
let _ = (socket, config); let _ = (socket, request);
Err("Caddy's admin socket needs Unix".into()) Err("Caddy's admin socket needs Unix".into())
} }
} }
/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the
/// old one). `Cache-Control: must-revalidate` makes Caddy load it even when it is the same as
/// the running one, so certificate and device files are read again (without it an identical
/// config is a no-op: QC round 2, B1; `qc_reloading_the_same_caddy_json_rereads_the_certificate_files`).
pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
let mut req = format!(
"POST /load HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n",
config.len()
)
.into_bytes();
req.extend_from_slice(config);
let (status, body) = admin(socket, &req).await?;
if (200..300).contains(&status) {
Ok(())
} else {
Err(format!(
"Caddy refused the config ({status}): {}",
String::from_utf8_lossy(&body)
.trim()
.chars()
.take(400)
.collect::<String>()
))
}
}
/// The config Caddy runs now.
pub async fn running_config(socket: &Path) -> Result<serde_json::Value, String> {
let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?;
if status != 200 {
return Err(format!(
"Caddy's admin API answered {status} to GET /config/"
));
}
serde_json::from_slice(&body).map_err(|e| format!("Caddy's running config is not JSON: {e}"))
}
/// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter).
pub async fn runs(socket: &Path, config: &[u8]) -> Result<bool, String> {
let want: serde_json::Value =
serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?;
Ok(running_config(socket).await? == want)
}
/// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host. /// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum Probe { pub enum Probe {
@@ -156,3 +192,175 @@ pub async fn probe(addr: SocketAddr, host: &str, path: &str) -> Probe {
)), )),
} }
} }
/// SHA-256 (hex) of the leaf certificate Caddy serves for this name: after a reload, whether
/// Caddy really read the certificate files again (the backstop for B1).
pub async fn served_cert_sha256(addr: SocketAddr, host: &str) -> Result<String, String> {
let run = async {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let cfg = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.dangerous()
.with_custom_certificate_verifier(Arc::new(AnyCert))
.with_no_client_auth();
let name =
rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?;
let tcp = tokio::net::TcpStream::connect(addr)
.await
.map_err(|e| e.to_string())?;
let tls = tokio_rustls::TlsConnector::from(Arc::new(cfg))
.connect(name, tcp)
.await
.map_err(|e| e.to_string())?;
let (_, conn) = tls.get_ref();
let leaf = conn
.peer_certificates()
.and_then(|c| c.first())
.ok_or("Caddy sent no certificate")?;
Ok::<_, String>(crate::util::sha256_hex(leaf.as_ref()))
};
tokio::time::timeout(Duration::from_secs(5), run)
.await
.map_err(|_| "Caddy did not finish the handshake within 5 s".to_owned())?
}
/// One health probe of an upstream, made by control while Caddy serves, with edge's rules
/// (crates/edge/src/health.rs): a host with a health check gets `GET <path>` with the upstream
/// address as Host and passes on 2xx; a host without one gets `GET /` with its own name as
/// Host and passes on any answer below 500. 5 s timeout. `kind` uses edge's words.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpstreamProbe {
pub ok: bool,
pub kind: Option<&'static str>,
pub status: Option<u16>,
pub latency_ms: Option<u64>,
}
fn status_kind(status: u16) -> &'static str {
match status {
300..=399 => "redirect",
401 | 403 => "sign_in",
404 => "not_found",
500..=599 => "server_error",
_ => "bad_answer",
}
}
fn io_kind(e: &std::io::Error) -> &'static str {
use std::io::ErrorKind as K;
match e.kind() {
K::ConnectionRefused | K::ConnectionReset | K::ConnectionAborted | K::BrokenPipe => {
"refused"
}
K::TimedOut => "timeout",
_ if e.to_string().contains("lookup") => "name",
_ => "refused",
}
}
/// The roots an `https://` upstream is checked against: the system bundle (`SSL_CERT_FILE`,
/// else the usual Debian/NixOS path), read once.
fn system_roots() -> Arc<rustls::RootCertStore> {
static ROOTS: std::sync::OnceLock<Arc<rustls::RootCertStore>> = std::sync::OnceLock::new();
ROOTS
.get_or_init(|| {
let mut store = rustls::RootCertStore::empty();
let path = std::env::var("SSL_CERT_FILE")
.unwrap_or_else(|_| "/etc/ssl/certs/ca-certificates.crt".into());
if let Ok(pem) = std::fs::read_to_string(path) {
for der in ianitor_core::pki::chain_der(&pem).unwrap_or_default() {
let _ = store.add(rustls_pki_types::CertificateDer::from(der));
}
}
Arc::new(store)
})
.clone()
}
pub async fn probe_upstream(
u: &ianitor_core::Upstream,
path: &str,
host_header: &str,
watch_only: bool,
) -> UpstreamProbe {
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
let started = Instant::now();
let fail = |kind: &'static str| UpstreamProbe {
ok: false,
kind: Some(kind),
status: None,
latency_ms: None,
};
async fn ask<S: AsyncRead + AsyncWrite + Unpin>(
mut s: S,
req: &[u8],
) -> Result<Option<u16>, std::io::Error> {
s.write_all(req).await?;
let mut head = [0u8; 64];
let mut n = 0;
while n < 13 {
let k = s.read(&mut head[n..]).await?;
if k == 0 {
break;
}
n += k;
}
Ok(String::from_utf8_lossy(&head[..n])
.split(' ')
.nth(1)
.and_then(|x| x.parse::<u16>().ok()))
}
let req = format!(
"GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n"
);
let run = async {
let tcp = match tokio::net::TcpStream::connect(u.authority()).await {
Ok(t) => t,
Err(e) => return Err(io_kind(&e)),
};
if u.scheme == ianitor_core::Scheme::Https {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let Ok(b) = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
else {
return Err("tls");
};
let cfg = b
.with_root_certificates(system_roots())
.with_no_client_auth();
let Ok(name) = rustls_pki_types::ServerName::try_from(u.host_str()) else {
return Err("name");
};
let tls = match tokio_rustls::TlsConnector::from(Arc::new(cfg))
.connect(name, tcp)
.await
{
Ok(t) => t,
Err(_) => return Err("tls"),
};
ask(tls, req.as_bytes()).await.map_err(|e| io_kind(&e))
} else {
ask(tcp, req.as_bytes()).await.map_err(|e| io_kind(&e))
}
};
match tokio::time::timeout(Duration::from_secs(5), run).await {
Err(_) => fail("timeout"),
Ok(Err(kind)) => fail(kind),
Ok(Ok(None)) => fail("bad_answer"),
Ok(Ok(Some(status))) => {
let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
let ok = if watch_only {
(100..500).contains(&status)
} else {
(200..300).contains(&status)
};
UpstreamProbe {
ok,
kind: (!ok).then(|| status_kind(status)),
status: Some(status),
latency_ms: Some(latency),
}
}
}
}
+18 -5
View File
@@ -164,6 +164,9 @@ pub struct Control {
pub(crate) apply_lock: tokio::sync::Mutex<()>, pub(crate) apply_lock: tokio::sync::Mutex<()>,
/// Held while an engine is switched or told to reload its device or certificate files. /// Held while an engine is switched or told to reload its device or certificate files.
pub(crate) engine_lock: tokio::sync::Mutex<()>, pub(crate) engine_lock: tokio::sync::Mutex<()>,
/// Serialises reading the device records and writing the device files (never held
/// across an apply or a switch).
pub(crate) devices_lock: tokio::sync::Mutex<()>,
/// Why the device files are not (yet) in force, until a retry succeeds. /// Why the device files are not (yet) in force, until a retry succeeds.
pub devices_problem: Mutex<Option<String>>, pub devices_problem: Mutex<Option<String>>,
} }
@@ -275,6 +278,7 @@ impl Control {
pause_saved: std::sync::atomic::AtomicBool::new(true), pause_saved: std::sync::atomic::AtomicBool::new(true),
apply_lock: tokio::sync::Mutex::new(()), apply_lock: tokio::sync::Mutex::new(()),
engine_lock: tokio::sync::Mutex::new(()), engine_lock: tokio::sync::Mutex::new(()),
devices_lock: tokio::sync::Mutex::new(()),
devices_problem: Mutex::new(None), devices_problem: Mutex::new(None),
cfg, cfg,
}); });
@@ -1541,8 +1545,12 @@ impl Control {
remove_if_exists(&p).map_err(|e| e.to_string())?; remove_if_exists(&p).map_err(|e| e.to_string())?;
} }
if caddy { if caddy {
// Caddy must run caddy.json again, the last good config. // Caddy must run caddy.json again, the last good config (with the device files as
// they are now); then no trial is out any more. Under the engine lock, so a device
// change that saw the trial and left the reload to this point is not lost.
let _engine = self.engine_lock.lock().await;
self.caddy_reload().await?; self.caddy_reload().await?;
crate::caddy_guard::disarm(&self.cfg.state_dir);
return Ok(rev); return Ok(rev);
} }
// Edge must now run edge.json, the last good config. If it confirmed the trial after // Edge must now run edge.json, the last good config. If it confirmed the trial after
@@ -1703,10 +1711,15 @@ impl Control {
self.unpause(); self.unpause();
self.sync_files().await; self.sync_files().await;
} }
if self.engine_running() == "caddy" if self.engine_running() == "caddy" {
&& let Err(e) = self.caddy_reload().await match self.caddy_reload().await {
{ Ok(()) => crate::caddy_guard::disarm(&self.cfg.state_dir),
log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}"); Err(e) => {
log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}")
}
}
} else {
crate::caddy_guard::disarm(&self.cfg.state_dir);
} }
if let Err(e) = self.shares.ensure_revocation_file() { if let Err(e) = self.shares.ensure_revocation_file() {
log::error!(target: "ianitor::share", "{e}"); log::error!(target: "ianitor::share", "{e}");
+308 -112
View File
@@ -3,13 +3,44 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Applies while Caddy serves (Mark, 2026-11-08: changes keep working under Caddy). The same //! Applies while Caddy serves (Mark, 2026-11-08: changes keep working under Caddy). The same
//! pipeline and journal as with edge; only the trial, the watch and the revert differ: the //! pipeline and journal as with edge; only the trial, the watch and the revert differ:
//! trial is loaded into Caddy through its admin socket, the touched hosts are probed through //!
//! Caddy, and a revert loads caddy.json (the last good config) again. //! - the trial is loaded into Caddy through its admin socket, after its deadline is armed
//! (crate::caddy_guard: a crashed or hung control cannot leave it serving);
//! - the watch judges health the way edge does (QC round 2, M1): control probes the upstreams
//! itself with edge's rules, and the probe *through* Caddy only asks whether Caddy answers
//! at all (any status counts, also its auth redirect, 401, 403 or 421);
//! - every round checks that Caddy still runs the trial (M2: a reload by anyone else drops it);
//! - a revert loads caddy.json (the last good config) again; a confirm claims the deadline,
//! then promotes, loads caddy.json and checks that Caddy runs it.
use std::net::SocketAddr;
use super::*; use super::*;
use crate::caddy_guard;
use crate::caddy_link::{self, Probe}; use crate::caddy_link::{self, Probe};
/// Where control reaches Caddy's HTTPS listener (its own machine).
fn local(addr: SocketAddr) -> SocketAddr {
if addr.ip().is_unspecified() {
let ip: std::net::IpAddr = if addr.is_ipv6() {
std::net::Ipv6Addr::LOCALHOST.into()
} else {
std::net::Ipv4Addr::LOCALHOST.into()
};
SocketAddr::new(ip, addr.port())
} else {
addr
}
}
/// How one host is probed (edge's rules, crates/edge/src/health.rs).
struct Rule {
upstreams: Vec<ianitor_core::Upstream>,
path: String,
has_check: bool,
}
impl Control { impl Control {
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`). /// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> { pub fn caddy_socket(&self) -> Option<std::path::PathBuf> {
@@ -20,14 +51,87 @@ impl Control {
.map(std::path::PathBuf::from) .map(std::path::PathBuf::from)
} }
/// Load caddy.json (the last good config) into the running Caddy. /// Load caddy.json (the last good config) into the running Caddy, even when it is the
/// config Caddy already runs (so it reads its files again), and check that it runs it.
pub async fn caddy_reload(&self) -> Result<(), String> { pub async fn caddy_reload(&self) -> Result<(), String> {
let sock = self let sock = self
.caddy_socket() .caddy_socket()
.ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?; .ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?;
let text = std::fs::read(&self.cfg.caddy.config) let text = std::fs::read(&self.cfg.caddy.config)
.map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?; .map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?;
caddy_link::load(&sock, &text).await caddy_link::load(&sock, &text).await?;
if !caddy_link::runs(&sock, &text).await? {
return Err("Caddy took the config but does not run it".into());
}
Ok(())
}
/// `caddy_reload`, then the backstop for certificate and device changes: Caddy must serve
/// the certificate that is on disk now for a Domi host (it proves the files were read).
pub async fn caddy_reload_checked(&self) -> Result<(), String> {
self.caddy_reload().await?;
let Ok((_, _, model)) = self.head_model() else {
return Ok(());
};
let Some(h) = model
.hosts()
.iter()
.find(|h| h.tls == ianitor_core::TlsMode::Domi)
else {
return Ok(());
};
let file = std::path::Path::new(&self.cfg.caddy_compile().cert_dir)
.join(format!("{}.crt", h.hostname));
let want = std::fs::read_to_string(&file)
.ok()
.and_then(|pem| ianitor_core::pki::chain_der(&pem).ok())
.and_then(|c| c.into_iter().next())
.map(|der| crate::util::sha256_hex(&der))
.ok_or_else(|| format!("cannot read {}", file.display()))?;
let addr = local(self.cfg.caddy_compile().https_listen);
let got = caddy_link::served_cert_sha256(addr, h.hostname.as_str()).await?;
if got != want {
return Err(format!(
"Caddy still serves an older certificate for {} after the reload",
h.hostname
));
}
Ok(())
}
fn caddy_rules(&self, plan: &Plan) -> BTreeMap<String, Rule> {
plan.model
.hosts()
.iter()
.map(|h| {
(
h.hostname.to_string(),
Rule {
upstreams: h.upstreams.clone(),
path: h
.health_check
.as_ref()
.map_or("/".to_owned(), |c| c.path.clone()),
has_check: h.health_check.is_some(),
},
)
})
.collect()
}
/// One round of edge-style upstream probes for one host; `(address, probe)` per upstream.
async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> {
let mut out = Vec::new();
for u in &r.upstreams {
let host_header = if r.has_check {
u.authority()
} else {
hostname.to_owned()
};
let p = caddy_link::probe_upstream(u, &r.path, &host_header, !r.has_check).await;
out.push((u.authority(), p));
}
out
} }
pub(super) async fn run_under_caddy( pub(super) async fn run_under_caddy(
@@ -56,27 +160,10 @@ impl Control {
.filter(|h| plan.target.host(h).is_some()) .filter(|h| plan.target.host(h).is_some())
.cloned() .cloned()
.collect(); .collect();
let addr = self.cfg.caddy_compile().https_listen; let addr = local(self.cfg.caddy_compile().https_listen);
let path_of = |h: &str| -> (String, bool) { let rules = self.caddy_rules(plan);
plan.model // A host whose upstreams already failed before the change is no reason to revert
.hosts() // (edge: `down_hosts`). Judged by the upstreams, as edge does.
.iter()
.find(|x| x.hostname.as_str() == h)
.and_then(|x| x.health_check.as_ref())
.map(|hc| (hc.path.clone(), true))
.unwrap_or_else(|| ("/".to_owned(), false))
};
let good = |p: &Probe, has_check: bool| match p {
Probe::Status(s) => {
if has_check {
(200..300).contains(s)
} else {
*s < 500
}
}
Probe::NoAnswer(_) => false,
};
// A host that already failed through Caddy before the change is no reason to revert.
let existed: BTreeSet<String> = self let existed: BTreeSet<String> = self
.repo .repo
.tree(&j.base) .tree(&j.base)
@@ -90,16 +177,33 @@ impl Control {
.unwrap_or_default(); .unwrap_or_default();
let mut was_down = BTreeSet::new(); let mut was_down = BTreeSet::new();
for h in &existed { for h in &existed {
let (path, check) = path_of(h); if let Some(r) = rules.get(h)
if !good(&caddy_link::probe(addr, h, &path).await, check) { && !Self::probe_host(h, r).await.iter().any(|(_, p)| p.ok)
{
was_down.insert(h.clone()); was_down.insert(h.clone());
} }
} }
if let Err(e) = caddy_link::load(&sock, caddy_text.as_bytes()).await { let window = self.cfg.watch_secs;
return self // The deadline goes out before the trial does (crate::caddy_guard).
.revert(id, &j, fail("apply.failed.reload", e), "failed") let deadline = now() + window + self.cfg.trial_margin_secs + 5;
.await; // Under the engine lock: a device change that looked a moment ago saw no trial and
// reloads caddy.json; it must not land after the trial is in.
let loaded = {
let _engine = self.engine_lock.lock().await;
match caddy_guard::arm(&self.cfg.state_dir, id, deadline) {
Err(e) => {
let mut r = reason("internal", Params::new());
r.detail = Some(e);
Err((r, "failed"))
}
Ok(()) => caddy_link::load(&sock, caddy_text.as_bytes())
.await
.map_err(|e| (fail("apply.failed.reload", e), "failed")),
}
};
if let Err((r, state)) = loaded {
return self.revert(id, &j, r, state).await;
} }
j.stage = "trial_loaded".into(); j.stage = "trial_loaded".into();
if let Err(e) = self.journal(&j) { if let Err(e) = self.journal(&j) {
@@ -115,7 +219,6 @@ impl Control {
.filter(|h| !was_down.contains(*h)) .filter(|h| !was_down.contains(*h))
.cloned() .cloned()
.collect(); .collect();
let window = self.cfg.watch_secs;
let mut kept_reason = if watch_hosts.is_empty() { let mut kept_reason = if watch_hosts.is_empty() {
reason( reason(
"apply.kept.removed", "apply.kept.removed",
@@ -130,10 +233,10 @@ impl Control {
]), ]),
) )
}; };
let ends = now() + window;
if judged.is_empty() { if judged.is_empty() {
self.update(id, |r| r.step("watch", "skipped")); self.update(id, |r| r.step("watch", "skipped"));
} else { } else {
let ends = now() + window;
self.update(id, |r| { self.update(id, |r| {
r.state = "watching".into(); r.state = "watching".into();
r.step("watch", "running"); r.step("watch", "running");
@@ -148,86 +251,19 @@ impl Control {
.collect(), .collect(),
}); });
}); });
// hostname -> (passed, failed, failed in a row, last probe) }
let mut stats: BTreeMap<String, (u32, u32, u32, Option<Probe>)> = judged if let Err(r) = self
.caddy_watch(id, &sock, caddy_text, &judged, &rules, plan, addr, ends)
.await
{
return self.revert(id, &j, r, "reverted").await;
}
if !judged.is_empty() {
let no_check: Vec<String> = judged
.iter() .iter()
.map(|h| (h.clone(), (0, 0, 0, None))) .filter(|h| rules.get(*h).is_some_and(|r| !r.has_check))
.cloned()
.collect(); .collect();
let no_check: Vec<String> = judged.iter().filter(|h| !path_of(h).1).cloned().collect();
loop {
for h in &judged {
let (path, check) = path_of(h);
let p = caddy_link::probe(addr, h, &path).await;
let ok = good(&p, check);
if let Some(s) = stats.get_mut(h) {
if ok {
s.0 += 1;
s.2 = 0;
} else {
s.1 += 1;
s.2 += 1;
}
s.3 = Some(p);
}
}
self.update(id, |r| {
if let Some(w) = &mut r.watch {
for wh in &mut w.hosts {
if let Some(s) = stats.get(&wh.hostname) {
wh.passed = s.0;
wh.failed = s.1;
wh.total = s.0 + s.1;
}
}
}
});
let over = now() >= ends;
let failing = stats
.iter()
.find(|(_, s)| s.2 >= 3 || (over && s.2 > 0))
.map(|(h, s)| (h.clone(), s.clone()));
if let Some((h, s)) = failing {
let upstream = plan
.model
.hosts()
.iter()
.find(|x| x.hostname.as_str() == h)
.and_then(|x| x.upstreams.first())
.map(|u| u.to_string())
.unwrap_or_default();
let mut p = messages::params([
("hostname", h.clone()),
("verb", plan.verb.into()),
("upstream", upstream.clone()),
("count", s.1.to_string()),
("of", (s.0 + s.1).to_string()),
("seconds", window.to_string()),
]);
let (code, detail) = match &s.3 {
Some(Probe::Status(st)) => {
p.insert("status".into(), st.to_string());
(
"apply.reverted.server_error",
format!("through Caddy: HTTP {st}"),
)
}
Some(Probe::NoAnswer(e)) => {
("apply.reverted.no_answer", format!("through Caddy: {e}"))
}
None => ("apply.reverted.no_answer", String::new()),
};
let mut r = reason(code, p);
r.hostname = Some(h.clone());
r.upstream = Some(upstream);
r.field = Some("upstreams[0]".into());
r.detail = Some(detail);
return self.revert(id, &j, r, "reverted").await;
}
if over {
break;
}
tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await;
}
if !no_check.is_empty() && no_check.len() == judged.len() { if !no_check.is_empty() && no_check.len() == judged.len() {
kept_reason = reason( kept_reason = reason(
"apply.kept.no_watch", "apply.kept.no_watch",
@@ -237,6 +273,10 @@ impl Control {
self.update(id, |r| r.step("watch", "done")); self.update(id, |r| r.step("watch", "done"));
} }
crash::point("watched"); crash::point("watched");
// Confirmed first, then the deadline is claimed (fix round 3): a crash in between
// leaves the deadline armed *and* the journal confirmed, so the guard and caddy-revert
// leave the trial alone and recovery promotes it. The other order would leave a window
// with nothing armed and nothing confirmed, where nobody reverts Caddy.
j.stage = "confirmed".into(); j.stage = "confirmed".into();
if let Err(e) = self.journal(&j) { if let Err(e) = self.journal(&j) {
let mut r = reason("internal", Params::new()); let mut r = reason("internal", Params::new());
@@ -244,7 +284,22 @@ impl Control {
return self.revert(id, &j, r, "failed").await; return self.revert(id, &j, r, "failed").await;
} }
crash::point("confirmed"); crash::point("confirmed");
// From the claim to Caddy running the promoted caddy.json, no device reload may load
// the old caddy.json in between.
let engine = self.engine_lock.lock().await;
// The guard may have reverted a trial that ran past its deadline (a stalled control):
// then this change is not kept.
if !caddy_guard::claim(&self.cfg.state_dir) {
drop(engine);
let mut r = reason("apply.interrupted", Params::new());
r.detail = Some(
"the trial ran past its deadline, so Caddy went back to the last good config"
.into(),
);
return self.revert(id, &j, r, "reverted").await;
}
if let Err(e) = self.promote() { if let Err(e) = self.promote() {
drop(engine);
log::error!(target: "ianitor::apply", "cannot write the config files: {e}"); log::error!(target: "ianitor::apply", "cannot write the config files: {e}");
let mut p = reason("control.files_unwritten", Params::new()); let mut p = reason("control.files_unwritten", Params::new());
p.detail = Some(e.to_string()); p.detail = Some(e.to_string());
@@ -258,6 +313,12 @@ impl Control {
return; return;
} }
crash::point("promoted"); crash::point("promoted");
// caddy.json now holds the change: Caddy loads what was written (with the device and
// certificate files as they are now) and must run it.
if let Err(e) = self.caddy_reload().await {
log::error!(target: "ianitor::apply", "Caddy did not load the promoted caddy.json: {e}");
}
drop(engine);
let push_step = self.push_step(); let push_step = self.push_step();
self.update(id, |r| r.step("push", push_step)); self.update(id, |r| r.step("push", push_step));
self.finish(id, "kept", Some(kept_reason), Vec::new()); self.finish(id, "kept", Some(kept_reason), Vec::new());
@@ -267,4 +328,139 @@ impl Control {
} }
self.push_wake.notify_one(); self.push_wake.notify_one();
} }
/// The watch under Caddy until `ends`: the reason to revert, if any.
#[allow(clippy::too_many_arguments)]
async fn caddy_watch(
&self,
id: &str,
sock: &std::path::Path,
trial: &str,
judged: &[String],
rules: &BTreeMap<String, Rule>,
plan: &Plan,
addr: SocketAddr,
ends: u64,
) -> Result<(), Reason> {
let mut seen: HashMap<(String, String), BTreeMap<u64, Check>> = HashMap::new();
let mut seq = 0u64;
let mut silent: BTreeMap<String, (u32, String)> = BTreeMap::new();
let paths: HashMap<String, String> = rules
.iter()
.map(|(h, r)| (h.clone(), r.path.clone()))
.collect();
let mut first = true;
loop {
// Anyone else's reload (a device change, a restart of caddy-fallback) drops the
// trial: then this is not a verdict on the change.
match caddy_link::runs(sock, trial.as_bytes()).await {
Ok(true) => {}
Ok(false) => {
let mut r = reason("apply.reverted.edge_lost", Params::new());
r.detail = Some("Caddy no longer runs the trial config".into());
return Err(r);
}
Err(e) => {
let mut r = reason("apply.reverted.edge_lost", Params::new());
r.detail = Some(e);
return Err(r);
}
}
if first {
crash::point("watching");
first = false;
}
let mut counts = Vec::new();
for h in judged {
let Some(rule) = rules.get(h) else { continue };
// Does Caddy answer for this host at all? Any status does.
match caddy_link::probe(addr, h, "/").await {
Probe::Status(_) => {
silent.remove(h);
}
Probe::NoAnswer(e) => {
let s = silent.entry(h.clone()).or_insert((0, String::new()));
s.0 += 1;
s.1 = e;
}
}
if let Some((n, e)) = silent.get(h)
&& *n >= 3
{
let mut r = reason(
"apply.reverted.no_answer",
messages::params([
("hostname", h.clone()),
("verb", plan.verb.into()),
("seconds", self.cfg.watch_secs.to_string()),
]),
);
r.hostname = Some(h.clone());
r.detail = Some(format!("Caddy does not answer for {h}: {e}"));
return Err(r);
}
for (address, p) in Self::probe_host(h, rule).await {
seq += 1;
seen.entry((h.clone(), address)).or_default().insert(
seq,
Check {
seq,
at: now(),
ok: p.ok,
source: if rule.has_check {
"health_check".into()
} else {
"watch".into()
},
kind: p.kind.map(str::to_owned),
status: p.status,
latency_ms: p.latency_ms,
},
);
}
let mut passed = 0u32;
let mut failed = 0u32;
let mut all_failing = !rule.upstreams.is_empty();
for ((host, _), m) in &seen {
if host != h {
continue;
}
passed += m.values().filter(|c| c.ok).count() as u32;
failed += m.values().filter(|c| !c.ok).count() as u32;
if m.values().rev().take_while(|c| !c.ok).count() < 3 {
all_failing = false;
}
}
counts.push(WatchHost {
hostname: h.clone(),
passed,
failed,
total: passed + failed,
});
if all_failing {
return Err(self.revert_reason(h, plan, &seen, &paths));
}
}
self.update(id, |r| {
if let Some(w) = &mut r.watch {
w.hosts = counts;
}
});
if now() >= ends {
break;
}
tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await;
}
// At the end, as with edge: every judged host needs an upstream whose last probe passed.
for h in judged {
let last_ok = seen
.iter()
.filter(|((host, _), _)| host == h)
.any(|(_, m)| m.values().next_back().is_some_and(|c| c.ok));
if !last_ok {
return Err(self.revert_reason(h, plan, &seen, &paths));
}
}
Ok(())
}
} }
+1
View File
@@ -7,6 +7,7 @@
//! edge keeps serving the last good config. //! edge keeps serving the last good config.
pub mod api; pub mod api;
pub mod caddy_guard;
pub mod caddy_link; pub mod caddy_link;
pub mod config; pub mod config;
pub mod crash; pub mod crash;
+23 -1
View File
@@ -30,7 +30,8 @@ fn usage() -> ExitCode {
eprintln!( eprintln!(
"usage: ianitor-control --config <control.toml> | --dev [--edge-bin <path>] | \ "usage: ianitor-control --config <control.toml> | --dev [--edge-bin <path>] | \
token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) | \ token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) | \
token list (...) | token revoke <id> (...) | openapi | check --config <c>" token list (...) | token revoke <id> (...) | openapi | check --config <c> | \
caddy-revert --config <c> | caddy-guard --config <c>"
); );
ExitCode::from(2) ExitCode::from(2)
} }
@@ -395,6 +396,27 @@ fn main() -> ExitCode {
Ok(()) Ok(())
} }
Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")), Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")),
// Caddy trial deadline (ianitor_control::caddy_guard): after control stops, and the guard.
Some(verb @ ("caddy-revert" | "caddy-guard")) => match args
.iter()
.position(|a| a == "--config")
.and_then(|i| args.get(i + 1))
{
Some(p) => match Config::load(&PathBuf::from(p)) {
Ok(cfg) if verb == "caddy-guard" => {
rt.block_on(ianitor_control::caddy_guard::run(cfg))
}
Ok(cfg) => rt
.block_on(ianitor_control::caddy_guard::revert_after_stop(&cfg))
.map(|done| {
if done {
eprintln!("Caddy is back on the last good config.");
}
}),
Err(e) => Err(e.to_string()),
},
None => return usage(),
},
Some("--dev") => rt.block_on(dev::run(&args[1..])), Some("--dev") => rt.block_on(dev::run(&args[1..])),
Some("--config") => match args.get(1) { Some("--config") => match args.get(1) {
Some(p) => match Config::load(&PathBuf::from(p)) { Some(p) => match Config::load(&PathBuf::from(p)) {
+80 -9
View File
@@ -218,9 +218,11 @@ fn bundle_password() -> Result<String, PkiFail> {
/// Private keys in `dir` that are not control's own: control refuses to run with one in its /// Private keys in `dir` that are not control's own: control refuses to run with one in its
/// state directory (ROADMAP §1.2: the root is never on the server). Found by content (any /// state directory (ROADMAP §1.2: the root is never on the server). Found by content (any
/// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`, `*root*.pem` with /// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`); the only keys
/// a key); the only keys allowed are `pki/intermediate.key`, `pki/pending-*.key` and /// allowed are `pki/intermediate.key`, `pki/pending-*.key` and `pki/devices/*.key`, and those
/// `pki/devices/*.key`, which control writes encrypted itself. /// must hold exactly one key in control's own encrypted armour, nothing else. A symbolic link
/// is never followed and never skipped: it is reported. Git's object store (`*.git/objects`,
/// compressed history) is not read.
pub fn root_key_files(dir: &Path) -> Vec<PathBuf> { pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
let allowed = |p: &Path| -> bool { let allowed = |p: &Path| -> bool {
let Ok(rel) = p.strip_prefix(dir) else { let Ok(rel) = p.strip_prefix(dir) else {
@@ -242,6 +244,12 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
_ => false, _ => false,
} }
}; };
let own_armour = |b: &[u8]| -> bool {
let t = String::from_utf8_lossy(b);
let begins = t.matches("-----BEGIN ").count();
let ours = t.matches(OWN_BEGIN).count();
begins == 1 && ours == 1 && t.matches(KEY_MARK).count() == 2
};
let mut found = Vec::new(); let mut found = Vec::new();
let mut stack = vec![(dir.to_path_buf(), 0)]; let mut stack = vec![(dir.to_path_buf(), 0)];
while let Some((d, depth)) = stack.pop() { while let Some((d, depth)) = stack.pop() {
@@ -250,21 +258,41 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
}; };
for e in rd.flatten() { for e in rd.flatten() {
let p = e.path(); let p = e.path();
let Ok(meta) = e.metadata() else { continue }; // symlink_metadata: a link is looked at, not followed.
let Ok(meta) = std::fs::symlink_metadata(&p) else {
continue;
};
if meta.file_type().is_symlink() {
found.push(p);
continue;
}
if meta.is_dir() { if meta.is_dir() {
if depth < 8 { let git_objects =
e.file_name() == "objects" && d.extension().is_some_and(|x| x == "git");
if depth < 8 && !git_objects {
stack.push((p, depth + 1)); stack.push((p, depth + 1));
} }
continue; continue;
} }
if !meta.is_file() || allowed(&p) { if !meta.is_file() {
continue;
}
let read = || {
(meta.len() <= 1 << 20)
.then(|| std::fs::read(&p).ok())
.flatten()
};
if allowed(&p) {
// Control's own key files: one key, in control's encrypted armour.
if !read().is_some_and(|b| own_armour(&b)) {
found.push(p);
}
continue; continue;
} }
let name = e.file_name().to_string_lossy().to_ascii_lowercase(); let name = e.file_name().to_string_lossy().to_ascii_lowercase();
let by_name = name.contains("root") && name.contains("key"); let by_name = name.contains("root") && name.contains("key");
let by_content = meta.len() <= 1 << 20 let by_content =
&& std::fs::read(&p) read().is_some_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes()));
.is_ok_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes()));
if by_name || by_content { if by_name || by_content {
found.push(p); found.push(p);
} }
@@ -275,6 +303,7 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
// Split so that this file does not match the pre-commit hook itself. // Split so that this file does not match the pre-commit hook itself.
const KEY_MARK: &str = concat!("PRIVATE ", "KEY-----"); const KEY_MARK: &str = concat!("PRIVATE ", "KEY-----");
const OWN_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----");
impl Pki { impl Pki {
/// Open the CA state. The root certificate must be a CA and self-signed; the password /// Open the CA state. The root certificate must be a CA and self-signed; the password
@@ -1182,3 +1211,45 @@ pub fn cli_wait(state_dir: &Path, rid: &str, since: u64) -> Result<String, Strin
std::thread::sleep(std::time::Duration::from_millis(250)); std::thread::sleep(std::time::Duration::from_millis(250));
} }
} }
#[cfg(test)]
mod root_key_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn allowed_paths_hold_only_our_armour_links_are_reported_and_git_objects_are_not_read() {
let dir = std::env::temp_dir().join(format!("ianitor-rk-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("pki/devices")).unwrap();
std::fs::create_dir_all(dir.join("routes.git/objects/ab")).unwrap();
let key = pki::generate_key().unwrap();
let sealed = pki::encrypt_key_with(&key, b"pw", 1000).unwrap();
let plain = key.serialize_pem();
std::fs::write(dir.join("pki/intermediate.key"), &sealed).unwrap();
std::fs::write(dir.join("pki/devices/d1.key"), &sealed).unwrap();
// Git's store is not read (a blob could hold anything, compressed or not).
std::fs::write(dir.join("routes.git/objects/ab/cdef"), &plain).unwrap();
assert!(
root_key_files(&dir).is_empty(),
"{:?}",
root_key_files(&dir)
);
// A plain key, or a second block, in an allowed place is not ours.
std::fs::write(dir.join("pki/pending-x.key"), &plain).unwrap();
std::fs::write(dir.join("pki/devices/d2.key"), format!("{sealed}{plain}")).unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("/nonexistent/domi-root.key", dir.join("pki/devices/d3.key"))
.unwrap();
let found = root_key_files(&dir);
assert!(found.contains(&dir.join("pki/pending-x.key")), "{found:?}");
assert!(found.contains(&dir.join("pki/devices/d2.key")), "{found:?}");
#[cfg(unix)]
assert!(found.contains(&dir.join("pki/devices/d3.key")), "{found:?}");
assert!(
!found.contains(&dir.join("pki/intermediate.key")),
"{found:?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
}
+56 -16
View File
@@ -164,9 +164,16 @@ impl Control {
} }
/// The device files changed (issue or revoke): rewrite them and tell the engine at once. /// The device files changed (issue or revoke): rewrite them and tell the engine at once.
///
/// It never waits for an apply (fix round 3): the files go to disk at once and edge is told
/// at once, also during a watch (edge's trial reads the same files). Only when Caddy serves
/// *and* a trial is out is the Caddy reload left to the end of that apply: a reload now
/// would drop the trial, and the end of every Caddy trial loads caddy.json again (promote,
/// revert, caddy-guard, caddy-revert), which reads the new files. During an engine switch
/// (engine lock busy for more than a second) the engine being started reads them anyway.
pub async fn devices_changed(&self) -> Result<(), String> { pub async fn devices_changed(&self) -> Result<(), String> {
let Some(p) = &self.pki else { return Ok(()) }; let Some(p) = &self.pki else { return Ok(()) };
let _engine = self.engine_lock.lock().await; let _files = self.devices_lock.lock().await;
let t = now(); let t = now();
let mut result = Ok(()); let mut result = Ok(());
for dir in self.cert_dirs() { for dir in self.cert_dirs() {
@@ -177,23 +184,34 @@ impl Control {
)); ));
} }
} }
// Tell the serving engine every time, changed or not: a repeated Revoke nudges again. // The engine lock is held for long only by a switch; an apply holds it for a moment
if result.is_ok() { // (loading a trial, or from the claim to the promoted reload), so then this waits.
result = if self.engine_running() == "caddy" { let engine =
self.caddy_reload() match tokio::time::timeout(Duration::from_secs(1), self.engine_lock.lock()).await {
.await Ok(g) => Some(g),
.map_err(|e| format!("Caddy did not reload the device list: {e}")) Err(_) if self.engine_state().state == "switching" => None,
} else if self.edge.attached() { Err(_) => Some(self.engine_lock.lock().await),
self.edge
.reload_devices()
.await
.map_err(|e| format!("edge did not re-read the device list: {e}"))
} else {
Ok(())
}; };
// Tell the serving engine every time, changed or not: a repeated Revoke nudges again.
// During a switch it is not told now, and never silently (QC round 4): the problem
// stays set, so the retry tells whichever engine serves once the switch is over (the
// switch itself also ends by telling it).
let mut pending = None;
if result.is_ok() {
if engine.is_none() {
pending = Some(
"an engine switch is under way; the engine that serves after it is told then"
.to_owned(),
);
} else {
result = self.nudge_devices().await;
}
} }
if let Ok(mut pr) = self.devices_problem.lock() { if let Ok(mut pr) = self.devices_problem.lock() {
*pr = result.as_ref().err().cloned(); *pr = result.as_ref().err().cloned().or(pending.clone());
}
if let Some(p) = &pending {
log::info!(target: "ianitor::pki", "{p}");
} }
if let Err(e) = &result { if let Err(e) = &result {
log::error!(target: "ianitor::pki", "{e}; retrying"); log::error!(target: "ianitor::pki", "{e}; retrying");
@@ -201,10 +219,32 @@ impl Control {
result result
} }
/// Tell the engine that serves to read the device files again. The caller holds the engine
/// lock. Under Caddy with a trial out, the end of that apply does it (promote, revert, the
/// guard and caddy-revert all load caddy.json, which reads the files).
pub(crate) async fn nudge_devices(&self) -> Result<(), String> {
let caddy = self.engine_running() == "caddy";
if caddy && crate::caddy_guard::armed(&self.cfg.state_dir).is_some() {
log::info!(target: "ianitor::pki", "a change is being tried on Caddy; Caddy reads the new device list when it ends");
Ok(())
} else if caddy {
self.caddy_reload_checked()
.await
.map_err(|e| format!("Caddy did not reload the device list: {e}"))
} else if self.edge.attached() {
self.edge
.reload_devices()
.await
.map_err(|e| format!("edge did not re-read the device list: {e}"))
} else {
Ok(())
}
}
async fn reload_serving_engine(&self) { async fn reload_serving_engine(&self) {
let _engine = self.engine_lock.lock().await; let _engine = self.engine_lock.lock().await;
if self.engine_running() == "caddy" { if self.engine_running() == "caddy" {
if let Err(e) = self.caddy_reload().await { if let Err(e) = self.caddy_reload_checked().await {
log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {e}"); log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {e}");
} }
} else if self.edge.attached() } else if self.edge.attached()
+11
View File
@@ -254,6 +254,17 @@ impl Control {
}); });
} }
} }
// Still under the engine lock: whichever engine serves now reads the device files again
// (QC round 4). A device change during the switch only wrote them; a Caddy that was
// already running, or started before they changed, would keep the old list.
if self.pki.is_some()
&& let Err(e) = self.nudge_devices().await
{
log::error!(target: "ianitor::engine", "after the switch: {e}; retrying");
if let Ok(mut p) = self.devices_problem.lock() {
*p = Some(e);
}
}
} }
fn units_and_cfg(&self) -> Result<(Arc<dyn Units>, EngineConfig), String> { fn units_and_cfg(&self) -> Result<(Arc<dyn Units>, EngineConfig), String> {
+845 -6
View File
@@ -78,6 +78,12 @@ esac
let deadline = Instant::now() + Duration::from_secs(30); let deadline = Instant::now() + Duration::from_secs(30);
loop { loop {
let r = env.call("GET", "/api/v1/engine", None).await; let r = env.call("GET", "/api/v1/engine", None).await;
// On a loaded machine a switch takes longer: stay under the API's 120 calls a
// minute rather than fail on a 429.
if r.status == 429 {
tokio::time::sleep(Duration::from_secs(1)).await;
continue;
}
assert_eq!(r.status, 200, "{}", r.text); assert_eq!(r.status, 200, "{}", r.text);
if r.json["state"] == "running" && r.json["running"] == running { if r.json["state"] == "running" && r.json["running"] == running {
return r.json; return r.json;
@@ -85,7 +91,7 @@ esac
if Instant::now() > deadline { if Instant::now() > deadline {
panic!("engine is {}\n{}", r.text, env.control_log()); panic!("engine is {}\n{}", r.text, env.control_log());
} }
tokio::time::sleep(Duration::from_millis(100)).await; tokio::time::sleep(Duration::from_millis(300)).await;
} }
} }
@@ -228,11 +234,30 @@ mkdir -p "$dir"
echo "$*" >> "{d}/fake/calls.log" echo "$*" >> "{d}/fake/calls.log"
case "$1:$2" in case "$1:$2" in
start:caddy-fallback.service) start:caddy-fallback.service)
# Like systemd: starting a unit that is active does nothing.
[ -e "$dir/$2" ] && exit 0
XDG_DATA_HOME="{d}/caddy-state" XDG_CONFIG_HOME="{d}/caddy-state" HOME="{d}/caddy-state" \ XDG_DATA_HOME="{d}/caddy-state" XDG_CONFIG_HOME="{d}/caddy-state" HOME="{d}/caddy-state" \
nohup "{c}" run --config "{d}/caddy/caddy.json" >> "{d}/logs/caddy.log" 2>&1 & nohup "{c}" run --config "{d}/caddy/caddy.json" >> "{d}/logs/caddy.log" 2>&1 &
echo $! > "{d}/fake/caddy.pid"; touch "$dir/$2" ;; echo $! > "{d}/fake/caddy.pid"
# The NixOS module starts ianitor-caddy-guard with caddy-fallback (crate::caddy_guard).
if [ ! -e "{d}/fake/no-guard" ]; then
IANITOR_LOG=info nohup "{g}" caddy-guard --config "{d}/control.toml" >> "{d}/logs/caddy-guard.log" 2>&1 &
echo $! > "{d}/fake/guard.pid"
fi
# fake/start-delay: Caddy serves at once, the unit reports active only later (a switch
# that is still in wait_serving while Caddy has read its files).
if [ -f "{d}/fake/start-delay" ]; then
(sleep "$(cat "{d}/fake/start-delay")"; touch "$dir/$2") >/dev/null 2>&1 &
else
touch "$dir/$2"
fi ;;
stop:caddy-fallback.service) stop:caddy-fallback.service)
[ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null; rm -f "$dir/$2" "{d}/fake/caddy.pid" ;; # fake/stop-delay and fake/fail-stop: a slow stop, and one that fails (Caddy keeps running).
[ -f "{d}/fake/stop-delay" ] && sleep "$(cat "{d}/fake/stop-delay")"
grep -qx "$2" "{d}/fake/fail-stop" 2>/dev/null && exit 1
[ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null
[ -f "{d}/fake/guard.pid" ] && kill "$(cat "{d}/fake/guard.pid")" 2>/dev/null
rm -f "$dir/$2" "{d}/fake/caddy.pid" "{d}/fake/guard.pid" ;;
start:*) touch "$dir/$2" ;; start:*) touch "$dir/$2" ;;
stop:*) rm -f "$dir/$2" ;; stop:*) rm -f "$dir/$2" ;;
is-active:*) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;; is-active:*) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;;
@@ -240,7 +265,8 @@ case "$1:$2" in
esac esac
"#, "#,
d = dir.display(), d = dir.display(),
c = caddy.display() c = caddy.display(),
g = env!("CARGO_BIN_EXE_ianitor-control"),
) )
} }
@@ -251,8 +277,10 @@ esac
impl Drop for CaddyEnv { impl Drop for CaddyEnv {
fn drop(&mut self) { fn drop(&mut self) {
if let Ok(p) = std::fs::read_to_string(self.env.dir.join("fake/caddy.pid")) { for f in ["fake/caddy.pid", "fake/guard.pid"] {
let _ = std::process::Command::new("kill").arg(p.trim()).status(); if let Ok(p) = std::fs::read_to_string(self.env.dir.join(f)) {
let _ = std::process::Command::new("kill").arg(p.trim()).status();
}
} }
} }
} }
@@ -392,4 +420,815 @@ esac
&& !edge_json.contains("c.test") && !edge_json.contains("c.test")
); );
} }
// ---------------------------------------------------------------- QC round 2
async fn qc_env_with_caddy_site(site: String) -> Option<CaddyEnv> {
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
let mut env = Env::new(EnvSpec {
site,
..Default::default()
})
.await;
let fake = env.dir.join("fake/systemctl");
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap();
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let d = |p: &str| env.dir.join(p).display().to_string();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
d("engine"),
fake.display(),
d("certs"),
d("caddy-state"),
d("logs/caddy-access.log"),
d("creds"),
d("caddy/admin.sock"),
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
Some(CaddyEnv { env, https })
}
/// QC r2: a forward-auth host with a health check is kept under edge (edge checks the
/// upstream). Under Caddy the watch probes *through* Caddy without a session: Authelia's
/// redirect is not 2xx, so the same change is reverted.
#[tokio::test(flavor = "multi_thread")]
async fn qc_forward_auth_host_with_health_check_is_kept_under_caddy_as_under_edge() {
let auth = ianitor_testkit::authelia::MockAuthelia::start().await;
let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url());
let Some(ce) = qc_env_with_caddy_site(site).await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let host = |h: &str| {
json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi",
"auth": "forward-auth", "health_check": {"path": "/", "interval_secs": 1}}})
};
let rec = env
.apply("POST", "/api/v1/hosts", Some(host("a.test")))
.await;
eprintln!("QC under edge: {}", rec["state"]);
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
let rec = env
.apply("POST", "/api/v1/hosts", Some(host("b.test")))
.await;
eprintln!(
"QC under caddy: {} {}",
rec["state"], rec["reason"]["detail"]
);
assert_eq!(rec["state"], "kept", "{rec}");
}
/// QC r2: control nudges Caddy (device list, renewed certificates) by POST /load of the
/// unchanged caddy.json. Caddy skips a load of an identical config, so the files it read at
/// start are not read again.
#[tokio::test(flavor = "multi_thread")]
async fn qc_reloading_the_same_caddy_json_rereads_the_certificate_files() {
let Some(ce) = env_with_caddy().await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let rec = env
.apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})))
.await;
assert_eq!(rec["state"], "kept");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202);
wait_engine(env, "caddy").await;
assert_eq!(visit(env, ce.https, "a.test").await, 200);
// Replace a.test's certificate with one from a root the client does not trust.
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let (root, rk) = ianitor_core::pki::create_root(now).unwrap();
let k = ianitor_core::pki::generate_key().unwrap();
let csr =
ianitor_core::pki::intermediate_csr(&k, ianitor_core::pki::INTERMEDIATE_CN).unwrap();
let int = ianitor_core::pki::Intermediate::new(
&ianitor_core::pki::sign_intermediate(&root, &rk, &csr, now).unwrap(),
k,
)
.unwrap();
let leaf = ianitor_core::pki::issue_server(&int, "a.test", now).unwrap();
std::fs::write(env.dir.join("certs/a.test.key"), &leaf.key_pem).unwrap();
std::fs::write(env.dir.join("certs/a.test.crt"), &leaf.chain_pem).unwrap();
// What control does in devices_changed / reload_serving_engine under Caddy.
let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
let r = ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &text).await;
assert!(r.is_ok(), "{r:?}");
let after = visit(env, ce.https, "a.test").await;
eprintln!(
"QC after same-config load: visit = {after} (200 = old certificate still served)"
);
assert_ne!(
after, 200,
"Caddy still serves the certificate it read at start"
);
}
/// QC r2: a control crash with a trial loaded into Caddy. Edge reverts an unconfirmed trial
/// by itself; Caddy has no deadline, so the unverified config keeps serving while control
/// is down.
#[tokio::test(flavor = "multi_thread")]
async fn qc_control_crash_mid_trial_under_caddy_leaves_the_last_good_config() {
let Some(mut ce) = env_with_caddy().await else {
return;
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let host = |h: &str| json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi", "auth": "none"}});
assert_eq!(
ce.env
.apply("POST", "/api/v1/hosts", Some(host("a.test")))
.await["state"],
"kept"
);
let r = ce
.env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202);
wait_engine(&ce.env, "caddy").await;
ce.env.kill_control();
ce.env.start_control(Some("trial_loaded"));
let r = ce
.env
.call("POST", "/api/v1/hosts", Some(host("b.test")))
.await;
assert_eq!(r.status, 202, "{}", r.text);
let st = ce.env.wait_control_exit(Duration::from_secs(30));
eprintln!("QC control exit: {st:?}");
assert!(st.is_some());
// Longer than edge's trial deadline would allow.
tokio::time::sleep(Duration::from_secs(15)).await;
let during = visit(&ce.env, ce.https, "b.test").await;
eprintln!("QC b.test through Caddy 15 s after the crash, control down: {during}");
ce.env.start_control(None);
tokio::time::sleep(Duration::from_secs(3)).await;
let after = visit(&ce.env, ce.https, "b.test").await;
eprintln!("QC b.test after control restarted (recovery): {after}");
assert_ne!(after, 200, "recovery must revert the trial");
assert_ne!(
during, 200,
"Caddy served the unconfirmed trial while control was down"
);
}
// ---------------------------------------------------------------- fix round 2
/// Like `env_with_caddy`, with a chosen watch, and with or without the Caddy trial guard
/// (the fake systemctl starts it next to Caddy unless `fake/no-guard` exists).
async fn caddy_env(watch_secs: u64, guard: bool) -> Option<CaddyEnv> {
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
let mut env = Env::new(EnvSpec {
watch_secs,
..Default::default()
})
.await;
let fake = env.dir.join("fake/systemctl");
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap();
if !guard {
std::fs::write(env.dir.join("fake/no-guard"), "").unwrap();
}
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let d = |p: &str| env.dir.join(p).display().to_string();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
d("engine"),
fake.display(),
d("certs"),
d("caddy-state"),
d("logs/caddy-access.log"),
d("creds"),
d("caddy/admin.sock"),
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
Some(CaddyEnv { env, https })
}
async fn to_caddy_with(env: &Env, echo: &ianitor_testkit::upstream::Echo) {
let rec = env
.apply(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})),
)
.await;
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
}
async fn wait_state(env: &Env, id: &str, state: &str) {
let deadline = Instant::now() + Duration::from_secs(20);
loop {
let r = env
.call("GET", &format!("/api/v1/applies/{id}"), None)
.await;
if r.json["state"] == state {
return;
}
assert!(Instant::now() < deadline, "never {state}: {}", r.text);
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
fn b_host(echo: &ianitor_testkit::upstream::Echo) -> Value {
json!({"host": {"hostname": "b.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})
}
/// QC round 2, M2: something reloads Caddy during a trial's watch (a device change, a
/// restart of caddy-fallback). The trial is gone from Caddy; the watch must notice and
/// treat it as interrupted, not report it kept while Caddy serves the old config.
#[tokio::test(flavor = "multi_thread")]
async fn a_reload_of_caddy_during_the_watch_is_noticed() {
let Some(ce) = caddy_env(8, true).await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
to_caddy_with(env, &echo).await;
let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
wait_state(env, &id, "watching").await;
assert_eq!(
visit(env, ce.https, "b.test").await,
200,
"the trial serves"
);
// What a device change or a Caddy restart does: Caddy gets the last good config.
let good = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &good)
.await
.unwrap();
let rec = env.wait_apply(&id).await;
assert_ne!(rec["state"], "kept", "{rec}");
assert_eq!(rec["reason"]["code"], "apply.reverted.edge_lost", "{rec}");
let now_good = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap();
assert!(!now_good.contains("b.test"), "{now_good}");
assert_ne!(visit(env, ce.https, "b.test").await, 200);
}
/// QC round 2, minor 3: the `watching` crash point under Caddy.
#[tokio::test(flavor = "multi_thread")]
async fn a_crash_while_watching_under_caddy_is_reverted() {
let Some(mut ce) = caddy_env(4, true).await else {
return;
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
to_caddy_with(&ce.env, &echo).await;
ce.env.kill_control();
ce.env.start_control(Some("watching"));
let r = ce
.env
.call("POST", "/api/v1/hosts", Some(b_host(&echo)))
.await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some());
ce.env.start_control(None);
let rec = ce.env.wait_apply(&id).await;
assert_eq!(rec["state"], "reverted", "{rec}");
assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
}
/// QC round 2, B2 (a): what systemd runs after control stops (ExecStopPost): with an
/// unconfirmed trial in the journal, Caddy goes back to the last good caddy.json at once,
/// without waiting for the guard's deadline.
#[tokio::test(flavor = "multi_thread")]
async fn caddy_revert_after_a_crash_loads_the_last_good_config() {
let Some(mut ce) = caddy_env(3, false).await else {
return;
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
to_caddy_with(&ce.env, &echo).await;
ce.env.kill_control();
ce.env.start_control(Some("trial_loaded"));
let r = ce
.env
.call("POST", "/api/v1/hosts", Some(b_host(&echo)))
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some());
assert_eq!(
visit(&ce.env, ce.https, "b.test").await,
200,
"the trial was loaded"
);
let config = ce.env.config_path();
let revert = || {
std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
.args(["caddy-revert", "--config"])
.arg(&config)
.output()
.unwrap()
};
let out = revert();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
// After recovery there is no trial: it changes nothing and succeeds.
ce.env.start_control(None);
tokio::time::sleep(Duration::from_secs(2)).await;
let out = revert();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
}
/// QC r3: a device revoked while Caddy serves. Control rewrites the allow list and loads
/// caddy.json (must-revalidate); the revoked device must no longer get in, the newly
/// allowed one must.
#[tokio::test(flavor = "multi_thread")]
async fn qc_device_revoked_under_caddy_is_refused() {
use ianitor_core::pki;
use ianitor_testkit::client::{self, ClientCert, Req};
let Some(ce) = env_with_caddy().await else {
return;
};
let env = &ce.env;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let (root, rk) = pki::create_root(now).unwrap();
let k = pki::generate_key().unwrap();
let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
let int =
pki::Intermediate::new(&pki::sign_intermediate(&root, &rk, &csr, now).unwrap(), k)
.unwrap();
let phone = pki::issue_device(&int, "phone", now).unwrap();
let laptop = pki::issue_device(&int, "laptop", now).unwrap();
std::fs::write(env.dir.join("certs/domi-devices-ca.pem"), int.cert_pem()).unwrap();
std::fs::write(env.dir.join("certs/domi-devices.pem"), &phone.cert_pem).unwrap();
let cc = |d: &pki::Issued| ClientCert {
chain_pem: d.chain_pem.clone(),
key_pem: d.key_pem.clone(),
tls12_only: false,
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let rec = env
.apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})))
.await;
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202);
wait_engine(env, "caddy").await;
let visit_as = |d: &pki::Issued| {
let c = cc(d);
let roots = env.ca.roots();
async move {
match client::https_with_cert(
ce.https,
"d.test",
roots,
&c,
&Req::get("d.test", "/"),
)
.await
{
Ok(r) => r.status,
Err(_) => 0,
}
}
};
let before = visit_as(&phone).await;
eprintln!("QC phone under Caddy before revocation: {before}");
assert_eq!(before, 200);
// Revoke the phone, allow the laptop; tell Caddy the way control does.
std::fs::write(env.dir.join("certs/domi-devices.pem"), &laptop.cert_pem).unwrap();
let sock = env.dir.join("caddy/admin.sock");
let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
ianitor_control::caddy_link::load(&sock, &text)
.await
.unwrap();
assert!(
ianitor_control::caddy_link::runs(&sock, &text)
.await
.unwrap()
);
let phone_after = visit_as(&phone).await;
let laptop_after = visit_as(&laptop).await;
eprintln!("QC after revocation under Caddy: phone {phone_after}, laptop {laptop_after}");
assert_ne!(phone_after, 200, "revoked phone still gets in under Caddy");
assert_eq!(
laptop_after, 200,
"newly allowed laptop is not let in under Caddy"
);
}
// ---------------------------------------------------------------- fix round 3
/// A control with the Domi CA, an intermediate signed by a test root, one device issued
/// and approved, and `d.test` asking for device certificates. With `caddy`, Caddy serves.
struct PkiEnv {
ce: CaddyEnv,
roots: std::sync::Arc<rustls::RootCertStore>,
device_id: String,
device: ianitor_testkit::client::ClientCert,
}
async fn pki_env(watch_secs: u64, caddy: bool) -> Option<PkiEnv> {
use ianitor_core::pki;
let ce = caddy_env(watch_secs, true).await?;
let mut ce = ce;
let env = &mut ce.env;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let (root_pem, root_key) = pki::create_root(now).unwrap();
std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap();
std::fs::write(
env.dir.join("creds/pki-password"),
"round-three-password-123",
)
.unwrap();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n",
env.dir.join("offline-root.crt").display()
);
std::fs::write(env.config_path(), text).unwrap();
env.kill_control();
env.start_control(None);
let cli = |env: &Env, args: &[&str]| {
env.command()
.args(args)
.arg("--config")
.arg(env.config_path())
.output()
.unwrap()
};
// The intermediate, signed offline.
let r = env
.call(
"POST",
"/api/v1/certs/intermediate/renewal",
Some(json!({})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
let signed = pki::sign_intermediate(&root_pem, &root_key, &csr, now).unwrap();
std::fs::write(env.dir.join("int.crt"), signed).unwrap();
let int_path = env.dir.join("int.crt").display().to_string();
let out = cli(env, &["pki", "install", &int_path]);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
// One device.
let r = env
.call(
"POST",
"/api/v1/certs/devices",
Some(json!({"name": "phone", "kind": "phone"})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let code = r.json["match_code"].as_str().unwrap().to_owned();
let out = cli(env, &["pki", "approve", &code]);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let devices: Value = serde_json::from_str(
&std::fs::read_to_string(env.dir.join("state/pki/devices.json")).unwrap(),
)
.unwrap();
let d = &devices[0];
let device_id = d["id"].as_str().unwrap().to_owned();
let sealed =
std::fs::read_to_string(env.dir.join(&format!("state/pki/devices/{device_id}.key")))
.unwrap();
let key = pki::decrypt_key(&sealed, b"round-three-password-123").unwrap();
let int_pem = std::fs::read_to_string(env.dir.join("state/pki/intermediate.crt")).unwrap();
let device = ianitor_testkit::client::ClientCert {
chain_pem: format!("{}{int_pem}", d["cert_pem"].as_str().unwrap()),
key_pem: key.serialize_pem(),
tls12_only: false,
};
let mut store = rustls::RootCertStore::empty();
store
.add(rustls_pki_types::CertificateDer::from(
pki::chain_der(&root_pem).unwrap().remove(0),
))
.unwrap();
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let rec = env
.apply(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})),
)
.await;
assert_eq!(rec["state"], "kept", "{rec}");
// The echo upstream must outlive this function: keep it running in the background.
std::mem::forget(echo);
if caddy {
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
}
Some(PkiEnv {
ce,
roots: std::sync::Arc::new(store),
device_id,
device,
})
}
impl PkiEnv {
async fn visit_as_device(&self, at: std::net::SocketAddr) -> u16 {
match ianitor_testkit::client::https_with_cert(
at,
"d.test",
self.roots.clone(),
&self.device,
&ianitor_testkit::client::Req::get("d.test", "/"),
)
.await
{
Ok(r) => r.status,
Err(_) => 0,
}
}
fn serving(&self, caddy: bool) -> std::net::SocketAddr {
if caddy {
self.ce.https
} else {
self.ce.env.edge.as_ref().unwrap().https
}
}
}
/// Fix round 3 (QC r3 Major): a revocation never waits for a running apply. The DELETE
/// answers at once, the allow list is on disk at once, and the device is refused within
/// edge's backstop window although an apply is still watching.
async fn revoke_during_a_watch(caddy: bool) {
let Some(p) = pki_env(6, caddy).await else {
return;
};
let env = &p.ce.env;
let at = p.serving(caddy);
assert_eq!(p.visit_as_device(at).await, 200, "the device gets in");
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
wait_state(env, &id, "watching").await;
let t = Instant::now();
let d = env
.call(
"DELETE",
&format!("/api/v1/certs/devices/{}", p.device_id),
None,
)
.await;
let took = t.elapsed();
assert_eq!(d.status, 204, "{}", d.text);
assert!(
took < Duration::from_millis(1500),
"the DELETE waited {took:?}"
);
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
let listed = p
.device
.chain_pem
.split("-----END CERTIFICATE-----")
.next()
.unwrap();
assert!(
!allow.contains(listed.trim()),
"the revoked device is still on the list"
);
if caddy {
// Caddy keeps the trial until the apply ends; then the device is out at once.
let rec = env.wait_apply(&id).await;
assert_eq!(rec["state"], "kept", "{rec}");
assert_ne!(
p.visit_as_device(at).await,
200,
"revoked device still gets in under Caddy"
);
} else {
let deadline = Instant::now() + Duration::from_secs(6);
while p.visit_as_device(at).await == 200 {
assert!(
Instant::now() < deadline,
"revoked device still gets in under Pingora"
);
tokio::time::sleep(Duration::from_millis(250)).await;
}
let rec = env.wait_apply(&id).await;
assert_eq!(rec["state"], "kept", "{rec}");
}
let c = env.call("GET", "/api/v1/certs", None).await;
assert!(c.json["devices_problem"].is_null(), "{}", c.text);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_watch_is_in_force_at_once_under_pingora() {
revoke_during_a_watch(false).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_watch_is_in_force_when_the_apply_ends_under_caddy() {
revoke_during_a_watch(true).await;
}
/// Fix round 3, minor 3: with Pingora serving, a deadline file left behind is cleared and
/// caddy-revert succeeds (the unit must not show failed).
#[tokio::test(flavor = "multi_thread")]
async fn caddy_revert_with_pingora_serving_clears_a_stale_deadline() {
let mut env = env().await;
env.kill_control();
std::fs::write(
env.dir.join("state/caddy-trial.json"),
r#"{"apply_id":"ch_x","deadline":1}"#,
)
.unwrap();
let out = env
.command()
.args(["caddy-revert", "--config"])
.arg(env.config_path())
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert!(!env.dir.join("state/caddy-trial.json").exists());
}
// ---------------------------------------------------------------- fix round 4
async fn engine_view(env: &Env) -> Value {
env.call("GET", "/api/v1/engine", None).await.json
}
async fn wait_switching(env: &Env) {
let deadline = Instant::now() + Duration::from_secs(10);
while engine_view(env).await["state"] != "switching" {
assert!(Instant::now() < deadline, "the switch never started");
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
async fn wait_switch_over(env: &Env) -> Value {
let deadline = Instant::now() + Duration::from_secs(40);
loop {
let e = engine_view(env).await;
if e["state"] == "running" {
return e;
}
assert!(Instant::now() < deadline, "the switch never ended: {e}");
tokio::time::sleep(Duration::from_millis(300)).await;
}
}
async fn revoke(env: &Env, id: &str) {
let t = Instant::now();
let d = env
.call("DELETE", &format!("/api/v1/certs/devices/{id}"), None)
.await;
assert_eq!(d.status, 204, "{}", d.text);
assert!(
t.elapsed() < Duration::from_secs(3),
"the DELETE waited {:?}",
t.elapsed()
);
}
async fn refused_soon(p: &PkiEnv, at: std::net::SocketAddr, what: &str) {
let deadline = Instant::now() + Duration::from_secs(4);
while p.visit_as_device(at).await == 200 {
assert!(Instant::now() < deadline, "{what}");
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
/// QC round 4, case A: a device is revoked while a switch to Caddy is still waiting for
/// the unit, after Caddy has already read the allow list. The switch ends by telling
/// Caddy again, so the device is refused once Caddy serves.
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_switch_to_caddy_is_in_force_when_it_ends() {
let Some(p) = pki_env(2, false).await else {
return;
};
let env = &p.ce.env;
std::fs::write(env.dir.join("fake/start-delay"), "5").unwrap();
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_switching(env).await;
// Caddy is up and has read its files; the unit is not reported active yet.
let deadline = Instant::now() + Duration::from_secs(5);
while p.visit_as_device(p.ce.https).await != 200 {
assert!(Instant::now() < deadline, "Caddy did not come up");
tokio::time::sleep(Duration::from_millis(200)).await;
}
assert_eq!(engine_view(env).await["state"], "switching");
revoke(env, &p.device_id).await;
let e = wait_switch_over(env).await;
assert_eq!(e["running"], "caddy", "{e}");
refused_soon(
&p,
p.ce.https,
"the revoked device still gets in under Caddy after the switch",
)
.await;
}
/// QC round 4, case B: a switch away from Caddy fails before Caddy is stopped, and a
/// device was revoked meanwhile. The Caddy that kept serving must refuse it.
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_failed_switch_away_from_caddy_is_in_force() {
let Some(p) = pki_env(2, true).await else {
return;
};
let env = &p.ce.env;
assert_eq!(
p.visit_as_device(p.ce.https).await,
200,
"the device gets in"
);
std::fs::write(env.dir.join("fake/stop-delay"), "4").unwrap();
std::fs::write(env.dir.join("fake/fail-stop"), "caddy-fallback.service\n").unwrap();
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "pingora"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_switching(env).await;
revoke(env, &p.device_id).await;
let e = wait_switch_over(env).await;
assert_eq!(e["running"], "caddy", "{e}");
assert!(!e["last_error"].is_null(), "{e}");
refused_soon(
&p,
p.ce.https,
"the revoked device still gets in under the Caddy that kept serving",
)
.await;
// Nothing is left pending.
let deadline = Instant::now() + Duration::from_secs(6);
loop {
let c = env.call("GET", "/api/v1/certs", None).await;
if c.json["devices_problem"].is_null() {
break;
}
assert!(Instant::now() < deadline, "{}", c.text);
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
} }
+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
+67 -554
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,
pub const INTERMEDIATE_DAYS: u32 = 365; match_code, 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 {
/// An ECDSA P-256 key pair. Never printed. D::BadCertificate(s) => PkiError::BadCertificate(s),
pub struct KeyPair(rcgen::KeyPair); D::BadCsr => PkiError::BadCsr,
D::CsrSubject => PkiError::CsrSubject,
impl fmt::Debug for KeyPair { D::BadKey | D::UnsupportedKey => PkiError::BadKey,
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { D::NotCa => PkiError::NotCa,
f.write_str("KeyPair(…)") D::KeyMismatch => PkiError::KeyMismatch,
} D::IssuerExpired => PkiError::IssuerExpired,
} D::BadName(s) => PkiError::BadName(s),
D::Random => PkiError::Random,
impl KeyPair { D::Build(s) | D::Signer(s) => PkiError::Build(s),
/// PKCS#8 PEM. Callers write it only to files with mode 0600 (or encrypt it). other => PkiError::Build(other.to_string()),
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
} }
} }
+26 -7
View File
@@ -78,12 +78,23 @@ pub fn hostname(host_header: &str) -> String {
/// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost /// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost
/// `X-Forwarded-For` entry that is not itself trusted (the same right-to-left rule as Caddy's /// `X-Forwarded-For` entry that is not itself trusted (the same right-to-left rule as Caddy's
/// `trusted_proxies_strict`). Anything a client could forge to the left is ignored. /// `trusted_proxies_strict`). Anything a client could forge to the left is ignored.
/// An IPv4 address carried as IPv6 (`::ffff:127.0.0.1`) is the IPv4 address.
fn canonical(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4),
v4 => v4,
}
}
pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option<IpAddr> { pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option<IpAddr> {
let peer = session let peer = canonical(
.client_addr() session
.and_then(|a| a.as_inet()) .client_addr()
.map(|a| a.ip())?; .and_then(|a| a.as_inet())
if !trusted.contains(&peer) { .map(|a| a.ip())?,
);
let trusted_ip = |ip: &IpAddr| trusted.iter().any(|t| canonical(*t) == *ip);
if !trusted_ip(&peer) {
return Some(peer); return Some(peer);
} }
let mut last = peer; let mut last = peer;
@@ -96,8 +107,8 @@ pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option<IpAddr> {
{ {
let Ok(s) = v.to_str() else { return Some(last) }; let Ok(s) = v.to_str() else { return Some(last) };
for part in s.rsplit(',') { for part in s.rsplit(',') {
match part.trim().parse::<IpAddr>() { match part.trim().parse::<IpAddr>().map(canonical) {
Ok(ip) if trusted.contains(&ip) => last = ip, Ok(ip) if trusted_ip(&ip) => last = ip,
Ok(ip) => return Some(ip), Ok(ip) => return Some(ip),
Err(_) => return Some(last), Err(_) => return Some(last),
} }
@@ -506,6 +517,14 @@ pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn an_ipv4_mapped_address_is_the_ipv4_address() {
let m = IpAddr::V6(std::net::Ipv4Addr::LOCALHOST.to_ipv6_mapped());
assert_eq!(canonical(m), IpAddr::V4(std::net::Ipv4Addr::LOCALHOST));
let v6 = IpAddr::V6(std::net::Ipv6Addr::LOCALHOST);
assert_eq!(canonical(v6), v6);
}
#[test] #[test]
fn hostname_strips_port_and_case() { fn hostname_strips_port_and_case() {
assert_eq!(hostname("App.Test:8443"), "app.test"); assert_eq!(hostname("App.Test:8443"), "app.test");
+72
View File
@@ -264,4 +264,76 @@ mod unix {
tokio::time::sleep(std::time::Duration::from_millis(250)).await; tokio::time::sleep(std::time::Duration::from_millis(250)).await;
} }
} }
/// QC r2: end to end through Pingora (2 worker threads, pre-TLS hook): a handshake that
/// fails after the resolver (bad ALPN) must not break the next TLS 1.2 device handshake.
#[tokio::test(flavor = "multi_thread")]
async fn qc_tls12_device_after_bad_alpn_handshakes_end_to_end() {
use std::sync::Arc;
let echo = Echo::start("app").await;
let p = pki();
let (phone, phone_pem) = device(&p, "phone");
let edge = setup(&echo, &p, &[&phone_pem]).await;
let roots = edge.roots();
let req = Req::get("locked.test", "/");
let mut failures = Vec::new();
let mut poisoned = 0;
for i in 0..40 {
let addr = edge.https;
let r2 = roots.clone();
let failed = tokio::task::spawn_blocking(move || {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let mut cfg = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(r2)
.with_no_client_auth();
cfg.alpn_protocols = vec![b"foo".to_vec()];
let mut conn = rustls::ClientConnection::new(
Arc::new(cfg),
rustls_pki_types::ServerName::try_from("open.test".to_owned()).unwrap(),
)
.unwrap();
let mut sock = std::net::TcpStream::connect(addr).unwrap();
sock.set_read_timeout(Some(std::time::Duration::from_secs(5)))
.unwrap();
let mut r = Ok((0, 0));
for _ in 0..5 {
r = conn.complete_io(&mut sock);
if r.is_err() || !conn.is_handshaking() {
break;
}
}
r.is_err()
})
.await
.unwrap();
if failed {
poisoned += 1;
}
match client::https_with_cert(
edge.https,
"locked.test",
roots.clone(),
&tls12(&phone),
&req,
)
.await
{
Ok(r) if r.status == 200 => {}
other => failures.push(format!("{i}: {other:?}")),
}
}
eprintln!(
"QC poison handshakes that failed: {poisoned}/40; device failures: {}",
failures.len()
);
assert_eq!(poisoned, 40, "the poison handshake must fail");
assert!(
failures.is_empty(),
"{} of 40 TLS 1.2 device handshakes failed: {:?}",
failures.len(),
failures.first()
);
}
} }
+30 -3
View File
@@ -151,7 +151,7 @@ in
type = types.listOf types.str; type = types.listOf types.str;
default = [ ]; default = [ ];
example = [ "127.0.0.1" ]; example = [ "127.0.0.1" ];
description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default."; description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default: on a loopback listener any local process could then claim any address (docs/deploy/beside-caddy.md).";
}; };
}; };
@@ -252,7 +252,9 @@ in
}) userCreds; }) userCreds;
users.groups.ianitor = { }; users.groups.ianitor = { };
users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; home = "${stateRoot}/control"; }; # Only control (and Caddy itself) may reach Caddy's admin socket; edge is not in it.
users.groups.ianitor-caddy-admin = { };
users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; extraGroups = [ "ianitor-caddy-admin" ]; home = "${stateRoot}/control"; };
users.users.ianitor-edge = { isSystemUser = true; group = "ianitor"; }; users.users.ianitor-edge = { isSystemUser = true; group = "ianitor"; };
users.users.caddy-fallback = { isSystemUser = true; group = "ianitor"; }; users.users.caddy-fallback = { isSystemUser = true; group = "ianitor"; };
@@ -300,6 +302,10 @@ in
User = "ianitor-control"; User = "ianitor-control";
Group = "ianitor"; Group = "ianitor";
ExecStart = "${pkg}/bin/ianitor-control --config ${controlToml}"; ExecStart = "${pkg}/bin/ianitor-control --config ${controlToml}";
# After every stop, a crash included: a trial still loaded into Caddy goes back to the
# last good caddy.json at once (ianitor_control::caddy_guard). It runs after a crash
# too, so no separate OnFailure= unit is needed.
ExecStopPost = "${pkg}/bin/ianitor-control caddy-revert --config ${controlToml}";
LoadCredential = loadCreds controlCreds ++ [ "ui-proof:${runProof}/ui-proof" ]; LoadCredential = loadCreds controlCreds ++ [ "ui-proof:${runProof}/ui-proof" ];
ReadWritePaths = [ stateRoot ]; ReadWritePaths = [ stateRoot ];
Restart = "on-failure"; Restart = "on-failure";
@@ -352,7 +358,10 @@ in
}; };
serviceConfig = hardening // { serviceConfig = hardening // {
User = "caddy-fallback"; User = "caddy-fallback";
Group = "ianitor"; # The admin socket (and its runtime directory) belong to this group; "ianitor" for the
# certificates and logs.
Group = "ianitor-caddy-admin";
SupplementaryGroups = [ "ianitor" ];
ExecStart = "${cfg.caddyPackage}/bin/caddy run --config ${stateRoot}/caddy/caddy.json"; ExecStart = "${cfg.caddyPackage}/bin/caddy run --config ${stateRoot}/caddy/caddy.json";
LoadCredential = loadCreds cfg.credentials ++ [ "ui-proof:${runProof}/ui-proof" ]; LoadCredential = loadCreds cfg.credentials ++ [ "ui-proof:${runProof}/ui-proof" ];
RuntimeDirectory = "caddy-fallback"; RuntimeDirectory = "caddy-fallback";
@@ -367,6 +376,24 @@ in
}; };
}; };
# The deadline of a trial under Caddy, outside control (a hung control included): once a
# second it reverts a trial past its deadline to the last good caddy.json. Runs with Caddy.
systemd.services.ianitor-caddy-guard = {
description = "Ianitor: deadline for changes tried on Caddy";
partOf = [ "caddy-fallback.service" ];
after = [ "caddy-fallback.service" ];
wantedBy = [ "caddy-fallback.service" ];
environment.IANITOR_LOG = "info";
serviceConfig = hardening // {
User = "ianitor-control";
Group = "ianitor";
ExecStart = "${pkg}/bin/ianitor-control caddy-guard --config ${controlToml}";
ReadWritePaths = [ "${stateRoot}/control" ];
Restart = "always";
RestartSec = 1;
};
};
# At boot: start the engine the UI chose last (ROADMAP §3). # At boot: start the engine the UI chose last (ROADMAP §3).
systemd.services.ianitor-engine-select = { systemd.services.ianitor-engine-select = {
description = "Ianitor: start the chosen engine"; description = "Ianitor: start the chosen engine";
+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;
+21
View File
@@ -157,6 +157,27 @@ in
assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept" assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept"
server.succeed("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve two.test:443:127.0.0.1 https://two.test/ | grep -q 200") server.succeed("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve two.test:443:127.0.0.1 https://two.test/ | grep -q 200")
# The trial's deadline under Caddy does not depend on control (fix round 2, B2): the guard
# runs with Caddy, only control may use Caddy's admin socket, and a control killed during
# the watch leaves Caddy on the last good config (ExecStopPost=caddy-revert).
server.succeed("systemctl is-active ianitor-caddy-guard.service")
server.fail("runuser -u ianitor-edge -- test -w /run/caddy-fallback/admin.sock")
server.succeed("runuser -u ianitor-control -- test -w /run/caddy-fallback/admin.sock")
r = api(server, t, "POST", "/hosts", {"host": {
"hostname": "three.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}})
three = r["apply"]["id"]
for _ in range(60):
if api(server, t, "GET", f"/applies/{three}").get("state") == "watching":
break
time.sleep(0.5)
assert visit(server, "three.test") == "200", "the trial serves"
server.succeed("systemctl kill --signal=KILL ianitor-control.service")
server.wait_until_fails("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve three.test:443:127.0.0.1 https://three.test/ | grep -q 200", timeout=10)
server.wait_for_unit("ianitor-control.service")
server.wait_until_succeeds(f"curl -sf -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/overview")
assert wait_apply(server, t, three)["state"] == "reverted"
assert visit(server, "two.test") == "200"
api(server, t, "POST", "/engine", {"target": "pingora"}) api(server, t, "POST", "/engine", {"target": "pingora"})
server.wait_until_succeeds( server.wait_until_succeeds(
f"curl -s -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/engine | jq -e '.running == \"pingora\" and .state == \"running\"'" f"curl -s -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/engine | jq -e '.running == \"pingora\" and .state == \"running\"'"
+116 -3
View File
@@ -144,13 +144,126 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit
|:--|:--|:--| |:--|:--|:--|
| 1 Core and engine | Done | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. The Let's Encrypt staging check moved to phase 3 (Mark, 2026-11-07). | | 1 Core and engine | Done | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. The Let's Encrypt staging check moved to phase 3 (Mark, 2026-11-07). |
| 2 Control plane | Done | Merged to main 2026-11-07 (PR 3): routes repo, journaled apply with trial/watch/revert, undo, restore, share links, API tokens, REST API + OpenAPI, `--dev`. Four QC rounds; every finding fixed or listed in Handover. Real Gitea, systemd credentials and Authelia not exercised. | | 2 Control plane | Done | Merged to main 2026-11-07 (PR 3): routes repo, journaled apply with trial/watch/revert, undo, restore, share links, API tokens, REST API + OpenAPI, `--dev`. Four QC rounds; every finding fixed or listed in Handover. Real Gitea, systemd credentials and Authelia not exercised. |
| 3 Web UI, PKI, NixOS | Not started | UI design drafted: claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u ("murex" palette on the Domi system, approved). Carries the Let's Encrypt staging check, on the first low-risk host beside Caddy. | | 3 Web UI, PKI, NixOS | Built and merged; Done criteria pending Mark | Merged to main 2026-11-08 (PR 5): web UI (murex palette), Domi CA and device mTLS, UI sign-in behind Authelia, runtime engine switch with changes under Caddy, NixOS flake, module and VM tests. Click smoke test green. Not yet done: VM tests run on a KVM host, Mark's nixos-rebuild on the staging mirror, deploy/test-access.sh there, the LE staging check. |
| 4 Hardening and release | Not started | Known gaps carried here: see Handover. | | 4 Hardening and release | Started: the release kit, Fabrica onboarding | A `v*` tag's Gitea release carries the source archive, the notes, screenshots of the web UI and the Aula page under a signed SHA256SUMS (docs/release.md). Fabrica onboarding (docs/fabrica.md, 2026-11-19): `aula: true`, AULA.md and the brief, a Playwright e2e suite that takes the shots and records the main flows, `tests.yaml` and the `e2e` pipeline; updates stay `fabrica-deploy`; no Canalis (a device-local layer). The rest of phase 4 is not started; known gaps carried here: see Handover. |
## 10. Handover ## 10. Handover
(Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.) (Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.)
**2026-11-07: Phase 2, control plane.** **2026-11-19: Ianitor onboarded to Fabrica (docs/fabrica.md; Fabrica docs/36_app_onboarding.md).**
- **Changed:**
- `.fabrica/app.yaml` has `aula: true` and `tagPrefix: v`, with one server part.
- The release pipeline publishes the source archive (`scripts/pack-source.mjs`, the Aula download), the notes,
five `file:` shots and `aula-page.json`.
- `.fabrica/aula.yaml`, `.fabrica/aula/brief.md`, `AULA.md`, `.fabrica/notes/0.2.0.md`.
- `.fabrica/tests.yaml` (target `web`) and `.fabrica/artifex/e2e.yaml` (`windows-e2e`).
- A Playwright suite in apps/web (`e2e/`, `playwright.config.ts`): the six §4 flows with their clicks counted, each
recorded as a video, and the five Aula shots. It runs on the built UI and the demo control plane, at a fixed
instant, with every page checked for real-looking names.
- `apps/web/scripts/shots.mjs` is removed.
- The demo keeps the hosts it is given and names device requests by what was asked.
- Version 0.2.0.
- Pensum: `#jd3x1h` (the videos on Aula, when Fabrica's `videos:` lands) and `#j4yav1` (the visual gate against
v0.2.0).
- **Decided:**
- Canalis does not apply (docs/fabrica.md part 4).
- There is no android target: no Android build.
- The visual gate waits one release, because v0.1.0's shots were taken at a moving clock.
- **Verified on this PC (Windows, Edge):**
- Playwright: web 6/6 and aula 5/5, under heavy load (the slowest flow took 72 s).
- vitest 21 (smoke 15, demo 6); svelte-check: 0 errors.
- `fabrica artifex check`: 0 problems (3 pipelines, app.yaml, aula.yaml, tests.yaml, brief). `fabrica pensum check`:
0 problems. `fabrica preflight ianitor`: 0 blockers.
- `fabrica aula shots` (5 × 1440×900), `fabrica notes`, `fabrica aula page`. Each PNG was looked at.
- No Rust file changed.
- **Not verified:**
- The `e2e` pipeline on the `windows-e2e` runner.
- The Linux suites and the Nix build (as in the 2026-11-17 entry).
- **Merged:** PR #11 as 7aa8b0e. Tag `v0.2.0` points at it.
- **Release:** hub run `rydgfrtcygvhb` (runner record `20261119-020531-s018`) at `v0.2.0`.
- Every step up to `page` passed on the Windows runner: e2e 6/6, pictures 5/5, source 551,770 bytes, notes,
shots, page.
- It is parked at the approval. It waits for Mark's Custos card (code 774 398), then the `domi-release`
signature of `SHA256SUMS`.
- Nothing is published until then.
- **Deployed:** nothing. The deploy is separate: Apps → Ianitor → Deploy.
- **Next step:**
- Mark answers the card and signs.
- Check the Gitea release `v0.2.0`: the files listed in docs/release.md, Handover step 5.
- Configuration_Server adds the Aula entry (docs/fabrica.md, Handover).
**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.**
- **Changed:**
- apps/web and packages/ui: Svelte 5 UI from the designer's hand-off (docs/ui-handoff.md, decisions in docs/ui-decisions.md), murex palette, self-hosted fonts, no outside requests (CSP). vitest click smoke test for every §4 flow, with the accepted 4th clicks.
- Domi CA in core and control (docs/pki.md): ECDSA P-256; root made offline by `ianitor-control ca init`; intermediate key encrypted at rest; server certificates 90 days, device certificates 1 year and never past the intermediate; control refuses to start with a private key it does not expect in its state dir. Device mTLS in edge and Caddy (`device_certs` hosts, allow list, 421 on SNI/Host mismatch).
- §8.6 answered: Custos has no CSR signing; ticket written (docs/custos-ticket.md, not filed); interim manual openssl signing and `pki approve` on the server.
- UI sign-in (G14): a per-boot `ui-proof` secret that only the admin host behind Authelia sends; control trusts Remote-User only with it.
- Engine switch at runtime through polkit (start/stop of exactly two units). Changes keep working under Caddy: trials loaded through its admin socket, watched by probing upstreams with edge's rules, reverted by control, a deadline guard unit, or ExecStopPost after a crash. Share links are off under Caddy.
- Test hooks moved behind the default `test-hooks` feature; the Nix release build is checked to contain none.
- flake.nix (`.#ianitor`, `.#ianitor-web`, `nixosModules.ianitor`), deploy/nixos with four VM tests, deploy/test-access.sh; docs/deploy/configuration-server.patch and beside-caddy.md (flowers.stage and esp32.stage on the staging mirror, the LE staging check).
- Tests: core 103, edge 57, control 75, diff 4, testkit 1 (240); vitest 15; svelte-check clean; hook self-test 55. Four QC rounds and two design reviews; every finding fixed or listed below.
- **Deployed:** nothing. The server is unchanged. The prepared change is docs/deploy/configuration-server.patch; Mark runs it (beside-caddy.md).
- **Not verified:**
- The four NixOS VM tests: written and their drivers build, but never run (no /dev/kvm in WSL2).
- Real systemd, polkit, LoadCredential, Authelia, Gitea push and Caddy under systemd; the module against hyperv-infra's nixpkgs 24.11.
- The caddy guard retrying a failed load (code reading only).
- PKCS#12 (AES-256) install on older iOS and macOS; a screen reader; a real clipboard copy in Chrome, Firefox and iOS Safari.
- https upstreams: Caddy-path probes use the system CA bundle; not compared with Pingora's roots.
- **Known gaps for later phases:**
- Edge beside Caddy listens on loopback TCP, so any local process could forge X-Forwarded-For; `trustedProxies` stays off there. A Unix-socket listener is the fix. (phase 4)
- Control on a Unix socket only edge can reach (G14 option b). (phase 4)
- Share links under Caddy need a validator Caddy calls via forward_auth. (before v1.1)
- "All hosts answered" after a switch is not claimed: control does not check every host.
- A revocation during an engine switch reaches the engine at the end of the switch (or by the 2 s retry), not at once.
- The open `apply_sequence` flake from phase 2 has not recurred, but its cause is still unknown.
- **Decided by Mark (2026-11-07/08):** the share link on a host with links off keeps 4 clicks; UI sign-in by a secret header from edge; the switch to Caddy is allowed with differences shown; share links off under Caddy for v1; device approval falls back to `pki approve`; manual intermediate signing is a §4 exception; device certificates last 1 year; confirmations on Stop all and Revoke; hidden tabs stop polling after 15 minutes; token lifetime choice; "Open to anyone" chip; production runs Authelia outside Configuration_Server; trial hosts flowers.stage and esp32.stage; changes keep working under Caddy.
- **Still open:**
- Mark: add hyperv-infra/ianitor/domi-root.crt (made offline), apply the patch with the merged commit hash, deploy to the staging mirror, run deploy/test-access.sh, then the LE staging check (it needs a new public name on production).
- Run the VM tests on a machine with KVM (`nix flake check`).
- (e) Delete F:\pwt and the merged remote branches.
- **Next step:** Mark's staging deploy and the VM tests close Phase 3; then Phase 4.
**2026-11-07: Phase 2, control plane** (kept for its open items).
- **Changed:** - **Changed:**
- Phase 2 on branch control/phase-2: crates/control (routes repo through the `git` binary, journaled apply with edge trial reloads, 60 s watch and revert, undo/redo, restore, push with retry, share links, API tokens, REST API with OpenAPI, `--dev`), edge in-process reload over an admin Unix socket, share-link checks and visitor pages in edge, share tokens and the exact `hosts/<hostname>.toml` loader in core. - Phase 2 on branch control/phase-2: crates/control (routes repo through the `git` binary, journaled apply with edge trial reloads, 60 s watch and revert, undo/redo, restore, push with retry, share links, API tokens, REST API with OpenAPI, `--dev`), edge in-process reload over an admin Unix socket, share-link checks and visitor pages in edge, share tokens and the exact `hosts/<hostname>.toml` loader in core.
- docs/api.md (curl examples, run end to end against `--dev`) and docs/ui-api.md (the designer's contract for phase 3, with the deviations listed at its end). - docs/api.md (curl examples, run end to end against `--dev`) and docs/ui-api.md (the designer's contract for phase 3, with the deviations listed at its end).
+26 -7
View File
@@ -309,22 +309,41 @@ allows exactly `ianitor-edge.service` and `caddy-fallback.service`, verbs start
waits until it serves; if it does not within 20 s, it starts the old one again and reports waits until it serves; if it does not within 20 s, it starts the old one again and reports
`engine.switch_failed`. The switch waits for a running apply (same lock, first come first `engine.switch_failed`. The switch waits for a running apply (same lock, first come first
served: a queued switch runs right after the apply in progress, before any apply queued after served: a queued switch runs right after the apply in progress, before any apply queued after
it). Back on Pingora, edge is reloaded so it serves what was applied while Caddy served. it). Back on Pingora, edge is reloaded so it serves what was applied while Caddy served. Every
switch, kept or gone back, ends by telling the engine that serves to read the device files again;
a device change during a switch only writes them and shows `devices_problem` ("an engine switch is
under way") until then, and the 2 s retry tells the serving engine too.
Refusals: `engine.unmanaged` (no `[engine]` in control.toml), `engine.same`, `engine.switching`, Refusals: `engine.unmanaged` (no `[engine]` in control.toml), `engine.same`, `engine.switching`,
`engine.not_ready` (Caddy's settings cannot be built from the current routes). `engine.not_ready` (Caddy's settings cannot be built from the current routes).
While Caddy serves (decisions Q3, Q4; Mark 2026-11-08): While Caddy serves (decisions Q3, Q4; Mark 2026-11-08):
- **changes keep working**: applies, Undo and Restore go through the same pipeline. Both outputs - **changes keep working**: applies, Undo and Restore go through the same pipeline. Both outputs
are compiled; the trial is loaded into Caddy through its admin API (`POST /load` on the Unix are compiled; the trial is loaded into Caddy through its admin API (`POST /load` on the Unix
socket `[compile_caddy] caddy_admin_socket`, `/run/caddy-fallback/admin.sock` under NixOS), the socket `[compile_caddy] caddy_admin_socket`, `/run/caddy-fallback/admin.sock` under NixOS,
touched hosts are probed *through Caddy* for the watch window, and a revert loads the previous group `ianitor-caddy-admin`: control and Caddy, not edge), and a revert loads the previous
`caddy.json` again. Without `caddy_admin_socket` an apply under Caddy fails with `caddy.json` again. Every load sends `Cache-Control: must-revalidate`, so Caddy reads its
`apply.failed.reload` and nothing changes; certificate and device files again even when the config is unchanged. The watch judges health
as edge does: control probes the upstreams itself with edge's rules (health check: `GET <path>`,
Host = the upstream, 2xx; none: `GET /`, Host = the hostname, below 500), and a probe *through*
Caddy only asks that Caddy answers at all (any status, its sign-in redirect included). Each
round also checks that Caddy still runs the trial (`GET /config/`); if anything else reloaded it,
the change is undone as `apply.reverted.edge_lost`. Without `caddy_admin_socket` an apply under
Caddy fails with `apply.failed.reload` and nothing changes;
- **an unconfirmed trial never outlives control**, as with edge: control arms a deadline
(`caddy-trial.json` in its state directory: watch + margin) before loading the trial and claims
it right after the journal says `confirmed` (a crash in between leaves both, and recovery
promotes). A guard revert counts only once Caddy is verified on caddy.json; a failed load is
retried with a growing pause. With Pingora serving, caddy-revert only clears a stale deadline. `ianitor-caddy-guard` (a unit that runs with caddy-fallback,
`ianitor-control caddy-guard`) reverts a trial past its deadline, which covers a hung control;
ianitor-control's `ExecStopPost=ianitor-control caddy-revert` reverts at once after any stop or
crash. Whoever renames the deadline file first wins, so a trial is either kept or reverted;
- device issues and revocations never wait for an apply: the files are written and edge is told
at once. Under Caddy, Caddy is reloaded at once and checked to serve the certificate on disk
for a Domi host (else `devices_problem`, retried), except while a trial is out: then the end
of that apply (promote or revert, both load caddy.json) brings the new files in;
- **share links are off**: minting is `409 share.engine_caddy`, and a visitor with a link gets the - **share links are off**: minting is `409 share.engine_caddy`, and a visitor with a link gets the
normal sign-in (fails closed). Caddy cannot check a share token and control never serves normal sign-in (fails closed). Caddy cannot check a share token and control never serves
visitors; a validator Caddy calls through `forward_auth` is planned before v1.1; visitors; a validator Caddy calls through `forward_auth` is planned before v1.1;
- device issues and revocations reload Caddy through the same socket (Caddy reads the allow list
when a config is loaded).
A revocation is in force only once the serving engine has the new list. If the list cannot be A revocation is in force only once the serving engine has the new list. If the list cannot be
written or the engine does not take it, `DELETE /certs/devices/{id}` answers `503 written or the engine does not take it, `DELETE /certs/devices/{id}` answers `503
+8
View File
@@ -32,6 +32,14 @@ visitor ── Caddy :443 (as today) ── https://127.0.0.1:18443 Ianitor edg
- Caddy keeps the public side for the two names and hands them to Ianitor over TLS; Ianitor - Caddy keeps the public side for the two names and hands them to Ianitor over TLS; Ianitor
serves them with Domi certificates, which Caddy checks against the Domi root (a public file). serves them with Domi certificates, which Caddy checks against the Domi root (a public file).
- Every other host is untouched. Rollback: revert the patch and switch (below). - Every other host is untouched. Rollback: revert the patch and switch (below).
- Visitor addresses: Ianitor sees every visit coming from 127.0.0.1 (Caddy), so the share-link
throttle counts all visitors together and the visit log shows 127.0.0.0. The option
`services.ianitor.edge.trustedProxies = [ "127.0.0.1" ]` would make edge believe Caddy's
`X-Forwarded-For` instead, but edge listens on a TCP port on loopback that **any local user or
process can reach**, and any of them could then claim any address. It stays **off** for the
trial (the two hosts have no share links and no visit log); turn it on only on a machine where
every local account is trusted. (A Unix-socket listener for edge, which Caddy alone could reach,
is the proper fix; not built yet.)
## The patch ## The patch
+1 -3
View File
@@ -67,7 +67,7 @@ new file mode 100644
index 0000000..cd23016 index 0000000..cd23016
--- /dev/null --- /dev/null
+++ b/hyperv-infra/modules/ianitor.nix +++ b/hyperv-infra/modules/ianitor.nix
@@ -0,0 +1,51 @@ @@ -0,0 +1,49 @@
+{ config, lib, inputs, ... }: +{ config, lib, inputs, ... }:
+ +
+# Ianitor beside Caddy (Ianitor ROADMAP §1.12, Phase 3): two low-risk hosts, flowers and esp32, +# Ianitor beside Caddy (Ianitor ROADMAP §1.12, Phase 3): two low-risk hosts, flowers and esp32,
@@ -100,8 +100,6 @@ index 0000000..cd23016
+ httpListen = "127.0.0.1:18080"; + httpListen = "127.0.0.1:18080";
+ httpsListen = "127.0.0.1:18443"; + httpsListen = "127.0.0.1:18443";
+ openFirewall = false; + openFirewall = false;
+ # Caddy in front, on loopback: its X-Forwarded-For names the visitor (throttle, logs).
+ trustedProxies = [ "127.0.0.1" ];
+ }; + };
+ control.listen = "127.0.0.1:7878"; + control.listen = "127.0.0.1:7878";
+ shareLinkKeyFile = config.sops.secrets."ianitor/share-link-key".path; + shareLinkKeyFile = config.sops.secrets."ianitor/share-link-key".path;
+231
View File
@@ -0,0 +1,231 @@
# Ianitor in Fabrica: release, Aula page, updates, showcase, tests
Mark, 2026-11-19: every Domi app is released and updated through Fabrica. Each app gets its own Aula Domi page,
updates in its own way, gets Canalis, gets showcase screenshots and videos from its e2e tests with demo data, and is
tested on Fabrica's Playwright runner.
This page says what each of those means for Ianitor. The checklist is Fabrica `docs/36_app_onboarding.md`. The
formats are in Fabrica core `docs/FORMATS.md`, and Calenda's `.fabrica/` is the reference app.
docs/release.md describes the release pipeline step by step.
## Why
Ianitor is a server app. What runs is built by Nix on the server and switched in by the `deploy` pipeline. Its only
screens are the web UI, served by control on loopback behind edge and Authelia.
Three of the six items fit an app like that. Three do not:
- Ianitor has no installer and no updater.
- It has no Canalis, because Canalis is for apps on one device.
- It has no phone build.
Each item below says which case it is and why.
## The six items
| # | Item | Ianitor | Where |
| :-- | :-- | :-- | :-- |
| 1 | Fabrica app | `app.yaml` with `aula: true`. One `server` part (pipeline `deploy`, flake input `ianitor`). A `release` pipeline started by a `v*` tag. | `.fabrica/app.yaml`, `.fabrica/artifex/{release,deploy}.yaml` |
| 2 | Aula page | `AULA.md`, the brief, the shots, the release's highlights. The release publishes the source archive (the page's download), `aula-*.png`, `aula.json`, `aula-page.json` and the notes under a `SHA256SUMS` signed by `domi-release`. | `AULA.md`, `.fabrica/aula/brief.md`, `.fabrica/aula.yaml`, `.fabrica/notes/<version>.md` |
| 3 | Auto-update | `fabrica-deploy@ianitor` on the server (part 3). | `.fabrica/artifex/deploy.yaml` |
| 4 | Canalis | Not applicable (part 4). | this page |
| 5 | Showcase | A Playwright suite on the built UI and the demo control plane, at a fixed instant. It takes the Aula screenshots and records a video of each main flow. The videos wait for Fabrica's `videos:` (part 5). | `apps/web/e2e/`, `apps/web/playwright.config.ts` |
| 6 | Test targets | `tests.yaml` with the `web` target, and the `e2e` pipeline on Fabrica's `windows-e2e` runner. No `android` target, because Ianitor has no Android build. | `.fabrica/tests.yaml`, `.fabrica/artifex/e2e.yaml` |
## 1. The Fabrica app
`.fabrica/app.yaml` has:
- `name`, `icon` and `color` (the murex accent);
- `aula: true` and `tagPrefix: v`;
- one part, `server: {pipeline: deploy, input: ianitor}`.
**No `desktop` part.** A desktop part's Deploy bumps the version, tags and pushes, and that tag starts an installer
release. Ianitor has no installer. Fabrica allows `aula: true` on an app with a server part only (FORMATS, *Fabrica:
the app*).
**The release comes from a tag.** The version is changed by hand (`[repo] Release: X.Y.Z`, checked by
`scripts/check-version.mjs`). Then the `vX.Y.Z` tag is pushed and the hub is asked for a run of `release` at that
tag (`POST /api/runs`, `ref: vX.Y.Z`). No Gitea webhook reaches the hub yet.
`fabrica artifex check` checks every file of this page except `AULA.md`. `fabrica preflight ianitor` checks the
server part's pipeline: the hub and the NixOS runner. The release pipeline runs on the Windows runner, which runs
its own preflight before each run (Fabrica `docs/23_preflight.md`).
## 2. The Aula page
- **`AULA.md`**: the project's text, as Calenda's: what Ianitor is, for whom, what it does, how it is installed (the
NixOS module, not a download), and what the release's files are.
- **`.fabrica/aula/brief.md`**: the card's line, a short about, and one caption per shot. `fabrica aula page` turns it
into `aula-page.json`.
- **`.fabrica/aula.yaml`**: five `file:` shots, the PNGs the e2e suite took (part 5). `fabrica aula shots` checks each
one (a PNG, at most 2560 × 1600 and 3 MB) and writes `target/aula/aula-<name>.png` and `aula.json`. It starts no
browser for them.
- **`.fabrica/notes/<version>.md`**: the highlights a person writes. `fabrica notes` adds the merges since the
previous tag.
**What Aula shows.** Aula's server config lists each project with:
- its download globs;
- whether it must be signed.
That config is `modules/aula.nix` on the server, owned by the Configuration_Server session. Aula publishes a release
only when a file matches the download globs. So Ianitor's download is the source archive of the tag
(`ianitor-<version>-src.tar.gz`, `scripts/pack-source.mjs`). Ianitor's entry is in the Handover below.
v0.1.0 is already a signed release with the shots and the notes. It has no `aula-page.json`, because `aula: true`
came later. Aula keeps a file only when it is in the verified `SHA256SUMS`.
## 3. Updates: `fabrica-deploy`
Ianitor updates the way a server part does (Fabrica docs/36 part 3, "a server only: `deploy.yaml`"):
1. Fabrica's Apps → Ianitor → Deploy, or `fabrica deploy ianitor`, starts the `deploy` pipeline on the NixOS runner.
2. Mark approves it on his Custos card.
3. `fabrica-deploy@ianitor` fast-forwards the server's clone, updates the flake input `ianitor`, switches the system,
and asks the health check.
4. If the health check does not answer, it rolls the switch back.
That is the right way for Ianitor because:
- The code that runs is whatever the server's flake builds. A downloaded binary would be a second, unsigned path
around the Nix build.
- The web UI is part of the same Nix package (`.#ianitor-web`), served by control. A deploy replaces it with the
binaries, so there is nothing for a browser-side updater to do.
- A service worker would cache an admin UI that sits behind Authelia and must never be served stale. The UI has
none, on purpose.
A release does not deploy, and a deploy does not need a release. The deploy takes the server's chosen commit; the
release is the signed record of a version, with its pictures and notes. After a deploy, `deploy/test-access.sh` is
run from a LAN machine (CLAUDE.md).
## 4. Canalis: not applicable
Canalis is Fundamentum's layer for app-to-app calls **on one device** (Fundamentum `docs/CANALIS.md`):
- A caller and a target are both local processes. They are authenticated by Tessera subkeys and signed manifests,
and connected over a Noise channel.
- Part A registers `domi-<app-id>://open` with the operating system, under the user's own classes.
- Part B serves capabilities behind the app's own consent prompt, in the app's window.
- The template is for a Tauri 2 + Rust desktop app (a .NET one for Tabula).
Ianitor has none of the pieces this needs:
- No process on Mark's PC or phone.
- No window to show a consent prompt in.
- No scheme to register.
- No Tessera identity.
Its UI is a page served by a server, reached through the browser behind Authelia. Its control API listens on the
server's loopback only and never serves public traffic (CLAUDE.md), so no app on a device can reach it.
A capability another app could want ("give this new service a host") would be a call from a device to a server.
That is a remote API with its own authentication (control's API tokens, docs/api.md), not Canalis.
So Ianitor stops before Part A. If a Domi app ever needs to ask Ianitor for something, the answer is a scoped API
token and a documented call, written in its own design doc.
## 5. Showcase: the e2e suite, screenshots and videos
`apps/web/playwright.config.ts`, `apps/web/e2e/`:
**The server.** The suite's global setup (`e2e/serve.ts`):
- builds the UI (Vite, production) into a fresh temporary folder;
- serves it on `127.0.0.1` at a free port, with `/api/v1` answered by the demo control plane (`tests/demo.ts`: hosts
under `.test`, addresses in the documentation ranges, people *ada* and *felix*);
- sends any other path to `index.html`, as production does.
`POST /__demo/reset` starts the demo over. Every test starts from the same invented server.
**The clock.** The instant is `2026-11-16T09:30:00+01:00`, a Monday in `Europe/Prague`, with locale `en-GB`. Two
things read it:
- the demo's answers (`tests/mockApi.ts` `clock`);
- the page's `Date` (`page.clock.setFixedTime`).
So "2 h ago", "today 07:30" and every expiry date read the same in every take. This is what Fabrica's visual
comparison needs (docs/28).
**The checks on every page.** After each test, every text, field and link the page shows is checked with
`realLooking` (tests/demo.ts), which the vitest demo test already uses. A name outside `.test`, an address outside the
documentation ranges, or a forbidden word fails the test.
**The browser.** On Windows it is the installed Edge (`PW_CHANNEL` names another), so nothing is downloaded.
Elsewhere it is Playwright's own Chromium. Video recording needs Playwright's ffmpeg in `PLAYWRIGHT_BROWSERS_PATH`,
which is on F: on Mark's PC and never on C:.
**The projects.**
| Project | Command | What it does | Writes |
| :-- | :-- | :-- | :-- |
| `web` | `pnpm --filter web test:e2e` | The main flows of ROADMAP §4, with the clicks counted as in the smoke test: Add a host (2), Undo (1), Restore (3), Share link (3), Switch engine (2), Device certificate (3). Each is recorded at 1440 × 900. | `target/e2e/videos/<flow>.webm` |
| `aula` | `pnpm --filter web aula:shots` | The five screenshots of `tests/demo.ts` SHOTS at 1440 × 900, scale 1, once nothing is busy and the fonts and two frames are in. | `target/e2e/aula/<name>.png` |
**Videos.** The flows' recordings are WebM, a few seconds each. Fabrica's `videos:` in `aula.yaml` is planned (its
docs/36, docs/37) but not on Fabrica `main`, where the key still fails as unknown. Until it lands:
- the release publishes the screenshots only;
- the videos are artifacts of the e2e run;
- Pensum ticket "Publish the showcase videos on Aula" holds the change. That change is a `videos:` list in
`aula.yaml` naming `target/e2e/videos/*.webm`, and the release's file globs.
**The visual gate waits one release.** Fabrica's `visual` step compares the shots with the last signed release's.
v0.1.0's shots were taken by the old DevTools script at a moving clock, so every shot would differ, and the first
release would stop for an approval of a change that is only the clock. So:
- this release (v0.2.0) publishes the fixed-clock shots;
- the `visual` step comes with the next release, against v0.2.0;
- Pensum ticket "Turn on the visual gate against v0.2.0" holds it.
`apps/web/scripts/shots.mjs` is removed: the suite takes the same five pictures, and `fabrica aula shots` writes
`aula.json`.
## 6. Test targets
- **`.fabrica/tests.yaml`**: `dir: apps/web`, one target `web` (kind `web`, project `web`), which is also the merge
gate. `fabrica tests run --target web` runs it off-screen, and the record, traces and videos go under
`.fabrica/runs/tests/`. The Playwright config passes `FABRICA_TESTS_DEVTOOLS` to the browser for the Tests page's
live view.
- **`.fabrica/artifex/e2e.yaml`**: Fabrica's own e2e pipeline with `fabrica` for `cargo run`. It is manual, on
`windows-e2e`, and runs `pnpm install --frozen-lockfile` then `fabrica tests run --target web`, with
`.fabrica/runs/tests/**` as the artifacts.
- **No `android` target.** Ianitor has no Android build. Its UI on a phone is the same page in the phone's browser,
which a `web` target with a phone viewport would test. That is a gap (below), not a phone queue item.
- **The Rust suites** (core, edge, control, diff) are not Playwright. They run in WSL2 and in the Nix build
(ROADMAP §8.3). Edge, diff and ACME are Linux-only and need caddy and pebble, which the Windows e2e runner does
not have.
## Risks
| Risk | Answer |
| :-- | :-- |
| A picture or video shows Mark's network | The UI talks only to the demo control plane. `realLooking` checks every page every test visits. The PNGs are looked at in the review. |
| The demo server is reachable from the LAN | It listens on `127.0.0.1` only, at a free port, for the length of the run. |
| A secret reaches the browser | The demo serves no token, key or certificate. The demo API token answer is the stand-in's invented `ian_tk1_…`, which no flow shows. |
| Two takes of a screen differ | A fixed instant and zone, the demo reset before each test, fonts and two frames awaited, animations disabled in the screenshot. |
| A video grows too large | Each flow is under 15 s at 1440 × 900. docs/37's limits (8 MiB, 60 s, 6 videos) are checked when `videos:` lands. |
| The release is held by the visual gate on the clock change | The gate comes one release later (part 5). |
## Gaps
- The videos are not on Aula until Fabrica's `videos:` is on `main` (Pensum ticket).
- There is no visual gate in v0.2.0 (Pensum ticket).
- There are no phone-width shots or tests, and no tests in WebKit or Firefox.
- The `e2e` pipeline has not run on the `windows-e2e` runner from this repo. The suite was run here, with Playwright
directly and with `fabrica tests run`.
- There is no Canalis (part 4).
## Handover
**Aula entry** for the server's `modules/aula.nix` (the Configuration_Server session adds it). `files` lists the
downloads only. Aula reads the kit (`aula-*.png`, `aula.json`, `aula-page.json`, `release-notes.md`) by itself and
never offers it as a download.
Aula publishes no release that has no file matching `files` (Aula `src/aula_sync.py`). That is why v0.1.0, with the
default `*-setup.exe`, shows nothing. v0.2.0 is the first release with a download.
```nix
{
name = "Ianitor";
repo = "mnovak/ianitor";
files = [ "ianitor-*-src.tar.gz" ];
signed = true;
}
```
**Releasing 0.2.0** (docs/release.md, "Handover"):
1. `[repo] Release: 0.2.0` on main.
2. Tag `v0.2.0` and push it.
3. Start `release` at `v0.2.0` on the hub.
4. Mark approves on the Custos card, then signs `SHA256SUMS` with `domi-release`.
+117
View File
@@ -0,0 +1,117 @@
# Releases: the source, the notes and the Aula page 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 these files, all under
a `SHA256SUMS` signed by `domi-release`:
- the source archive of the tag;
- the release notes;
- the screenshots of the web UI;
- the Aula landing page.
The release ships no binary, and the deploy stays the deploy. docs/fabrica.md says how the six Fabrica items (Aula,
updates, Canalis, showcase, tests) fit Ianitor.
The release kit is Fabrica's (Fabrica `docs/12_release_kit.md`, `docs/19_web_shots.md`; core `docs/FORMATS.md`,
"Fabrica: release notes" and "Fabrica: the Aula page"). The screenshots are `file:` shots, PNGs taken by the web UI's
own Playwright suite. `fabrica aula shots` checks them and writes `aula.json`.
## The pipeline: `.fabrica/artifex/release.yaml`
`on: tag "v*"` and `manual: true`, on the Windows runner. That is 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 vitest (the click smoke test and the demo data test) | |
| `e2e` | `pnpm --filter web test:e2e`: the main flows in Edge on the built UI and the demo control plane, each recorded (docs/fabrica.md part 5) | `target/e2e/videos/*.webm` (not published yet) |
| `pictures` | `pnpm --filter web aula:shots`: the five screens from the same suite | `target/e2e/aula/<name>.png` |
| `source` | `node scripts/pack-source.mjs <version>`: `git archive` of the tag | `target/release/ianitor-<version>-src.tar.gz` |
| `notes` | `fabrica notes`: the range since the previous `v*` tag | `target/notes/release-notes.md`, `release-notes.json` |
| `shots` | `fabrica aula shots`: checks the five PNGs (`.fabrica/aula.yaml`) and copies them | `target/aula/aula-<name>.png`, `aula.json` |
| `page` | `fabrica aula page`: the brief (`.fabrica/aula/brief.md`), the shots and the notes | `target/aula/aula-page.json` |
| `approve` | the run's Custos approval, before anything is published | |
| `publish` | the Gitea release of the tag with the files above. `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.
**The download.** Aula offers a project's release only when it has a file to download, and kit files (the shots,
the notes, the page) never count. Ianitor's download is its source archive. The archive is every tracked file at the
tag, under `ianitor-<version>/`. `git archive` of one tree gives the same bytes every time.
**app.yaml** has `aula: true` and one `server` part. There is no desktop part: a desktop part's Deploy bumps the
version and pushes a tag for an installer release, and Ianitor has no installer. The release is started by its tag.
## Release notes
`fabrica notes` writes them from:
- the first-parent commit subjects;
- the Pensum tickets done;
- `.fabrica/notes/<version>.md`, the highlights a person writes.
The highlights go first.
## Screenshots
`apps/web/e2e/specs/aula.spec.ts`, project `aula` of `apps/web/playwright.config.ts` (docs/fabrica.md part 5). For
each shot of `apps/web/tests/demo.ts` SHOTS, it:
1. loads the page at 1440 × 900, scale 1, at the suite's fixed instant;
2. clicks the shot's selectors;
3. waits for its selector, for no `aria-busy` element, for the fonts, two frames and 400 ms;
4. saves `target/e2e/aula/<name>.png`.
The suite's global setup builds the UI and serves it on `127.0.0.1` with `/api/v1` answered by the demo control plane.
| 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, and the e2e suite checks every page it visits the same way (`realLooking`), so a real name
cannot slip in through a later fixture.
## Risks
| Risk | Answer |
| :-- | :-- |
| A screenshot or video shows Mark's network | The UI talks only to the demo control plane. The demo data test and the e2e suite's `realLooking` check refuse 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`, and the UI's own CSP allows no outside requests. Playwright's profile is temporary. |
| A secret reaches the browser | The demo serves no token, key or certificate. |
| A forged screenshot, note or archive | They are release assets under `SHA256SUMS`, signed by `domi-release` through Custos. The Gitea text is not signed; the asset is. |
| The source archive is not the tag | It is `git archive` of the run's HEAD, the tag's commit in the run's clean worktree. Anyone can repeat it and compare the SHA-256. |
| A shot of a half-drawn screen | Each `wait` selector exists only once the screen's data is there. The page has no `aria-busy` element, and the fonts and two frames are awaited. |
## Gaps
- Tested on Windows with Edge only. The suite is plain Playwright and should work in Chromium on Linux, but that is
untested.
- One size (desktop). There is no phone layout shot.
- The release does not run the Rust tests (see above).
- No `[repo] Release:` step: the version in `Cargo.toml`, `Cargo.lock` and the `package.json`s is changed by hand
before tagging.
- The flows' videos are not published yet (docs/fabrica.md part 5).
## Handover: releasing a version
1. On main, set the version in `Cargo.toml`, `Cargo.lock` and both `package.json`s. `node scripts/check-version.mjs
X.Y.Z` must pass. Write `.fabrica/notes/X.Y.Z.md`.
2. Tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z`.
3. Start the `release` pipeline at `vX.Y.Z` from Fabrica. No Gitea webhook reaches the hub yet, so use the hub's
`POST /api/runs` with ref `vX.Y.Z`.
4. Approve on the Custos card, then sign `SHA256SUMS` on Custos (`domi-release`).
5. Check the Gitea release `vX.Y.Z`. Its text is the notes. Its files are `ianitor-X.Y.Z-src.tar.gz`,
`release-notes.md`, `release-notes.json`, five `aula-*.png`, `aula.json`, `aula-page.json`, `SHA256SUMS` and
`SHA256SUMS.minisig`.
6. Deploy as before: Fabrica's *Apps* → Ianitor → *Deploy*, then run deploy/test-access.sh from a LAN machine.
+2 -1
View File
@@ -545,4 +545,5 @@ Recorded by the Phase 3 implementation (branch `phase-3`); docs/api.md has the c
10 minutes. 10 minutes.
- New host field `device_certs` (bool): only Domi device certificates on the allow list get in. - New host field `device_certs` (bool): only Domi device certificates on the allow list get in.
- `overview.paused_reason` gives the underlying code (`apply.needs_attention`, - `overview.paused_reason` gives the underlying code (`apply.needs_attention`,
`control.files_unwritten`, `repo.*`) next to `paused {code: "control.paused"}`. `control.files_unwritten`, `repo.*`) next to `paused {code: "control.paused"}`, and
`overview.paused_detail` the technical detail behind it (for "Show details").
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@ianitor/ui", "name": "@ianitor/ui",
"version": "0.1.0", "version": "0.2.0",
"private": true, "private": true,
"license": "MPL-2.0", "license": "MPL-2.0",
"description": "The shared dark Domi theme (murex palette) and its Svelte components.", "description": "The shared dark Domi theme (murex palette) and its Svelte components.",
+26 -3
View File
@@ -16,6 +16,7 @@
onclose, onclose,
escape = true, escape = true,
closable = true, closable = true,
toggle,
children, children,
footer, footer,
}: { }: {
@@ -26,6 +27,8 @@
onclose: () => void; onclose: () => void;
escape?: boolean; escape?: boolean;
closable?: boolean; closable?: boolean;
/** A popover's opener (a CSS selector): a click there is the opener's, which toggles it. */
toggle?: string;
children?: Snippet; children?: Snippet;
footer?: Snippet; footer?: Snippet;
} = $props(); } = $props();
@@ -39,12 +42,32 @@
if (modal && typeof el.showModal === "function") el.showModal(); if (modal && typeof el.showModal === "function") el.showModal();
else if (typeof el.show === "function") el.show(); else if (typeof el.show === "function") el.show();
else el.setAttribute("open", ""); else el.setAttribute("open", "");
const first = el.querySelector<HTMLElement>( const first =
"[data-autofocus], input:not([type=hidden]):not([readonly]):not([type=radio]), textarea, select", el.querySelector<HTMLElement>("[data-autofocus]") ??
); el.querySelector<HTMLElement>("input:not([type=hidden]):not([readonly]):not([type=radio]), textarea:not([readonly]), select");
(first ?? el.querySelector<HTMLElement>(".ia-dialog-title"))?.focus(); (first ?? el.querySelector<HTMLElement>(".ia-dialog-title"))?.focus();
} }
// A dialog opened with show() (the popover) gets no cancel event: Esc and a click outside
// close it here, like the modal ones.
const key = (e: KeyboardEvent) => {
if (!modal && e.key === "Escape" && escape) {
e.preventDefault();
onclose();
}
};
const down = (e: PointerEvent) => {
if (!modal && escape && el && e.target instanceof Node && !el.contains(e.target)) {
if (toggle && e.target instanceof Element && e.target.closest(toggle)) return;
onclose();
}
};
document.addEventListener("keydown", key);
// On the next turn, so the click that opened the popover does not close it.
const t = setTimeout(() => document.addEventListener("pointerdown", down), 0);
return () => { return () => {
clearTimeout(t);
document.removeEventListener("keydown", key);
document.removeEventListener("pointerdown", down);
if (opener instanceof HTMLElement && document.contains(opener)) opener.focus(); if (opener instanceof HTMLElement && document.contains(opener)) opener.focus();
}; };
}); });
+15 -2
View File
@@ -12,6 +12,15 @@
@import "@fontsource/manrope/latin-400.css"; @import "@fontsource/manrope/latin-400.css";
@import "@fontsource/manrope/latin-600.css"; @import "@fontsource/manrope/latin-600.css";
@import "@fontsource/manrope/latin-700.css"; @import "@fontsource/manrope/latin-700.css";
/* latin-ext: Czech names and places (č, ř, ů) in host names, device names and messages. */
@import "@fontsource/cinzel/latin-ext-500.css";
@import "@fontsource/cormorant-garamond/latin-ext-500.css";
@import "@fontsource/cormorant-garamond/latin-ext-600.css";
@import "@fontsource/manrope/latin-ext-400.css";
@import "@fontsource/manrope/latin-ext-600.css";
@import "@fontsource/manrope/latin-ext-700.css";
html, body { margin: 0; }
.ia .sr-only { .ia .sr-only {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden;
@@ -98,7 +107,10 @@
.ia .ia-engine small { color: var(--muted); font-weight: 400; font-size: 0.86rem; } .ia .ia-engine small { color: var(--muted); font-weight: 400; font-size: 0.86rem; }
/* ── Lists and rows (§2.5) ──────────────────────────────────────────────── */ /* ── Lists and rows (§2.5) ──────────────────────────────────────────────── */
.ia .ia-list { border: 1px solid var(--hairline); border-radius: var(--radius-lg); overflow: hidden; } .ia .ia-list { border: 1px solid var(--hairline); border-radius: var(--radius-lg); }
/* No overflow clipping on the list: a row's menu must reach past it. The end rows carry the corners. */
.ia .ia-list > :first-child { border-top-left-radius: calc(var(--radius-lg) - 1px); border-top-right-radius: calc(var(--radius-lg) - 1px); }
.ia .ia-list > :last-child { border-bottom-left-radius: calc(var(--radius-lg) - 1px); border-bottom-right-radius: calc(var(--radius-lg) - 1px); }
.ia .ia-row { display: grid; grid-template-columns: 128px minmax(0, 1.4fr) minmax(0, 1.6fr) 44px; gap: 16px; padding: 12px 10px 12px 18px; align-items: start; border-top: 1px solid var(--hairline); } .ia .ia-row { display: grid; grid-template-columns: 128px minmax(0, 1.4fr) minmax(0, 1.6fr) 44px; gap: 16px; padding: 12px 10px 12px 18px; align-items: start; border-top: 1px solid var(--hairline); }
.ia .ia-row:first-child { border-top: 0; } .ia .ia-row:first-child { border-top: 0; }
.ia .ia-row.head { background: var(--colonnade); padding-top: 10px; padding-bottom: 10px; align-items: center; } .ia .ia-row.head { background: var(--colonnade); padding-top: 10px; padding-bottom: 10px; align-items: center; }
@@ -121,6 +133,7 @@
background: none; color: var(--text-2); font-weight: 600; font-size: 0.92rem; text-align: left; cursor: pointer; background: none; color: var(--text-2); font-weight: 600; font-size: 0.92rem; text-align: left; cursor: pointer;
} }
.ia .ia-menu [role="menuitem"]:hover, .ia .ia-menu [role="menuitem"]:focus { background: var(--surface-2); color: var(--text); outline: none; } .ia .ia-menu [role="menuitem"]:hover, .ia .ia-menu [role="menuitem"]:focus { background: var(--surface-2); color: var(--text); outline: none; }
.ia .ia-menu [role="menuitem"]:focus-visible { outline: var(--focus-ring); outline-offset: -2px; }
.ia .ia-menu [role="menuitem"].danger { color: var(--danger); } .ia .ia-menu [role="menuitem"].danger { color: var(--danger); }
.ia .ia-menu [role="menuitem"][aria-disabled="true"] { color: var(--disabled); cursor: not-allowed; flex-wrap: wrap; padding-top: 6px; padding-bottom: 6px; } .ia .ia-menu [role="menuitem"][aria-disabled="true"] { color: var(--disabled); cursor: not-allowed; flex-wrap: wrap; padding-top: 6px; padding-bottom: 6px; }
.ia .ia-menu .reason { flex-basis: 100%; padding-left: 28px; font-weight: 400; font-size: var(--fs-sub); color: var(--muted); } .ia .ia-menu .reason { flex-basis: 100%; padding-left: 28px; font-weight: 400; font-size: var(--fs-sub); color: var(--muted); }
@@ -185,7 +198,7 @@
@media (max-width: 719.98px) { .ia .ia-toasts { right: 16px; left: 16px; bottom: calc(80px + env(safe-area-inset-bottom)); } } @media (max-width: 719.98px) { .ia .ia-toasts { right: 16px; left: 16px; bottom: calc(80px + env(safe-area-inset-bottom)); } }
.ia .ia-progress { height: 6px; border-radius: 3px; background: var(--surface-2); overflow: hidden; } .ia .ia-progress { height: 6px; border-radius: 3px; background: var(--surface-2); overflow: hidden; }
.ia .ia-progress > span { display: block; height: 100%; background: var(--accent); transition: width var(--dur-tick) linear; } .ia .ia-progress > span { display: block; height: 100%; background: var(--accent); transition: width var(--dur-tick) linear; }
.ia .ia-secret { display: block; width: 100%; background: var(--surface); border: 1px solid var(--control-edge); border-radius: var(--radius-sm); box-shadow: var(--carved); padding: 12px 14px; font-weight: 600; letter-spacing: 0.02em; word-break: break-all; color: var(--text); font: inherit; } .ia .ia-secret { display: block; width: 100%; background: var(--surface); border: 1px solid var(--control-edge); border-radius: var(--radius-sm); box-shadow: var(--carved); padding: 12px 14px; font: inherit; font-weight: 600; letter-spacing: 0.02em; word-break: break-all; overflow-wrap: anywhere; white-space: pre-wrap; color: var(--text); resize: none; }
.ia .ia-details pre { background: var(--surface); border-radius: var(--radius-sm); color: var(--muted); font-size: var(--fs-sub); white-space: pre-wrap; padding: 10px 12px; margin: 6px 0; } .ia .ia-details pre { background: var(--surface); border-radius: var(--radius-sm); color: var(--muted); font-size: var(--fs-sub); white-space: pre-wrap; padding: 10px 12px; margin: 6px 0; }
.ia .ia-frame { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 32px; text-align: center; } .ia .ia-frame { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 32px; text-align: center; }
.ia .ia-card { background: var(--surface); border: 1px solid var(--hairline); border-radius: var(--radius); padding: 12px 14px; } .ia .ia-card { background: var(--surface); border: 1px solid var(--hairline); border-radius: var(--radius); padding: 12px 14px; }
+1
View File
@@ -17,6 +17,7 @@ export const ICONS = {
building: "M4 21V5l8-3 8 3v16M9 21v-5h6v5M8 8h2M14 8h2M8 12h2M14 12h2", building: "M4 21V5l8-3 8 3v16M9 21v-5h6v5M8 8h2M14 8h2M8 12h2M14 12h2",
swap: "M7 7h13l-4-4M17 17H4l4 4", swap: "M7 7h13l-4-4M17 17H4l4 4",
copy: "M9 9h11v11H9zM5 15H4V4h11v1", copy: "M9 9h11v11H9zM5 15H4V4h11v1",
download: "M12 4v11M7 10l5 5 5-5M5 20h14",
chevron: "M6 9l6 6 6-6", chevron: "M6 9l6 6 6-6",
dots: "M5 12h.01M12 12h.01M19 12h.01", dots: "M5 12h.01M12 12h.01M19 12h.01",
close: "M6 6l12 12M18 6 6 18", close: "M6 6l12 12M18 6 6 18",
+80 -25
View File
@@ -14,18 +14,24 @@ importers:
specifier: workspace:* specifier: workspace:*
version: link:../../packages/ui version: link:../../packages/ui
devDependencies: devDependencies:
'@playwright/test':
specifier: 1.56.1
version: 1.56.1
'@sveltejs/vite-plugin-svelte': '@sveltejs/vite-plugin-svelte':
specifier: ^5.0.3 specifier: ^5.0.3
version: 5.1.1(svelte@5.57.3)(vite@6.4.5) version: 5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))
'@testing-library/svelte': '@testing-library/svelte':
specifier: ^5.2.6 specifier: ^5.2.6
version: 5.4.2(svelte@5.57.3)(vite@6.4.5)(vitest@3.2.7(jsdom@26.1.0)) version: 5.4.2(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))(vitest@3.2.7(@types/node@22.20.5)(jsdom@26.1.0))
'@testing-library/user-event': '@testing-library/user-event':
specifier: ^14.6.1 specifier: ^14.6.1
version: 14.6.8(@testing-library/dom@10.4.2) version: 14.6.8(@testing-library/dom@10.4.2)
'@tsconfig/svelte': '@tsconfig/svelte':
specifier: ^5.0.4 specifier: ^5.0.4
version: 5.0.8 version: 5.0.8
'@types/node':
specifier: ^22.20.5
version: 22.20.5
jsdom: jsdom:
specifier: ^26.0.0 specifier: ^26.0.0
version: 26.1.0 version: 26.1.0
@@ -40,10 +46,10 @@ importers:
version: 5.9.3 version: 5.9.3
vite: vite:
specifier: ^6.1.0 specifier: ^6.1.0
version: 6.4.5 version: 6.4.5(@types/node@22.20.5)
vitest: vitest:
specifier: ^3.0.5 specifier: ^3.0.5
version: 3.2.7(jsdom@26.1.0) version: 3.2.7(@types/node@22.20.5)(jsdom@26.1.0)
packages/ui: packages/ui:
dependencies: dependencies:
@@ -286,6 +292,11 @@ packages:
'@jridgewell/trace-mapping@0.3.31': '@jridgewell/trace-mapping@0.3.31':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@playwright/test@1.56.1':
resolution: {integrity: sha512-vSMYtL/zOcFpvJCW71Q/OEGQb7KYBPAdKh35WNSkaZA75JlAO8ED8UN6GUNTm3drWomcbcqRPFqQbLae8yBTdg==}
engines: {node: '>=18'}
hasBin: true
'@rollup/rollup-android-arm-eabi@4.68.0': '@rollup/rollup-android-arm-eabi@4.68.0':
resolution: {integrity: sha512-Ta2n0ntLfzP0LqwwcXOIh2z0mnHjlxMS+h4Y9lo+w33Quyf9KFKEi9QZ2IKqeEBKr0qxNpXc/DQjz5KVIs8AEA==} resolution: {integrity: sha512-Ta2n0ntLfzP0LqwwcXOIh2z0mnHjlxMS+h4Y9lo+w33Quyf9KFKEi9QZ2IKqeEBKr0qxNpXc/DQjz5KVIs8AEA==}
cpu: [arm] cpu: [arm]
@@ -484,6 +495,9 @@ packages:
'@types/estree@1.0.10': '@types/estree@1.0.10':
resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==}
'@types/node@22.20.5':
resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==}
'@vitest/expect@3.2.7': '@vitest/expect@3.2.7':
resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==} resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==}
@@ -642,6 +656,11 @@ packages:
picomatch: picomatch:
optional: true optional: true
fsevents@2.3.2:
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
fsevents@2.3.3: fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -736,6 +755,16 @@ packages:
resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
engines: {node: '>=12'} engines: {node: '>=12'}
playwright-core@1.56.1:
resolution: {integrity: sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==}
engines: {node: '>=18'}
hasBin: true
playwright@1.56.1:
resolution: {integrity: sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==}
engines: {node: '>=18'}
hasBin: true
postcss@8.5.32: postcss@8.5.32:
resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
engines: {node: ^10 || ^12 || >=14} engines: {node: ^10 || ^12 || >=14}
@@ -847,6 +876,9 @@ packages:
engines: {node: '>=14.17'} engines: {node: '>=14.17'}
hasBin: true hasBin: true
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
vite-node@3.2.4: vite-node@3.2.4:
resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==} resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==}
engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
@@ -1119,6 +1151,10 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2 '@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.6.0 '@jridgewell/sourcemap-codec': 1.6.0
'@playwright/test@1.56.1':
dependencies:
playwright: 1.56.1
'@rollup/rollup-android-arm-eabi@4.68.0': '@rollup/rollup-android-arm-eabi@4.68.0':
optional: true optional: true
@@ -1203,25 +1239,25 @@ snapshots:
'@sveltejs/load-config@0.2.3': {} '@sveltejs/load-config@0.2.3': {}
'@sveltejs/vite-plugin-svelte-inspector@4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5))(svelte@5.57.3)(vite@6.4.5)': '@sveltejs/vite-plugin-svelte-inspector@4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5)))(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))':
dependencies: dependencies:
'@sveltejs/vite-plugin-svelte': 5.1.1(svelte@5.57.3)(vite@6.4.5) '@sveltejs/vite-plugin-svelte': 5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))
debug: 4.4.3 debug: 4.4.3
svelte: 5.57.3 svelte: 5.57.3
vite: 6.4.5 vite: 6.4.5(@types/node@22.20.5)
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
'@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5)': '@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))':
dependencies: dependencies:
'@sveltejs/vite-plugin-svelte-inspector': 4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5))(svelte@5.57.3)(vite@6.4.5) '@sveltejs/vite-plugin-svelte-inspector': 4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5)))(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))
debug: 4.4.3 debug: 4.4.3
deepmerge: 4.3.1 deepmerge: 4.3.1
kleur: 4.1.5 kleur: 4.1.5
magic-string: 0.30.21 magic-string: 0.30.21
svelte: 5.57.3 svelte: 5.57.3
vite: 6.4.5 vite: 6.4.5(@types/node@22.20.5)
vitefu: 1.1.3(vite@6.4.5) vitefu: 1.1.3(vite@6.4.5(@types/node@22.20.5))
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
@@ -1240,14 +1276,14 @@ snapshots:
dependencies: dependencies:
svelte: 5.57.3 svelte: 5.57.3
'@testing-library/svelte@5.4.2(svelte@5.57.3)(vite@6.4.5)(vitest@3.2.7(jsdom@26.1.0))': '@testing-library/svelte@5.4.2(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))(vitest@3.2.7(@types/node@22.20.5)(jsdom@26.1.0))':
dependencies: dependencies:
'@testing-library/dom': 10.4.2 '@testing-library/dom': 10.4.2
'@testing-library/svelte-core': 1.1.3(svelte@5.57.3) '@testing-library/svelte-core': 1.1.3(svelte@5.57.3)
svelte: 5.57.3 svelte: 5.57.3
optionalDependencies: optionalDependencies:
vite: 6.4.5 vite: 6.4.5(@types/node@22.20.5)
vitest: 3.2.7(jsdom@26.1.0) vitest: 3.2.7(@types/node@22.20.5)(jsdom@26.1.0)
'@testing-library/user-event@14.6.8(@testing-library/dom@10.4.2)': '@testing-library/user-event@14.6.8(@testing-library/dom@10.4.2)':
dependencies: dependencies:
@@ -1266,6 +1302,10 @@ snapshots:
'@types/estree@1.0.10': {} '@types/estree@1.0.10': {}
'@types/node@22.20.5':
dependencies:
undici-types: 6.21.0
'@vitest/expect@3.2.7': '@vitest/expect@3.2.7':
dependencies: dependencies:
'@types/chai': 5.2.3 '@types/chai': 5.2.3
@@ -1274,13 +1314,13 @@ snapshots:
chai: 5.3.3 chai: 5.3.3
tinyrainbow: 2.0.0 tinyrainbow: 2.0.0
'@vitest/mocker@3.2.7(vite@6.4.5)': '@vitest/mocker@3.2.7(vite@6.4.5(@types/node@22.20.5))':
dependencies: dependencies:
'@vitest/spy': 3.2.7 '@vitest/spy': 3.2.7
estree-walker: 3.0.3 estree-walker: 3.0.3
magic-string: 0.30.21 magic-string: 0.30.21
optionalDependencies: optionalDependencies:
vite: 6.4.5 vite: 6.4.5(@types/node@22.20.5)
'@vitest/pretty-format@3.2.7': '@vitest/pretty-format@3.2.7':
dependencies: dependencies:
@@ -1419,6 +1459,9 @@ snapshots:
optionalDependencies: optionalDependencies:
picomatch: 4.0.7 picomatch: 4.0.7
fsevents@2.3.2:
optional: true
fsevents@2.3.3: fsevents@2.3.3:
optional: true optional: true
@@ -1515,6 +1558,14 @@ snapshots:
picomatch@4.0.7: {} picomatch@4.0.7: {}
playwright-core@1.56.1: {}
playwright@1.56.1:
dependencies:
playwright-core: 1.56.1
optionalDependencies:
fsevents: 2.3.2
postcss@8.5.32: postcss@8.5.32:
dependencies: dependencies:
nanoid: 3.3.20 nanoid: 3.3.20
@@ -1655,13 +1706,15 @@ snapshots:
typescript@5.9.3: {} typescript@5.9.3: {}
vite-node@3.2.4: undici-types@6.21.0: {}
vite-node@3.2.4(@types/node@22.20.5):
dependencies: dependencies:
cac: 6.7.14 cac: 6.7.14
debug: 4.4.3 debug: 4.4.3
es-module-lexer: 1.7.0 es-module-lexer: 1.7.0
pathe: 2.0.3 pathe: 2.0.3
vite: 6.4.5 vite: 6.4.5(@types/node@22.20.5)
transitivePeerDependencies: transitivePeerDependencies:
- '@types/node' - '@types/node'
- jiti - jiti
@@ -1676,7 +1729,7 @@ snapshots:
- tsx - tsx
- yaml - yaml
vite@6.4.5: vite@6.4.5(@types/node@22.20.5):
dependencies: dependencies:
esbuild: 0.25.12 esbuild: 0.25.12
fdir: 6.5.0(picomatch@4.0.7) fdir: 6.5.0(picomatch@4.0.7)
@@ -1685,17 +1738,18 @@ snapshots:
rollup: 4.68.0 rollup: 4.68.0
tinyglobby: 0.2.17 tinyglobby: 0.2.17
optionalDependencies: optionalDependencies:
'@types/node': 22.20.5
fsevents: 2.3.3 fsevents: 2.3.3
vitefu@1.1.3(vite@6.4.5): vitefu@1.1.3(vite@6.4.5(@types/node@22.20.5)):
optionalDependencies: optionalDependencies:
vite: 6.4.5 vite: 6.4.5(@types/node@22.20.5)
vitest@3.2.7(jsdom@26.1.0): vitest@3.2.7(@types/node@22.20.5)(jsdom@26.1.0):
dependencies: dependencies:
'@types/chai': 5.2.3 '@types/chai': 5.2.3
'@vitest/expect': 3.2.7 '@vitest/expect': 3.2.7
'@vitest/mocker': 3.2.7(vite@6.4.5) '@vitest/mocker': 3.2.7(vite@6.4.5(@types/node@22.20.5))
'@vitest/pretty-format': 3.2.7 '@vitest/pretty-format': 3.2.7
'@vitest/runner': 3.2.7 '@vitest/runner': 3.2.7
'@vitest/snapshot': 3.2.7 '@vitest/snapshot': 3.2.7
@@ -1713,10 +1767,11 @@ snapshots:
tinyglobby: 0.2.17 tinyglobby: 0.2.17
tinypool: 1.1.1 tinypool: 1.1.1
tinyrainbow: 2.0.0 tinyrainbow: 2.0.0
vite: 6.4.5 vite: 6.4.5(@types/node@22.20.5)
vite-node: 3.2.4 vite-node: 3.2.4(@types/node@22.20.5)
why-is-node-running: 2.3.0 why-is-node-running: 2.3.0
optionalDependencies: optionalDependencies:
'@types/node': 22.20.5
jsdom: 26.1.0 jsdom: 26.1.0
transitivePeerDependencies: transitivePeerDependencies:
- jiti - jiti
+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`);
+35
View File
@@ -0,0 +1,35 @@
// 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 one download (docs/release.md): the source of the commit being released, as
// target/release/ianitor-X.Y.Z-src.tar.gz (every file git tracks, under ianitor-X.Y.Z/)
// Ianitor ships no binary: the server builds it with Nix (docs/fabrica.md part 3). The archive is
// listed in the release's SHA256SUMS, signed by domi-release, so the source a version names can be
// checked. `git archive` of one tree gives the same bytes every time.
// node scripts/pack-source.mjs X.Y.Z
// Exit codes: 0 written, 1 git failed, 2 usage.
import { spawnSync } from "node:child_process";
import { mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const repo = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const version = process.argv[2];
if (process.argv.length !== 3 || !/^\d+\.\d+\.\d+$/.test(version)) {
console.error("usage: node scripts/pack-source.mjs X.Y.Z");
process.exit(2);
}
const out = join(repo, "target", "release");
mkdirSync(out, { recursive: true });
for (const n of readdirSync(out)) if (/^ianitor-.*-src\.tar\.gz$/.test(n)) rmSync(join(out, n), { force: true });
const file = join(out, `ianitor-${version}-src.tar.gz`);
const git = spawnSync("git", ["archive", "--format=tar.gz", `--prefix=ianitor-${version}/`, "-o", file, "HEAD"], { cwd: repo, stdio: "inherit" });
if (git.error || git.status !== 0) {
console.error(`pack-source: git archive failed${git.error ? `: ${git.error.message}` : ` (exit ${git.status})`}`);
process.exit(1);
}
console.log(`pack-source: ${file} (${statSync(file).size} bytes)`);