55 Commits

Author SHA1 Message Date
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
mnovak b24ffdf9db [control] Design review: Caddy differences per host in fallback_ready, active apply kind, hosts and watch end, capped device end date, CSR fingerprint for signing by hand, crash points exit without SIGABRT 2026-11-08 11:21:43 +01:00
mnovak 3bf5fa0e1a [control] QC minors: device install links open a page and download on POST (never listed), approve and install failures show on the request and the CLI waits, PBKDF2 floor, private pki dirs or an error, trusted_proxies for a proxy in front, a placeholder keeps the device allow list from being empty (Caddy refuses that) 2026-11-08 11:02:50 +01:00
mnovak bc336d1188 [repo] NixOS and docs: Caddy admin socket for changes under Caddy, polkit start/stop only, edge never stops restarting, openssl in the VM tests, beside-Caddy without secrets in argv, pinned Ianitor rev, X-Served-By trial marker 2026-11-08 10:49:42 +01:00
mnovak e84eb1ba74 [control] Fix round 1: changes apply while Caddy serves (admin socket, watch through Caddy), revocations that fail are errors and catch up, proof only on the forward-auth UI host, root keys found by content, intermediates checked before install, stale SNI cleared before each handshake 2026-11-08 10:49:31 +01:00
mnovak 0749119f19 [tests] Tests first, fix round 1: proof only on the forward-auth UI host, revocations that cannot be written, root key files by content, intermediates that cannot issue, stale SNI after a failed or resumed handshake, edge re-reads the allow list, changes apply while Caddy serves, Hostname focus (red) 2026-11-08 10:26:31 +01:00
mnovak e2a777882c [control] Root-key refusal test: a control that does not refuse is killed after 20 s instead of hanging the suite 2026-11-08 00:10:26 +01:00
mnovak b85c38f615 [repo] VM tests: no clash with the driver's log name (the drivers of all four build) 2026-11-08 00:06:37 +01:00
mnovak ca9bf3fdd4 [repo] NixOS: flake with the release build (test hooks off) and the web UI, services.ianitor module (edge, control, caddy-fallback, engine-select, per-boot UI proof, polkit for exactly two units), four VM tests, deploy/test-access.sh 2026-11-08 00:04:13 +01:00
mnovak a61dfd854f [web] Decisions applied: openssl signing by hand with the .ext file, Sign out link, renew soon 30 days before a device certificate ends 2026-11-07 23:48:44 +01:00
mnovak 9933f55242 [control] Mark's UI decisions: Remote-Name shown with the proof, [ui] logout_url for Sign out, openssl signing files for the manual intermediate step, engine.not_ready, server sentences for the eight generic codes 2026-11-07 23:48:43 +01:00
mnovak 3e326e85a0 [web] The web UI: hosts, add/edit with apply progress, undo, history and restore, share links, engine switch, certificates and device installs, signing by hand, settings and tokens; smoke test counts every §4 flow's clicks 2026-11-07 23:44:27 +01:00
mnovak aed5fbfcff [control] Overview for the UI: who is looking (viewer) and the underlying pause reason, so the UI offers the right action 2026-11-07 23:44:25 +01:00
mnovak f9dd2247f8 [control] Dev mode: a throw-away Domi root signs the first intermediate at start, so tls = "domi" works for any name; --ui-dir serves a built UI 2026-11-07 23:24:45 +01:00
mnovak 6237e721d6 [control] Test hooks: IANITOR_TEST_CRASH_AT and IANITOR_TEST_FAIL_WRITE only with the default test-hooks feature; a --no-default-features build has neither 2026-11-07 23:23:51 +01:00
mnovak 12886a1d31 [control] Engine switch: POST /engine through a Units abstraction (systemctl via polkit, a fake in tests); engine file first, back to the old engine if the new one does not serve; changes and share links wait while Caddy serves 2026-11-07 23:22:59 +01:00
mnovak c18ae154ad [control] Domi CA and UI sign-in: intermediate renewal by CSR with manual offline signing, domi host certificates, device requests approved by code, one-time PKCS#12 installs, revocation; Remote-User trusted only with edge's per-boot proof 2026-11-07 23:21:49 +01:00
mnovak 211b851c3e [control] Tests first: Domi CA flows through the API (offline-signed intermediate, domi host chains, device approval by code, one-time install, revocation, no root key) and UI sign-in that refuses a forged Remote-User (red) 2026-11-07 23:11:05 +01:00
mnovak a5190acc3b [edge] Device certificates as Caddy does them: no certificate on a device host fails the handshake, a Host other than the SNI name is 421; diff corpus gains six device cases 2026-11-07 22:55:37 +01:00
mnovak 3d8f524d00 [edge] Device certificates: mTLS on hosts with device_certs only (asked per SNI), chain to the Domi CA bundle and the allow list in the handshake, checked again per request; 403 without one 2026-11-07 22:49:32 +01:00
mnovak 4054427b62 [edge] Tests first: a Domi device cert is accepted for mTLS, a self-signed one with the same subject, an unlisted one and none are not (red) 2026-11-07 22:46:08 +01:00
mnovak 18da3f5d5a [core] Device certificates: device_certs host field; edge config v3 and Caddy client_authentication with a CA bundle and an allow list, 403 without a certificate 2026-11-07 22:46:07 +01:00
mnovak dc23bfe842 [core] Domi CA: offline root (10 y, pathLen 1), intermediate from a CSR (1 y, pathLen 0), server (90 d) and device (1 y) leaves, encrypted keys, match codes 2026-11-07 22:41:29 +01:00
mnovak cde0c3ea3b [core] Tests first: the Domi CA chains to the root, a leaf cannot sign, expired and wrong-name certs are rejected (red) 2026-11-07 22:40:56 +01:00
mnovak 7cb5715580 [docs] Custos ticket: the CSR-signing operation with match-code approval that Custos does not have yet 2026-11-07 22:40:38 +01:00
mnovak cb04bff74e [repo] Merge: Mark's decisions on the open points (PR #4) 2026-11-07 22:18:05 +01:00
151 changed files with 21700 additions and 156 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.
## 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/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.
@@ -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/fuzz cargo-fuzz targets.
deploy/nixos NixOS module + VM tests.
scripts the release's version check. Releases (notes, screenshots): docs/release.md.
## Commands
cargo test --workspace # quote test counts per crate; an exit code alone is not green
cargo run -p ianitor-control -- --dev
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 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.
- $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.
- 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.
- 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.
Generated
+503 -12
View File
@@ -2,6 +2,41 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "aead"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
dependencies = [
"crypto-common 0.2.2",
"inout",
]
[[package]]
name = "aes"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
dependencies = [
"cipher",
"cpubits",
"cpufeatures 0.3.1",
]
[[package]]
name = "aes-gcm"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f"
dependencies = [
"aead",
"aes",
"cipher",
"ctr",
"ctutils",
"ghash",
]
[[package]]
name = "ahash"
version = "0.8.12"
@@ -281,6 +316,12 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bit-vec"
version = "0.9.1"
@@ -302,7 +343,7 @@ version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest",
"digest 0.10.7",
]
[[package]]
@@ -314,6 +355,24 @@ dependencies = [
"generic-array",
]
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]]
name = "block-padding"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
dependencies = [
"hybrid-array",
]
[[package]]
name = "brotli"
version = "3.5.0"
@@ -352,6 +411,15 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cbc"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
dependencies = [
"cipher",
]
[[package]]
name = "cc"
version = "1.11.1"
@@ -376,6 +444,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"rand_core 0.10.1",
]
[[package]]
name = "chrono"
version = "0.4.45"
@@ -385,6 +464,17 @@ dependencies = [
"num-traits",
]
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"block-buffer 0.12.1",
"crypto-common 0.2.2",
"inout",
]
[[package]]
name = "clap"
version = "4.6.7"
@@ -434,6 +524,24 @@ dependencies = [
"cc",
]
[[package]]
name = "cmov"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "cms"
version = "0.3.0-rc.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e99ff55bfffd019bf15e3f0d5edef2ca1e3af5ade276ed100e3c0c3455050c2"
dependencies = [
"const-oid",
"der",
"spki",
"x509-cert",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
@@ -459,6 +567,12 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "const-oid"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]]
name = "const-random"
version = "0.1.18"
@@ -505,6 +619,12 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -514,6 +634,15 @@ dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.4"
@@ -554,6 +683,33 @@ dependencies = [
"typenum",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
]
[[package]]
name = "ctr"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21"
dependencies = [
"cipher",
]
[[package]]
name = "ctutils"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
[[package]]
name = "daemonix"
version = "0.1.0"
@@ -591,6 +747,19 @@ version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "der"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
dependencies = [
"const-oid",
"der_derive",
"flagset",
"pem-rfc7468",
"zeroize",
]
[[package]]
name = "der-parser"
version = "9.0.0"
@@ -619,6 +788,17 @@ dependencies = [
"rusticata-macros",
]
[[package]]
name = "der_derive"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "deranged"
version = "0.5.9"
@@ -636,17 +816,38 @@ dependencies = [
"syn 1.0.109",
]
[[package]]
name = "des"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "916a94e407b54f9034d71dd748234cd1e516ced6284009906ae246f177eafe5a"
dependencies = [
"cipher",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"block-buffer 0.10.4",
"crypto-common 0.1.7",
"subtle",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer 0.12.1",
"const-oid",
"crypto-common 0.2.2",
"ctutils",
]
[[package]]
name = "displaydoc"
version = "0.2.7"
@@ -658,6 +859,21 @@ dependencies = [
"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]]
name = "equivalent"
version = "1.0.3"
@@ -706,6 +922,12 @@ version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
[[package]]
name = "flagset"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
[[package]]
name = "flate2"
version = "1.1.11"
@@ -879,6 +1101,16 @@ dependencies = [
"cfg-if",
"libc",
"r-efi 6.0.0",
"rand_core 0.10.1",
]
[[package]]
name = "ghash"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5"
dependencies = [
"polyval",
]
[[package]]
@@ -947,6 +1179,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest 0.11.3",
]
[[package]]
name = "http"
version = "1.5.0"
@@ -992,6 +1233,15 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
]
[[package]]
name = "hyper"
version = "1.12.0"
@@ -1054,7 +1304,7 @@ dependencies = [
[[package]]
name = "ianitor-control"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"axum",
"base64 0.22.1",
@@ -1064,23 +1314,30 @@ dependencies = [
"ianitor-edge",
"ianitor-testkit",
"log",
"rcgen",
"p12-keystore",
"qrcode",
"ring",
"rpassword",
"rustls",
"rustls-pki-types",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tokio-rustls",
"toml",
"utoipa",
]
[[package]]
name = "ianitor-core"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"base64 0.22.1",
"domi-pki",
"ring",
"rustls-pki-types",
"rustls-webpki",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -1091,12 +1348,13 @@ dependencies = [
[[package]]
name = "ianitor-diff"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"ianitor-control",
"ianitor-core",
"ianitor-edge",
"ianitor-testkit",
"rcgen",
"rustls",
"serde_json",
"tokio",
@@ -1104,7 +1362,7 @@ dependencies = [
[[package]]
name = "ianitor-edge"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"arc-swap",
"async-trait",
@@ -1119,6 +1377,7 @@ dependencies = [
"instant-acme",
"log",
"pingora",
"rcgen",
"ring",
"rustls",
"rustls-pki-types",
@@ -1131,7 +1390,7 @@ dependencies = [
[[package]]
name = "ianitor-testkit"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"bytes",
"futures-util",
@@ -1274,6 +1533,16 @@ dependencies = [
"serde_core",
]
[[package]]
name = "inout"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
dependencies = [
"block-padding",
"hybrid-array",
]
[[package]]
name = "instant-acme"
version = "0.8.5"
@@ -1606,6 +1875,29 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "p12-keystore"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c2ed4fa0ec7ec58b657d4184680c57da9e203e97771d29a566028869a5193e0"
dependencies = [
"cbc",
"cms",
"der",
"des",
"hex",
"hmac",
"pkcs12",
"pkcs5",
"pkcs8",
"rand 0.10.3",
"rc2",
"sha1 0.11.0",
"sha2",
"thiserror 2.0.21",
"x509-parser 0.18.1",
]
[[package]]
name = "parking"
version = "2.2.1"
@@ -1635,6 +1927,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "pbkdf2"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
dependencies = [
"digest 0.11.3",
"hmac",
]
[[package]]
name = "pem"
version = "4.0.0"
@@ -1645,6 +1947,15 @@ dependencies = [
"serde_core",
]
[[package]]
name = "pem-rfc7468"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9"
dependencies = [
"base64ct",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -1935,12 +2246,64 @@ dependencies = [
"tokio",
]
[[package]]
name = "pkcs12"
version = "0.2.0-rc.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fd993500a1de8a428a2e6cc9a2ec942c99a801a88d58a24fb986c5ad3b767ca"
dependencies = [
"cms",
"const-oid",
"der",
"digest 0.11.3",
"spki",
"x509-cert",
"zeroize",
]
[[package]]
name = "pkcs5"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca"
dependencies = [
"aes",
"aes-gcm",
"cbc",
"der",
"pbkdf2",
"scrypt",
"sha2",
"spki",
]
[[package]]
name = "pkcs8"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "polyval"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd"
dependencies = [
"cpubits",
"cpufeatures 0.3.1",
"universal-hash",
]
[[package]]
name = "potential_utf"
version = "0.1.6"
@@ -1987,6 +2350,12 @@ dependencies = [
"yansi",
]
[[package]]
name = "qrcode"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
[[package]]
name = "quote"
version = "1.0.47"
@@ -2029,6 +2398,17 @@ dependencies = [
"rand_core 0.9.5",
]
[[package]]
name = "rand"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"chacha20",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
@@ -2067,6 +2447,21 @@ dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rc2"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ceda21af1ae61033b63175653a1af86cae399d79cd03ca80ba347eb3a6c4a7fe"
dependencies = [
"cipher",
]
[[package]]
name = "rcgen"
version = "0.14.10"
@@ -2152,6 +2547,27 @@ dependencies = [
"serde",
]
[[package]]
name = "rpassword"
version = "7.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196"
dependencies = [
"libc",
"rtoolbox",
"windows-sys 0.61.2",
]
[[package]]
name = "rtoolbox"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "rust_decimal"
version = "1.43.0"
@@ -2288,6 +2704,16 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "salsa20"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c"
dependencies = [
"cfg-if",
"cipher",
]
[[package]]
name = "same-file"
version = "1.0.6"
@@ -2312,6 +2738,18 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "scrypt"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0"
dependencies = [
"cfg-if",
"pbkdf2",
"salsa20",
"sha2",
]
[[package]]
name = "security-framework"
version = "2.11.1"
@@ -2466,8 +2904,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"digest 0.11.3",
]
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"digest 0.11.3",
]
[[package]]
@@ -2524,6 +2984,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "spki"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -2924,7 +3394,7 @@ dependencies = [
"httparse",
"log",
"rand 0.9.5",
"sha1",
"sha1 0.10.7",
"thiserror 2.0.21",
]
@@ -2955,6 +3425,16 @@ dependencies = [
"tinyvec",
]
[[package]]
name = "universal-hash"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
dependencies = [
"crypto-common 0.2.2",
"ctutils",
]
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
@@ -3196,6 +3676,17 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "x509-cert"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b"
dependencies = [
"const-oid",
"der",
"spki",
]
[[package]]
name = "x509-parser"
version = "0.16.0"
+3 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"]
[workspace.package]
version = "0.1.0"
version = "0.2.0"
edition = "2024"
rust-version = "1.89"
license = "MPL-2.0"
@@ -13,6 +13,8 @@ publish = false
ianitor-core = { path = "crates/core" }
ianitor-edge = { path = "crates/edge" }
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_json = "1.0.145"
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"]
}
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="dark" />
<meta name="referrer" content="no-referrer" />
<title>Hosts — Ianitor Domi</title>
</head>
<body class="ia">
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+26 -3
View File
@@ -1,10 +1,33 @@
{
"name": "web",
"version": "0.0.0",
"version": "0.2.0",
"private": true,
"license": "MPL-2.0",
"description": "Ianitor Domi web UI (Svelte 5). Placeholder until phase 3.",
"description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.",
"type": "module",
"scripts": {
"dev": "node -e \"console.log('web: placeholder, the UI arrives in phase 3; nothing is listening')\""
"dev": "vite",
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings && tsc -p e2e/tsconfig.json",
"test": "vitest run",
"test:e2e": "playwright test --project=web",
"aula:shots": "playwright test --project=aula"
},
"dependencies": {
"@ianitor/ui": "workspace:*"
},
"devDependencies": {
"@playwright/test": "1.56.1",
"@sveltejs/vite-plugin-svelte": "^5.0.3",
"@testing-library/svelte": "^5.2.6",
"@testing-library/user-event": "^14.6.1",
"@tsconfig/svelte": "^5.0.4",
"@types/node": "^22.20.5",
"jsdom": "^26.0.0",
"svelte": "^5.20.0",
"svelte-check": "^4.1.4",
"typescript": "^5.7.3",
"vite": "^6.1.0",
"vitest": "^3.0.5"
}
}
+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 },
],
});
+175
View File
@@ -0,0 +1,175 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// The shell (handoff §2.16): sidebar on desktop, top and bottom bars on phone, the routes,
// the banners every screen starts with, toasts and the signed-out dialog (§10).
import { onMount } from "svelte";
import { Button, Dialog, Icon } from "@ianitor/ui";
import type { IconName } from "@ianitor/ui";
import EngineChip from "./components/EngineChip.svelte";
import EnginePopover from "./components/EnginePopover.svelte";
import TopBanners from "./components/TopBanners.svelte";
import { app, navigate, refresh, startPolling } from "./lib/app.svelte";
import { remembered } from "./lib/applies";
import Certificates from "./views/Certificates.svelte";
import History from "./views/History.svelte";
import Hosts from "./views/Hosts.svelte";
import RenewByHand from "./views/RenewByHand.svelte";
import Settings from "./views/Settings.svelte";
import SignedIn from "./views/SignedIn.svelte";
const route = $derived.by(() => {
const u = new URL(app.path, "http://x");
const p = u.pathname.replace(/\/+$/, "") || "/";
const seg = p.split("/").filter(Boolean).map(decodeURIComponent);
if (p === "/signed-in") return { view: "signed-in" as const };
if (seg[0] === "history") return { view: "history" as const, host: u.searchParams.get("host") ?? undefined, pick: seg[1] };
if (seg[0] === "certificates") return { view: seg[1] === "renew-by-hand" ? ("renew" as const) : ("certs" as const), newDevice: seg[1] === "new" };
if (seg[0] === "settings") return { view: "settings" as const, tab: seg[1] ?? "general" };
return { view: "hosts" as const, newHost: seg[0] === "hosts" && seg[1] === "new", edit: seg[0] === "hosts" && seg[2] === "edit" ? seg[1] : undefined };
});
const NAV: { href: string; label: string; icon: IconName; views: string[] }[] = [
{ href: "/", label: "Hosts", icon: "building", views: ["hosts"] },
{ href: "/history", label: "History", icon: "history", views: ["history"] },
{ href: "/certificates", label: "Certificates", icon: "shield", views: ["certs", "renew"] },
{ href: "/settings/general", label: "Settings", icon: "gear", views: ["settings"] },
];
const TITLES: Record<string, string> = { hosts: "Hosts", history: "History", certs: "Certificates", renew: "Certificates", settings: "Settings", "signed-in": "Signed in" };
$effect(() => {
document.title = `${TITLES[route.view] ?? "Hosts"} — Ianitor Domi`;
});
onMount(() => {
if (route.view === "signed-in") return;
const stop = startPolling();
// Resume an apply this tab was watching before a reload or a sign-in (§3).
const id = remembered();
if (id && route.view === "hosts") app.panel = { kind: "host", resume: id };
let ch: BroadcastChannel | undefined;
try {
ch = new BroadcastChannel("ianitor-auth");
ch.onmessage = (m) => {
if (m.data === "signed-in") {
app.signedOut = false;
void refresh();
}
};
} catch {
/* no BroadcastChannel: "I have signed in" still works */
}
return () => {
stop();
ch?.close();
};
});
function go(e: MouseEvent, href: string) {
if (e.metaKey || e.ctrlKey || e.shiftKey) return;
e.preventDefault();
navigate(href);
}
function signIn() {
const w = window.open("/signed-in", "ianitor-sign-in");
if (!w) {
// The new tab was blocked: this tab goes to the sign-in, so an open form is saved first
// (sessionStorage, this tab only) and comes back after it (§10).
window.dispatchEvent(new Event("ianitor:save-draft"));
location.href = `/signed-in?back=${encodeURIComponent(app.path)}`;
}
}
async function signedInAgain() {
app.signedOut = false;
await refresh();
}
const viewer = $derived(app.overview?.viewer ?? null);
</script>
{#if route.view === "signed-in"}
<SignedIn />
{:else}
<a class="skip domi-btn" href="#main">Skip to content</a>
<div class="shell">
<nav class="sidebar" aria-label="Main">
<div class="ia-wordmark brand">IANITOR DOMI</div>
{#each NAV as n (n.href)}
<a href={n.href} class="nav" aria-current={n.views.includes(route.view) ? "page" : undefined} onclick={(e) => go(e, n.href)}><Icon name={n.icon} />{n.label}</a>
{/each}
<div class="foot ia-muted">
<p>{viewer?.via === "authelia" ? `Signed in as ${viewer.name} through Authelia` : viewer ? `Using the API token "${viewer.name}"` : "Signed in through Authelia"}</p>
<p>Control on 127.0.0.1 only</p>
{#if app.overview?.site?.auth_logout_url}<a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a>{/if}
</div>
</nav>
<header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span>{#if app.phone}<EngineChip />{/if}</header>
<main id="main" tabindex="-1">
<TopBanners />
{#if route.view === "hosts"}
<Hosts route={{ newHost: route.newHost, edit: route.edit }} />
{:else if route.view === "history"}
{#key route.host}<History host={route.host} pick={route.pick} />{/key}
{:else if route.view === "certs"}
<Certificates newDevice={route.newDevice} />
{:else if route.view === "renew"}
<RenewByHand />
{:else if route.view === "settings"}
<Settings tab={route.tab} />
{/if}
</main>
<nav class="bottombar" aria-label="Main">
{#each NAV as n (n.href)}
<a href={n.href} aria-current={n.views.includes(route.view) ? "page" : undefined} onclick={(e) => go(e, n.href)}><Icon name={n.icon} /><span>{n.label}</span></a>
{/each}
</nav>
</div>
{#if app.panel?.kind === "engine"}
<EnginePopover onclose={() => {
app.panel = null;
document.querySelector<HTMLElement>("[data-engine-chip]")?.focus();
}} />
{/if}
<div class="ia-toasts" role="status" aria-live="polite">
{#each app.toasts as t (t.id)}<div class="ia-toast"><Icon name="check" />{t.text}</div>{/each}
</div>
{#if app.signedOut}
<Dialog title="Your sign-in has ended" role="alertdialog" escape={false} closable={false} onclose={() => {}}>
<p>Sign in again; this page keeps what you typed.</p>
{#snippet footer()}
<Button onclick={signedInAgain}>I have signed in</Button>
<Button variant="primary" onclick={signIn} data-autofocus>Sign in</Button>
{/snippet}
</Dialog>
{/if}
{/if}
<style>
.shell { display: grid; grid-template-columns: var(--sidebar-w) minmax(0, 1fr); min-height: 100dvh; }
.sidebar { background: var(--colonnade); border-right: 1px solid var(--hairline); padding: 22px 14px; display: flex; flex-direction: column; gap: 4px; position: sticky; top: 0; height: 100dvh; }
.brand { padding: 4px 10px 18px; }
.nav { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-nav); text-decoration: none; border: 1px solid transparent; }
.nav:hover { background: var(--surface); color: var(--text); }
.nav[aria-current="page"] { background: var(--surface-2); color: var(--text); box-shadow: var(--inset-lit); border-color: color-mix(in srgb, var(--accent) 30%, transparent); }
.nav[aria-current="page"] :global(svg) { color: var(--accent); }
.foot { margin-top: auto; font-size: 0.82rem; display: flex; flex-direction: column; gap: 4px; padding: 0 10px; }
main { padding: var(--main-pad); display: flex; flex-direction: column; gap: 18px; min-width: 0; outline: none; }
.topbar, .bottombar { display: none; }
@media (max-width: 719.98px) {
.shell { grid-template-columns: minmax(0, 1fr); }
.sidebar { display: none; }
.topbar { display: flex; align-items: center; justify-content: space-between; background: var(--colonnade); border-bottom: 1px solid var(--hairline); padding: 10px 16px; }
.topbar .ia-wordmark { font-size: 12px; letter-spacing: 0.26em; }
main { padding: 18px 16px calc(90px + env(safe-area-inset-bottom)); gap: 14px; }
.bottombar { display: grid; grid-template-columns: repeat(4, 1fr); position: fixed; left: 0; right: 0; bottom: 0; background: var(--colonnade); border-top: 1px solid var(--hairline); padding: 6px 8px calc(10px + env(safe-area-inset-bottom)); z-index: 40; }
.bottombar a { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: var(--phone-bar-h); border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-tab-phone); text-decoration: none; }
.bottombar a[aria-current="page"] { background: var(--surface-2); color: var(--text); }
.bottombar a[aria-current="page"] :global(svg) { color: var(--accent); }
}
</style>
@@ -0,0 +1,80 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §7.1: the apply checklist, its countdown and the queued state.
import { Button, Icon, Progress } from "@ianitor/ui";
import type { ApplyView } from "../lib/types";
import { app, secondsLeft } from "../lib/app.svelte";
let { apply, oncancel }: { apply: ApplyView; oncancel?: () => void } = $props();
const engine = $derived(app.overview?.engine.running === "caddy" ? "Caddy" : "Pingora");
const watchSeconds = $derived(app.overview?.site?.watch_seconds ?? 60);
const left = $derived(apply.watch ? secondsLeft(apply.watch.ends_at) : watchSeconds);
const st = (k: string) => apply.steps.find((s) => s.key === k)?.state ?? "pending";
const merged = (a: string, b: string) => {
const x = st(a);
const y = st(b);
if (x === "failed" || y === "failed") return "failed";
if (x === "running" || y === "running") return "running";
if (x === "done" && (y === "done" || y === "skipped")) return "done";
return x;
};
const noWatch = $derived(apply.reason?.code === "apply.kept.no_watch");
const rows = $derived([
{ s: st("validate"), t: { pending: "Check the host file", running: "Checking the host file", done: "Checked the host file", failed: "The host file did not pass the check", skipped: "Check the host file" } },
{ s: merged("compile", "write"), t: { pending: "Build the Pingora and Caddy settings", running: "Building the Pingora and Caddy settings", done: "Built the Pingora and Caddy settings", failed: "Could not build the settings", skipped: "Build the Pingora and Caddy settings" } },
{ s: st("reload"), t: { pending: `Reload ${engine}`, running: `Reloading ${engine}`, done: `Reloaded ${engine}, no connections dropped`, failed: `${engine} did not take the new settings`, skipped: `Reload ${engine}` } },
{
s: st("watch"),
t: noWatch
? { pending: "Check that it answers", running: `Checking that it answers: ${left} s left`, done: "It answers", failed: "Health checks failed", skipped: "Nothing to watch: the host is removed." }
: { pending: `Watch health checks for ${watchSeconds} s`, running: `Watching health checks: ${left} s left`, done: `Health checks passed for ${watchSeconds} s`, failed: "Health checks failed", skipped: "Nothing to watch: the host is removed." },
},
]);
const prefix: Record<string, string> = { done: "Done:", running: "Now:", pending: "Next:", failed: "Failed:", skipped: "Skipped:" };
const final = $derived(["kept", "reverted", "failed", "needs_attention"].includes(apply.state));
</script>
{#if apply.state === "queued"}
<p class="ia-status" data-s="running">
<Icon name="clock" />
<span>
Waiting for "{apply.queue?.waiting_for?.summary ?? "another change"}" to finish{apply.queue?.waiting_for?.seconds_left != null
? `, about ${apply.queue.waiting_for.seconds_left} s`
: ""}.
{#if (apply.queue?.position ?? 1) > 1}{(apply.queue?.position ?? 1) - 1} other changes are ahead of this one.{/if}
</span>
</p>
{#if oncancel}<div><Button onclick={oncancel}>Cancel</Button></div>{/if}
{:else}
<ol class="steps">
{#each rows as r, i (i)}
<li class={r.s}>
{#if r.s === "done"}<Icon name="check" />{:else if r.s === "running"}<Icon name="clock" />{:else if r.s === "failed"}<Icon name="ring" />{:else}<span class="hollow" aria-hidden="true"></span>{/if}
<span><span class="sr-only">{prefix[r.s]}</span>{r.t[r.s as keyof typeof r.t]}</span>
</li>
{/each}
{#if st("watch") === "failed" && !final}
<li class="running"><Icon name="clock" /><span><span class="sr-only">Now:</span>Undoing the change</span></li>
{/if}
</ol>
{#if apply.state === "watching"}
<Progress label="Health watch" max={watchSeconds} now={watchSeconds - left} text="{left} seconds left" />
<p class="ia-hint">You can leave this screen. Other changes wait their turn; only one apply runs at a time.</p>
{/if}
{/if}
<style>
.steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
.steps li { display: flex; gap: 10px; align-items: center; }
.steps li.pending { color: var(--muted); }
.steps li.running { color: var(--text); }
.steps li.running :global(svg) { color: var(--accent); }
.steps li.done { color: var(--text-2); }
.steps li.done :global(svg) { color: var(--kept); }
.steps li.failed :global(svg) { color: var(--down); }
.steps li.skipped { color: var(--muted); }
.hollow { width: 14px; height: 14px; border-radius: 50%; border: 2px solid var(--muted); margin: 2px; }
</style>
+165
View File
@@ -0,0 +1,165 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §7.4 and §7.5: the last-change bar with Undo (1 click), and the reverted / not
// applied banner that stands in for its first line.
import { Banner, Button, Details, Icon, Progress } from "@ianitor/ui";
import { ApiError, call, del, newKey, post, sentence } from "../lib/api";
import { app, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { atTime, firstSentence, when } from "../lib/format";
import type { ApplyView } from "../lib/types";
let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props();
const o = $derived(app.overview);
const last = $derived(o?.last_apply ?? null);
const active = $derived(o?.active_apply ?? null);
const undo = $derived(o?.undo ?? null);
let moved = $state<string | null>(null);
let undoing = $state(false);
let pushing = $state(false);
const dismissKey = $derived(last ? `apply:${last.id}` : "");
function runningHeading(summary: string, a: { kind: string; hosts: string[]; summary: string } | null): string {
if (!a) return summary;
const h = a.hosts[0] ?? "";
switch (a.kind) {
case "add": return `Adding ${h}`;
case "remove": return `Removing ${h}`;
case "edit": return `Changing ${h}`;
case "share_links": return `Turning on share links for ${h}`;
case "undo": return `Undoing: ${a.summary.replace(/^Undid: /, "")}`;
case "restore": return a.summary.replace(/^Restored /, "Restoring ");
default: return summary;
}
}
async function doUndo() {
if (!undo?.target) return;
undoing = true;
moved = null;
try {
await post("/undo", { target_change_id: undo.target.change_id });
await refresh();
} catch (e) {
if (e instanceof ApiError && e.code === "undo.target_moved") {
moved = e.body.message;
await refresh();
} else {
moved = sentence(e);
}
} finally {
undoing = false;
}
}
async function pushNow() {
pushing = true;
try {
await call("POST", "/repo/push", {}, { idem: newKey() });
} catch {
/* the bar shows the push state on the next poll */
} finally {
pushing = false;
await refresh();
}
}
async function cancel(id: string) {
try {
await del(`/applies/${encodeURIComponent(id)}`);
toast("Cancelled before it started. Nothing changed.");
await refresh();
} catch (e) {
moved = sentence(e);
}
}
const keptLine = $derived.by(() => {
if (!last || last.state !== "kept") return "";
const t = when(last.finished_at ?? last.created_at, app.now);
const code = last.reason?.code ?? "";
if (code === "apply.kept.no_watch") return `${last.hosts[0] ?? ""} has no health check, so Ianitor only checked that it answers.`;
const what = code === "apply.kept.removed" ? "removed" : code === "apply.kept.no_edge" ? "saved, nothing checked (development mode)" : `health checks passed for ${o?.site?.watch_seconds ?? 60} s`;
const push = last.push?.state === "pushed" ? `pushed to Gitea as ${last.commit_short}` : last.push?.state === "pending" ? "sending to Gitea" : last.commit_short ? `saved as commit ${last.commit_short}` : "";
return [t, what, push].filter(Boolean).join(" · ");
});
const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed");
const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null);
// Ticks every second on the local clock (§7.2), not only on the 5 s poll.
const watchLeft = $derived(
active?.watch_ends_at ? secondsLeft(active.watch_ends_at) : active?.seconds_left != null ? active.seconds_left : null,
);
// The outcome's offer, by code (§7.5).
const offer = $derived.by(() => {
const c = last?.reason?.code ?? "";
if (/^apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
if (/^apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: last?.reason?.field ?? undefined };
if (/^apply\.failed\.(reload|build|edge_unreachable)$/.test(c)) return null;
if (last?.attempted_host) return { label: "Edit and try again", field: last?.reason?.field ?? undefined };
return null;
});
const pushLine = $derived.by(() => {
const p = last?.push;
const remote = "Gitea";
switch (p?.error_code) {
case "push.failed.rejected": return `Kept, but ${remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server.`;
case "push.failed.auth": return `Kept, but ${remote} refused Ianitor's access key. Check the key in Custos.`;
default: return `Kept, but not yet saved to ${remote}: ${remote} did not answer.${p?.next_try_at ? ` Ianitor tries again ${atTime(p.next_try_at, app.now)}.` : " Ianitor tries again by itself."}`;
}
});
const canPushNow = $derived(pushFailed && last?.push?.error_code !== "push.failed.rejected");
</script>
{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)}
{@const parts = firstSentence(last.reason?.message ?? "")}
<Banner tone="notice" ondismiss={() => (app.dismissed = [...app.dismissed, dismissKey])}>
{#snippet title()}<span class="ia-status" data-s="reverted"><Icon name="undo" /><span class="word">{last.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
{#if parts[1]}Reason: {parts[1]}{/if}
{#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")}<Details detail={last.reason.detail} />{/if}
{#snippet actions()}
{#if offer}<Button variant="outline" onclick={() => onedit(last, offer?.field)}>{offer.label}</Button>{/if}
{/snippet}
</Banner>
{/if}
{#if last || active}
<section class="ia-bar" aria-label="Last change">
{#if active}
<div class="grow">
<div class="ia-status" data-s="running"><Icon name="clock" /><span class="word">{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"}</span>
<span>{runningHeading(active.summary, active.kind ? active : null)}</span></div>
<div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : active.state === "watching" ? `${watchLeft ?? 0} s left` : "Checking and loading the change"}</div>
{#if active.state === "watching" && watchLeft != null}
{@const total = o?.site?.watch_seconds ?? 60}
<Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" />
{/if}
</div>
{#if active.state === "queued"}<Button onclick={() => cancel(active.id)}>Cancel</Button>{:else}<button type="button" class="domi-btn link" onclick={() => onshowsteps(active.id)}>Show steps</button>{/if}
{:else if last}
<div class="grow">
{#if last.state === "kept"}
<div><span class="ia-status" data-s="kept"><Icon name="check" /><span class="word">kept</span></span> {last.summary}</div>
<div class="ia-sub" class:warn={pushFailed}>{pushFailed ? pushLine : keptLine}</div>
{:else if undo?.target}
<div>Undo: {undo.target.summary}</div>
{/if}
{#if undo?.effect && (last.state !== "kept" || undo?.target?.change_id !== last.change_id)}<div class="ia-sub">{undo.effect}</div>{/if}
{#if moved}<div class="ia-sub" role="status">{moved}</div>{/if}
{#if undoReason}<div class="ia-sub" id="undo-reason">{undoReason}</div>{/if}
{#if !undo?.target}<div class="ia-sub">Nothing to undo yet.</div>{/if}
</div>
{#if canPushNow}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if}
{#if undo?.target}
<Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available}
describedby={undoReason ? "undo-reason" : undefined}
label="Undo: {undo.target.summary}.{undo.effect ? ' ' + undo.effect + '.' : ''}">Undo</Button>
{/if}
{/if}
</section>
{/if}
<style>
.warn { color: var(--degraded); }
</style>
+29
View File
@@ -0,0 +1,29 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §2.4: the engine chip (click 1 of the switch). On the main screen's header on a
// desktop, in the top bar on a phone (§2.16).
import { Icon } from "@ianitor/ui";
import { app } from "../lib/app.svelte";
const o = $derived(app.overview);
const engineName = $derived(o?.engine.running === "caddy" ? "Caddy" : "Pingora");
const engineLabel = $derived(
o?.engine.state === "switching" ? "Engine: switching" : `Engine: ${engineName}${o?.engine.state === "stopped" ? ", not answering" : ""}. Change engine`,
);
</script>
{#if o}
<button type="button" class="ia-engine" data-engine-chip aria-haspopup="dialog" aria-expanded={app.panel?.kind === "engine"} aria-label={engineLabel}
onclick={() => (app.panel = app.panel?.kind === "engine" ? null : { kind: "engine" })}>
{#if o.engine.state === "switching"}<Icon name="clock" /> Engine Switching…{:else}
<span class="ia-status" data-s={o.engine.state === "stopped" ? "down" : "healthy"}><span class="ia-dot"></span></span>
<small class="desktop">Engine</small> {engineName}{#if o.engine.running === "caddy"} <small>(fallback)</small>{/if}{/if}
<Icon name="chevron" />
</button>
{/if}
<style>
@media (max-width: 719.98px) { .desktop { display: none; } }
</style>
@@ -0,0 +1,121 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §9: the engine popover. Click 1 is the chip, click 2 "Switch to Caddy" (the popover
// is the confirmation). The switch runs in control; this polls GET /engine until it ends.
import { onDestroy, onMount } from "svelte";
import { Banner, Button, Details, Dialog, Icon, Progress } from "@ianitor/ui";
import { call, get, newKey, sentence } from "../lib/api";
import { app, refresh } from "../lib/app.svelte";
import { whenInline } from "../lib/format";
import type { EngineView } from "../lib/types";
let { onclose }: { onclose: () => void } = $props();
const e = $derived(app.overview?.engine ?? null);
const running = $derived(e?.running ?? "pingora");
const name = $derived(running === "caddy" ? "Caddy" : "Pingora");
const other = $derived(running === "caddy" ? "Pingora" : "Caddy");
const target = $derived(running === "caddy" ? "pingora" : "caddy");
let switching = $state(false);
let problem = $state<string | null>(null);
let timer: ReturnType<typeof setTimeout> | undefined;
onDestroy(() => clearTimeout(timer));
let activeLinks = $state(0);
onMount(async () => {
try {
const l = await get<{ items: { state: string }[] }>("/share-links", { quiet: true });
activeLinks = l.items.filter((x) => x.state === "active").length;
} catch {
/* the count is only a hint */
}
});
const fr = $derived(e?.fallback_ready ?? null);
const differs = $derived(fr ? fr.compared - fr.matched : 0);
const notReady = $derived(running === "pingora" && !e?.fallback_ready?.built_at);
const disabledReason = $derived(!e?.switchable ? "This server does not let Ianitor switch engines." : notReady ? "Caddy is not ready: its settings have not been built yet." : null);
async function doSwitch() {
problem = null;
switching = true;
const from = name;
const to = other;
try {
await call("POST", "/engine", { target }, { idem: newKey() });
const poll = async () => {
try {
const v = await get<EngineView>("/engine", { quiet: true });
if (v.state === "switching") {
timer = setTimeout(poll, 1000);
return;
}
switching = false;
await refresh();
if (v.last_error) {
app.switchResult = { ok: false, title: `${to} did not start, so ${from} is serving again.`, text: "Visitors had a short break and nothing else changed.", detail: v.last_error.detail ?? null };
} else {
app.switchResult = { ok: true, title: `Now serving with ${to}.`, text: "Switch back from the engine chip at any time; it is the same 2 clicks." };
}
onclose();
} catch {
// Contact may drop for a few seconds while the engines change (§9.2).
timer = setTimeout(poll, 1000);
}
};
timer = setTimeout(poll, 500);
} catch (err) {
switching = false;
problem = sentence(err);
}
}
</script>
<Dialog title={e?.state === "stopped" ? `${name} is not answering` : `Serving with ${name}`} kind="popover" modal={false} escape={!switching} toggle="[data-engine-chip]" {onclose}>
<p class="ia-label">Engine</p>
{#if e?.state === "stopped"}
<p>Visitors may not reach any host. Switching to {other} is the quickest way back.</p>
{:else}
<p class="ia-text2">
{#if e?.since}Since {whenInline(e.since, app.now)}. {/if}
{#if running === "pingora"}
{#if notReady}Caddy is not ready: its settings have not been built yet.{:else if differs > 0}Caddy was built {whenInline(fr?.built_at, app.now)} with the same routes, but {differs} of {fr?.compared} {fr?.compared === 1 ? "host" : "hosts"} {differs === 1 ? "behaves" : "behave"} differently on it.{:else}Caddy is ready with the same routes: built {whenInline(fr?.built_at, app.now)}{fr?.compared ? (fr.compared === 1 ? ", and the host behaves the same" : `, and all ${fr.compared} hosts behave the same`) : ""}.{/if}
{#if !notReady && !fr?.current} It is rebuilt from the current routes when you switch.{/if}
{:else}Pingora is ready with the same routes.{/if}
</p>
{#if running === "pingora" && !notReady && fr?.differences.length}
<Details detail={fr.differences.join("\n")} />
{/if}
{/if}
<div class="ia-card">
<p><strong>What happens</strong></p>
<ul>
<li>{name} stops and {other} starts. New visits reach {other} in about 2 seconds.</li>
<li>Open connections close; videos and uploads in progress restart.</li>
<li>Hosts and certificates stay the same.</li>
{#if running === "pingora"}
<li>Share links stop working while Caddy serves: visitors with a link get the normal sign-in. They work again when you switch back.{#if activeLinks}{" "}{activeLinks === 1 ? "1 share link is" : `${activeLinks} share links are`} active.{/if}</li>
<li>Changes keep working: Ianitor tries each one on Caddy and undoes it if a host stops answering.</li>
{:else}
<li>Share links work again.</li>
{/if}
<li>This page may lose contact for a few seconds.</li>
</ul>
</div>
{#if switching}
<p class="ia-status" data-s="running" role="status"><Icon name="clock" /><strong>Switching to {other}</strong></p>
<Progress label="Switching engine" max={1} now={0} text="{name} stopping, starting {other}" />
{/if}
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if disabledReason}<p class="ia-hint" id="switch-reason">{disabledReason}</p>{/if}
{#snippet footer()}
<Button onclick={onclose}>Cancel</Button>
<Button variant={e?.state === "stopped" ? "primary" : "outline"} icon="swap" onclick={doSwitch} pending={switching}
disabled={!!disabledReason} describedby={disabledReason ? "switch-reason" : undefined}>Switch to {other}</Button>
{/snippet}
</Dialog>
<style>
ul { margin: 6px 0 0; padding-left: 1.1rem; color: var(--text-2); }
</style>
+142
View File
@@ -0,0 +1,142 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §2.5 and §5.1: the host list, sorted down, degraded, pending, unknown, healthy.
import { Status } from "@ianitor/ui";
import type { StatusKind } from "@ianitor/ui";
import HostMenu from "./HostMenu.svelte";
import { app, changesBlocked } from "../lib/app.svelte";
import { ago, duration } from "../lib/format";
import type { HostRow } from "../lib/types";
let {
hosts,
onedit,
onremove,
onshare,
onhistory,
onretry,
}: {
hosts: HostRow[];
onedit: (h: string) => void;
onremove: (h: string) => void;
onshare: (h: string) => void;
onhistory: (h: string) => void;
onretry: (h: string) => void;
} = $props();
const ORDER: Record<string, number> = { down: 0, degraded: 1, pending: 2, unknown: 3, healthy: 4 };
const sorted = $derived([...hosts].sort((a, b) => (ORDER[a.health.state] ?? 5) - (ORDER[b.health.state] ?? 5) || a.hostname.localeCompare(b.hostname)));
const running = $derived(app.overview?.active_apply ? (app.overview.last_apply?.hosts ?? []) : []);
const underCaddy = $derived(app.overview?.engine.running === "caddy");
function kind(h: HostRow): [StatusKind, string] {
switch (h.health.state) {
case "healthy": return ["healthy", "healthy"];
case "degraded": return ["degraded", "degraded"];
case "down": return ["down", "down"];
case "pending": return ["unknown", "waiting"];
default: return ["unknown", "not checked"];
}
}
function since(h: HostRow): string {
return h.health.since ? duration((app.now - Date.parse(h.health.since)) / 1000) : "a while";
}
function sub(h: HostRow): { text: string; problem: boolean } {
const f = h.health.failure;
const visitors = 'Visitors get an error page.';
switch (h.health.state) {
case "healthy": {
const added = h.added_at && app.now - Date.parse(h.added_at) < 86_400_000 ? "Added today · c" : "C";
const lat = h.health.latency_ms != null && !underCaddy ? ` · ${h.health.latency_ms} ms` : "";
return { text: `${added}hecked ${ago(h.health.last_check_at, app.now)}${lat}`, problem: false };
}
case "degraded": {
const ok = h.health.upstreams.filter((u) => u.state === "healthy").length;
const m = h.health.upstreams.length;
if (m > 1) return { text: `${ok} of ${m} addresses answer. Visitors are sent to the ones that do.`, problem: true };
return { text: `Answering only some checks.`, problem: true };
}
case "down":
if (f?.kind === "refused") return { text: `Connection refused for ${since(h)}. ${visitors}`, problem: true };
if (f?.kind === "timeout") return { text: `Not answering for ${since(h)}. ${visitors}`, problem: true };
if (f?.kind === "name") return { text: `The name ${f.upstream ?? ""} cannot be found. ${visitors}`, problem: true };
if (f?.kind === "tls") return { text: `The certificate of ${f.upstream ?? ""} cannot be checked.`, problem: true };
return { text: `Answering with an error page for ${since(h)}.`, problem: true };
case "pending": return { text: "Waiting for the first check.", problem: false };
default: return { text: "No health check set for this host.", problem: false };
}
}
function phoneDetail(h: HostRow): string {
if (h.health.state === "healthy" && h.health.latency_ms != null) return `${h.health.latency_ms} ms`;
if (h.health.state === "down" && h.health.failure?.kind === "refused") return `refused for ${since(h)}`;
if (h.health.state === "unknown") return "no health check";
if (h.added_at && app.now - Date.parse(h.added_at) < 86_400_000) return "added today";
return h.share_links ? "share links on" : "";
}
function chips(h: HostRow): string[] {
const c = [h.tls === "domi" ? "Domi certificate" : "Let's Encrypt"];
c.push(h.auth === "forward-auth" ? "Sign-in first" : "Open to anyone");
if (h.share_links) c.push("Share links on");
if (h.device_certs) c.push("Device certificate needed");
if (!h.websockets) c.push("No websockets");
return c;
}
const blocked = $derived(changesBlocked());
const shareReason = $derived(!app.overview?.site?.share_links_available ? (underCaddy ? "Share links are off while Caddy serves." : "Share links are not set up on this server.") : null);
</script>
<div class="ia-list" role="table" aria-label="Hosts">
<div class="ia-row head" role="row">
<span class="ia-label col-status" role="columnheader">Status</span>
<span class="ia-label" role="columnheader">Host</span>
<span class="ia-label desktop" role="columnheader">Sends traffic to</span>
<span role="columnheader"><span class="sr-only">More</span></span>
</div>
{#each sorted as h (h.hostname)}
{@const [k, w] = kind(h)}
{@const s = sub(h)}
<div class="ia-row" role="row">
<span class="col-status" role="cell"><Status kind={k} word={w} /></span>
<span role="cell">
<span class="phone-dot"><Status kind={k} word="" /></span>
<span class="ia-host">{h.hostname}</span>
<span class="ia-chips desktop">{#each chips(h) as c (c)}<span class="ia-chip">{c}</span>{/each}</span>
<span class="ia-sub phone">{w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}</span>
</span>
<span role="cell" class="desktop">
<span>{h.upstreams[0] ?? ""}</span>{#if h.upstreams.length > 1}{" "}<span class="ia-muted">+{h.upstreams.length - 1} more</span>{/if}
<span class="ia-sub" class:problem={s.problem} style="display:block">{running.includes(h.hostname) ? "Changing now · " : ""}{s.text}</span>
{#if h.certificate.state === "pending"}<span class="ia-sub" style="display:block">Waiting for Let's Encrypt to issue the certificate.</span>{/if}
{#if h.certificate.state === "failed"}
<span class="ia-sub" style="display:block;color:var(--down)">Let's Encrypt could not confirm <strong>{h.hostname}</strong>. The name must point to this server, and port 80 must be open from the internet.
<button type="button" class="domi-btn link" onclick={() => onretry(h.hostname)}>Try again</button></span>
{/if}
</span>
<span role="cell">
<HostMenu hostname={h.hostname} items={[
{ label: "Share link", icon: "link", reason: shareReason, run: () => onshare(h.hostname) },
{ label: "Edit host", icon: "pencil", reason: blocked, run: () => onedit(h.hostname) },
{ label: "Show in history", icon: "history", run: () => onhistory(h.hostname) },
{ label: "Remove host", icon: "trash", danger: true, divider: true, reason: blocked, run: () => onremove(h.hostname) },
]} />
</span>
</div>
{/each}
</div>
<style>
.phone, .phone-dot { display: none; }
.problem { color: var(--text-2) !important; }
@media (max-width: 719.98px) {
.desktop { display: none !important; }
.phone { display: block; padding-left: 22px; }
.phone-dot { display: inline; }
}
</style>
+88
View File
@@ -0,0 +1,88 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts" module>
import type { IconName } from "@ianitor/ui";
export interface Item {
label: string;
icon: IconName;
danger?: boolean;
reason?: string | null;
divider?: boolean;
run: () => void;
}
</script>
<script lang="ts">
// Handoff §2.6: the row's ⋯ menu (WAI-ARIA menu button).
import { tick } from "svelte";
import { Icon } from "@ianitor/ui";
let { hostname, items }: { hostname: string; items: Item[] } = $props();
let open = $state(false);
let btn: HTMLButtonElement | undefined = $state();
let list: HTMLUListElement | undefined = $state();
const id = "menu-" + Math.random().toString(36).slice(2, 9);
const nodes = () => Array.from(list?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? []);
async function show(focus: "first" | "last" = "first") {
open = true;
await tick();
const n = nodes();
(focus === "first" ? n[0] : n[n.length - 1])?.focus();
}
function close(back = true) {
open = false;
if (back) btn?.focus();
}
function key(e: KeyboardEvent) {
const n = nodes();
const i = n.indexOf(document.activeElement as HTMLElement);
if (e.key === "ArrowDown") { e.preventDefault(); n[(i + 1) % n.length]?.focus(); }
else if (e.key === "ArrowUp") { e.preventDefault(); n[(i - 1 + n.length) % n.length]?.focus(); }
else if (e.key === "Home") { e.preventDefault(); n[0]?.focus(); }
else if (e.key === "End") { e.preventDefault(); n[n.length - 1]?.focus(); }
else if (e.key === "Escape") { e.preventDefault(); close(); }
else if (e.key === "Tab") close(false);
}
function pick(it: Item) {
if (it.reason) return;
// Focus back on More first: a dialog the item opens returns focus there when it closes
// (§2.9), not to a menu item that no longer exists.
close(true);
it.run();
}
function outside(e: MouseEvent) {
if (open && !(e.target instanceof Node && (list?.contains(e.target) || btn?.contains(e.target)))) close(false);
}
</script>
<svelte:window onclick={outside} />
<div class="ia-menu-wrap">
<button bind:this={btn} type="button" class="ia-icon-btn" aria-label="More for {hostname}" aria-haspopup="menu"
aria-expanded={open} aria-controls={id}
onclick={() => (open ? close() : show())}
onkeydown={(e) => { if (e.key === "ArrowDown") { e.preventDefault(); show("first"); } else if (e.key === "ArrowUp") { e.preventDefault(); show("last"); } }}>
<Icon name="dots" />
</button>
{#if open}
<ul bind:this={list} class="ia-menu" role="menu" id={id} aria-label={hostname} tabindex="-1" onkeydown={key}>
{#each items as it (it.label)}
{#if it.divider}<li role="separator"><hr /></li>{/if}
<li role="none">
<button type="button" role="menuitem" tabindex="-1" class:danger={it.danger} aria-disabled={it.reason ? "true" : undefined} onclick={() => pick(it)}>
<Icon name={it.icon} />{it.label}
{#if it.reason}<span class="reason">{it.reason}</span>{/if}
</button>
</li>
{/each}
</ul>
{/if}
</div>
+538
View File
@@ -0,0 +1,538 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §6 and §7: the add/edit panel, its validation on blur, Apply, and the progress and
// outcome of the apply it starts. Every decision comes from control; the form only carries it.
import { onDestroy, onMount } from "svelte";
import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui";
import ApplyProgress from "./ApplyProgress.svelte";
import { ApiError, call, del, get, newKey, sentence } from "../lib/api";
import { app, changesBlocked, refresh, restoreLastKept, toast } from "../lib/app.svelte";
import { FINAL, follow } from "../lib/applies";
import { firstSentence } from "../lib/format";
import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types";
let {
hostname,
resume,
prefill,
focusField,
onclose,
}: {
hostname?: string;
resume?: string;
prefill?: HostSpec | null;
focusField?: string;
onclose: () => void;
} = $props();
const site = $derived(app.overview?.site ?? null);
const signinOk = $derived(site?.forward_auth_configured ?? false);
// ---- the form
type Rule = { action: "set" | "remove"; name: string; kind: "value" | "secret"; value: string; secret: string };
let host = $state({
hostname: "",
upstreams: [""],
tls: "domi" as "domi" | "letsencrypt",
auth: "forward-auth" as "forward-auth" | "none",
websockets: true,
share_links: false,
device_certs: false,
access_log: "off" as "off" | "truncated",
hc: false,
hcPath: "/",
hcEvery: 30,
req: [] as Rule[],
resp: [] as Rule[],
});
let rev = $state<string | null>(null);
let more = $state(false);
let loading = $state(true);
let notFound = $state<string | null>(null);
let errors = $state<Record<string, ErrorBody>>({});
let touched = $state<Record<string, boolean>>({});
let summary = $state("");
let underFooter = $state("");
let conflict = $state<ErrorBody | null>(null);
let topError = $state<ApiError | null>(null);
let idem = newKey();
let lastBody = "";
// ---- the apply
let apply = $state<ApplyView | null>(null);
let restoring = $state(false);
let restoreProblem = $state<string | null>(null);
let phase = $state<"form" | "progress">("form");
let stop: (() => void) | undefined;
let closeTimer: ReturnType<typeof setTimeout> | undefined;
function fromSpec(s: HostSpec) {
host.hostname = s.hostname;
host.upstreams = s.upstreams.length ? [...s.upstreams] : [""];
host.tls = s.tls;
host.auth = s.auth;
host.websockets = s.websockets;
host.share_links = s.share_links;
host.device_certs = !!s.device_certs;
host.access_log = s.access_log;
host.hc = !!s.health_check;
host.hcPath = s.health_check?.path ?? "/";
host.hcEvery = s.health_check?.interval_secs ?? 30;
const rule = (r: HeaderRule): Rule => ({ action: r.action, name: r.name, kind: r.secret ? "secret" : "value", value: r.value ?? "", secret: r.secret ?? "" });
host.req = (s.request_headers ?? []).map(rule);
host.resp = (s.response_headers ?? []).map(rule);
if (host.hc || host.req.length || host.resp.length || !host.websockets || host.share_links || host.access_log !== "off" || host.device_certs) more = true;
}
function spec(): HostSpec {
const rules = (rs: Rule[]): HeaderRule[] =>
rs.map((r) =>
r.action === "remove"
? { action: "remove", name: r.name }
: r.kind === "secret"
? { action: "set", name: r.name, secret: r.secret }
: { action: "set", name: r.name, value: r.value },
);
// The UI always sends every field explicitly (the schema's own defaults differ).
return {
hostname: host.hostname.trim(),
upstreams: host.upstreams.map((u) => u.trim()).filter((u, i) => u !== "" || i === 0),
tls: host.tls,
auth: host.auth,
websockets: host.websockets,
share_links: host.share_links,
device_certs: host.device_certs,
access_log: host.access_log,
health_check: host.hc ? { path: host.hcPath, interval_secs: Number(host.hcEvery) } : null,
request_headers: rules(host.req),
response_headers: rules(host.resp),
};
}
onMount(async () => {
if (resume) {
phase = "progress";
stop = follow(resume, onApply);
}
if (prefill) {
fromSpec(prefill);
} else if (hostname) {
try {
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
fromSpec(d.host);
rev = d.rev;
} catch (e) {
notFound = sentence(e);
}
} else {
rev = app.overview?.rev ?? null;
if (!signinOk) host.auth = "none";
}
// A form saved before this tab went to sign in comes back (App.svelte, signIn).
try {
const raw = sessionStorage.getItem(DRAFT);
const d = raw ? (JSON.parse(raw) as { hostname: string; host: typeof host }) : null;
if (d && d.hostname === (hostname ?? "") && !resume) {
Object.assign(host, d.host);
more = more || d.host.hc || d.host.req.length > 0 || d.host.resp.length > 0;
}
sessionStorage.removeItem(DRAFT);
} catch {
/* no storage: nothing to bring back */
}
loading = false;
if (phase === "form") {
// The Dialog focused its heading while this said "Loading…": now the first field
// (Hostname; Send traffic to when editing), so typing right after opening works.
const f = focusField ?? (hostname ? "upstreams[0]" : "hostname");
if (f.startsWith("health_check")) more = true;
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
}
window.addEventListener("ianitor:save-draft", saveDraft);
});
const DRAFT = "ianitor-draft";
function saveDraft() {
if (phase !== "form") return;
try {
sessionStorage.setItem(DRAFT, JSON.stringify({ hostname: hostname ?? "", host: $state.snapshot(host) }));
} catch {
/* no storage */
}
}
onDestroy(() => {
stop?.();
clearTimeout(closeTimer);
if (typeof window !== "undefined") window.removeEventListener("ianitor:save-draft", saveDraft);
});
function fieldId(f: string): string {
return "f-" + f.replace(/[^a-z0-9]+/gi, "-");
}
const errAt = (f: string) => errors[f];
function setErrors(list: ErrorBody[], only?: string) {
const next: Record<string, ErrorBody> = only ? { ...errors } : {};
if (only) {
for (const k of Object.keys(next)) if (k === only || k.startsWith(only + "[")) delete next[k];
}
for (const e of list) {
const f = e.field ?? "";
if (!f) continue;
if (only && !(f === only || f.startsWith(only + "["))) continue;
next[f] = e;
}
errors = next;
}
// Validation on blur (§2.10): only the field that lost focus, debounced.
let blurTimer: ReturnType<typeof setTimeout> | undefined;
function blur(field: string) {
touched[field] = true;
clearTimeout(blurTimer);
blurTimer = setTimeout(async () => {
try {
await call("POST", `/hosts/validate?mode=${hostname ? "edit" : "create"}`, spec());
setErrors([], field);
} catch (e) {
if (e instanceof ApiError) setErrors(e.errors.length ? e.errors : [e.body], field);
}
}, 300);
}
async function submit(e?: Event) {
e?.preventDefault();
if (changesBlocked()) return;
const body = spec();
const text = JSON.stringify(body);
if (text !== lastBody) {
idem = newKey();
lastBody = text;
}
underFooter = "";
conflict = null;
topError = null;
try {
const path = hostname ? `/hosts/${encodeURIComponent(hostname)}` : "/hosts";
const a = await call<{ apply: ApplyView }>(hostname ? "PUT" : "POST", path, { host: body, base_rev: rev }, { idem });
const ap = a.data?.apply;
if (!ap) return;
apply = ap;
phase = "progress";
stop?.();
stop = follow(ap.id, onApply);
} catch (err) {
if (!(err instanceof ApiError)) {
topError = null;
underFooter = sentence(err);
return;
}
if (err.code === "change.conflict") {
conflict = err.body;
return;
}
if (err.code === "change.unchanged") {
underFooter = "This is the same as what is live now, so nothing changed.";
return;
}
const list = err.errors.length ? err.errors : err.body.field ? [err.body] : [];
if (list.length) {
setErrors(list);
for (const x of list) if (x.field) touched[x.field] = true;
summary = `${list.length} ${list.length === 1 ? "thing" : "things"} to fix before Apply.`;
const first = list.find((x) => x.field)?.field;
if (first?.startsWith("health_check") || first?.includes("headers")) more = true;
if (first) setTimeout(() => document.getElementById(fieldId(first))?.focus(), 0);
} else {
topError = err;
}
}
}
function onApply(a: ApplyView) {
apply = a;
if (a.state === "kept") {
if (a.kind !== "remove") app.focusHost = a.hosts[0] ?? null;
closeTimer = setTimeout(() => onclose(), 1500);
}
}
async function cancelQueued() {
if (!apply) return;
try {
await del(`/applies/${encodeURIComponent(apply.id)}`);
toast("Cancelled before it started. Nothing changed.");
stop?.();
phase = "form";
apply = null;
} catch (e) {
underFooter = sentence(e);
}
}
function editAgain(field?: string) {
stop?.();
phase = "form";
apply = null;
idem = newKey();
const f = field ?? "upstreams[0]";
if (f.startsWith("health_check")) {
more = true;
host.hc = true;
}
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
}
async function keepMine() {
if (!hostname) {
rev = app.overview?.rev ?? rev;
} else {
try {
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
rev = d.rev;
} catch {
/* keep the old rev */
}
}
await refresh();
if (!hostname) rev = app.overview?.rev ?? rev;
conflict = null;
}
async function useTheirs() {
if (!hostname) return;
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
fromSpec(d.host);
rev = d.rev;
conflict = null;
}
const name = $derived(host.hostname.trim() || hostname || "the host");
const heading = $derived.by(() => {
if (phase !== "progress" || !apply) return hostname ? `Edit ${hostname}` : "New host";
const h = apply.hosts[0] ?? name;
switch (apply.kind) {
case "add":
return `Adding ${h}`;
case "remove":
return `Removing ${h}`;
case "share_links":
return `Turning on share links for ${h}`;
case "undo":
return `Undoing: ${apply.summary.replace(/^Undid: /, "")}`;
case "restore":
return apply.summary.replace(/^Restored /, "Restoring ");
default:
return `Changing ${h}`;
}
});
const reasonOffer = $derived.by(() => {
const c = apply?.reason?.code ?? "";
if (/apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
if (/apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: "" };
if (c.startsWith("apply.reverted") || c === "apply.failed.validation" || c.startsWith("pki.")) return { label: "Edit and try again", field: apply?.reason?.field ?? undefined };
return null;
});
const blocked = $derived(changesBlocked());
const shareWarning = $derived(host.auth === "none" && host.share_links);
</script>
<Dialog title={heading} kind="panel" {onclose}>
{#if loading}
<p class="ia-muted">Loading…</p>
{:else if notFound}
<Banner tone="notice" live="status">{#snippet title()}{notFound}{/snippet}
{#snippet actions()}<Button onclick={onclose}>Back to hosts</Button>{/snippet}
</Banner>
{:else if phase === "progress" && apply}
<div aria-live="polite" class="sr-only">
{#if apply.state === "queued"}Waiting for another change to finish.{:else if apply.state === "watching"}Watching health checks.{:else if apply.state === "kept"}Kept. {apply.reason?.message}{:else if apply.state === "reverted"}Reverted. {apply.reason?.message}{:else if apply.state === "failed"}Not applied. {apply.reason?.message}{/if}
</div>
<ApplyProgress {apply} oncancel={cancelQueued} />
{#if apply.state === "kept"}
<Banner tone="kept">
{#snippet title()}<span class="ia-status" data-s="kept"><span class="word">kept</span></span> <strong>{apply?.hosts[0] ?? name}</strong> {apply?.kind === "remove" ? "is removed." : "is live."}{/snippet}
{(apply.reason?.message ?? "").replace(/^\S+ is (live|removed)\.\s*/, "")}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if}
</Banner>
{:else if apply.state === "reverted" || apply.state === "failed"}
{@const parts = firstSentence(apply.reason?.message ?? "")}
<Banner tone="notice" live="status">
{#snippet title()}<span class="ia-status" data-s="reverted"><span class="word">{apply?.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
{#if parts[1]}Reason: {parts[1]}{/if}
{#snippet actions()}
{#if reasonOffer}
<Button variant="outline" onclick={() => (reasonOffer?.field === "" ? (editAgain(), submit()) : editAgain(reasonOffer?.field))}>{reasonOffer.label}</Button>
{/if}
{/snippet}
</Banner>
{#if apply.reason?.detail}<Details detail={apply.reason.detail} />{/if}
<p class="ia-hint">Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.</p>
{:else if apply.state === "needs_attention"}
<Banner tone="down" live="alert">{#snippet title()}<strong>Ianitor could not undo a failed change.</strong>{/snippet}{apply.reason?.message}
{#if restoreProblem}<p role="status">{restoreProblem}</p>{/if}
{#snippet actions()}
{#if app.overview?.undo?.target}<Button variant="primary" pending={restoring} onclick={async () => { restoring = true; restoreProblem = await restoreLastKept(); restoring = false; }}>Restore the last kept version</Button>{/if}
{/snippet}
</Banner>
{/if}
{:else}
<form id="host-form" onsubmit={submit} novalidate>
{#if summary}<p class="sr-only" role="alert">{summary}</p>{/if}
{#if conflict}
<Banner tone="notice" live="status">
{#snippet title()}{conflict?.message}{/snippet}
{#snippet actions()}<Button onclick={keepMine}>Keep my edits</Button>{#if hostname}<Button onclick={useTheirs}>Use the new version</Button>{/if}{/snippet}
</Banner>
{/if}
{#if topError}
<Banner tone="notice" live="status">{#snippet title()}{sentence(topError)}{/snippet}</Banner>
{#if topError.body.detail}<Details detail={topError.body.detail} reference={topError.requestId} />{/if}
{/if}
<div class="domi-field">
<label class="domi-field-label" for={fieldId("hostname")}>Hostname</label>
<input id={fieldId("hostname")} class="domi-input" bind:value={host.hostname} readonly={!!hostname}
autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
aria-invalid={errAt("hostname") && touched["hostname"] ? "true" : undefined}
aria-describedby="{fieldId('hostname')}-e {fieldId('hostname')}-h" onblur={() => blur("hostname")} />
{#if errAt("hostname") && touched["hostname"]}
<p class="domi-error" id="{fieldId('hostname')}-e"><Icon name="ring" />{errAt("hostname").message}
{#if errAt("hostname").params?.suggestion}
<button type="button" class="domi-btn link" onclick={() => { host.hostname = errAt("hostname").params.suggestion; blur("hostname"); }}>Use {errAt("hostname").params.suggestion}</button>
{/if}
</p>
{/if}
{#if hostname}<p class="ia-hint" id="{fieldId('hostname')}-h">To use another address, add a new host and remove this one.</p>{/if}
</div>
{#each host.upstreams as _, i (i)}
{@const f = `upstreams[${i}]`}
{@const err = errAt(f) ?? (i === 0 ? errAt("upstreams") : undefined)}
<div class="domi-field">
{#if i === 0}<label class="domi-field-label" for={fieldId(f)}>Send traffic to</label>{/if}
<div class="row">
<input id={fieldId(f)} class="domi-input" bind:value={host.upstreams[i]} autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
aria-label={i === 0 ? undefined : `Also send traffic to, address ${i + 1}`}
aria-invalid={err && (touched[f] || touched["upstreams"]) ? "true" : undefined}
aria-describedby="{fieldId(f)}-e" onblur={() => blur(f)} />
{#if i > 0}<button type="button" class="ia-icon-btn" aria-label="Remove this address" onclick={() => host.upstreams.splice(i, 1)}><Icon name="trash" /></button>{/if}
</div>
{#if err && (touched[f] || touched["upstreams"])}
<p class="domi-error" id="{fieldId(f)}-e"><Icon name="ring" />{err.message}
{#if err.params?.suggestion}<button type="button" class="domi-btn link" onclick={() => { host.upstreams[i] = err.params.suggestion; blur(f); }}>Use {err.params.suggestion}</button>{/if}
</p>
{/if}
{#if i === 0 && host.upstreams.length === 1}<p class="ia-hint">Add another address later for a second server.</p>{/if}
</div>
{/each}
<div><button type="button" class="domi-btn link" onclick={() => host.upstreams.push("")}>Add another address</button></div>
<Segmented legend="Certificate" name="tls" bind:value={host.tls}
options={[{ value: "domi", label: "Domi certificate" }, { value: "letsencrypt", label: "Let's Encrypt" }]} />
<p class="ia-hint">Domi for home devices only; Let's Encrypt for a public site.</p>
<Segmented legend="Who can open it" name="auth" bind:value={host.auth} disabled={signinOk ? [] : ["forward-auth"]}
options={[{ value: "forward-auth", label: "Sign in first" }, { value: "none", label: "Anyone" }]} />
{#if !signinOk}<p class="ia-hint">Sign-in is not set up on this server yet, so choose Anyone for now. To set it up, add the Authelia address to ianitor.toml in the routes repository.</p>{/if}
{#if errAt("auth")}<p class="domi-error"><Icon name="ring" />{errAt("auth").message}</p>{/if}
<div>
<button type="button" class="domi-btn link" aria-expanded={more} aria-controls="more-options" onclick={() => (more = !more)}>
More options: headers, websockets, health check, share links, visit log
</button>
</div>
{#if more}
<div id="more-options" class="more">
<div class="domi-field">
<span class="domi-field-label">Health check</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.hc} /> Check that it answers</label>
<p class="ia-hint">Ianitor asks this address regularly and shows the result on the main screen.</p>
</div>
{#if host.hc}
<div class="domi-field">
<label class="domi-field-label" for={fieldId("health_check.path")}>Health check address</label>
<input id={fieldId("health_check.path")} class="domi-input" bind:value={host.hcPath} aria-invalid={errAt("health_check.path") ? "true" : undefined} onblur={() => blur("health_check.path")} />
{#if errAt("health_check.path")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.path").message}</p>{/if}
<p class="ia-hint">Use an address that answers without signing in, like /health.</p>
</div>
<div class="domi-field">
<label class="domi-field-label" for={fieldId("health_check.interval_secs")}>Checks every</label>
<div class="row"><input id={fieldId("health_check.interval_secs")} class="domi-input narrow" type="number" min="1" max="3600" bind:value={host.hcEvery} onblur={() => blur("health_check.interval_secs")} /> <span class="ia-text2">seconds</span></div>
{#if errAt("health_check.interval_secs")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.interval_secs").message}</p>{/if}
</div>
{/if}
<div class="domi-field">
<span class="domi-field-label">Websockets</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.websockets} /> Allow websockets</label>
<p class="ia-hint">Live updates for apps like Home Assistant. Leave on unless you know the app does not need them.</p>
</div>
<div class="domi-field">
<span class="domi-field-label">Share links</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.share_links} /> Allow share links</label>
<p class="ia-hint">Lets you make links that open this host without signing in, until they expire.</p>
{#if shareWarning}<p class="ia-hint">Anyone can already open {name}, so a share link changes nothing.</p>{/if}
</div>
<div class="domi-field">
<span class="domi-field-label">Device certificates</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.device_certs} /> Only devices with a Domi device certificate</label>
<p class="ia-hint">Phones, computers and apps need a certificate from Certificates before they can open it.</p>
</div>
<Segmented legend="Visit log" name="access_log" bind:value={host.access_log} options={[{ value: "off", label: "Off" }, { value: "truncated", label: "On" }]} />
<p class="ia-hint">On keeps a log on this server, with visitor addresses shortened.</p>
{#each [{ list: "request_headers", rules: host.req, title: "Header rules sent to your service", secrets: true }, { list: "response_headers", rules: host.resp, title: "Header rules sent back to visitors", secrets: false }] as group (group.list)}
<div class="domi-field">
<span class="domi-field-label">{group.title}</span>
{#each group.rules as r, i (i)}
{@const p = `${group.list}[${i}]`}
<div class="rule ia-card">
<Segmented legend="Rule {i + 1}" name="{p}-action" bind:value={r.action} options={[{ value: "set", label: "Set" }, { value: "remove", label: "Remove" }]} />
<label class="domi-field-label" for={fieldId(p + ".name")}>Header name</label>
<input id={fieldId(p + ".name")} class="domi-input" bind:value={r.name} onblur={() => blur(p + ".name")} />
{#if r.action === "set"}
{#if group.secrets}
<Segmented legend="Value" name="{p}-kind" bind:value={r.kind} disabled={(site?.secrets.length ?? 0) === 0 ? ["secret"] : []} options={[{ value: "value", label: "Fixed value" }, { value: "secret", label: "Secret" }]} />
{/if}
{#if r.kind === "secret" && group.secrets}
<select class="domi-input" bind:value={r.secret} aria-label="Secret">
{#each site?.secrets ?? [] as s (s)}<option value={s}>{s}</option>{/each}
</select>
{:else}
<input class="domi-input" bind:value={r.value} aria-label="Value" onblur={() => blur(p + ".value")} />
{/if}
{/if}
{#each Object.entries(errors).filter(([k]) => k.startsWith(p)) as [, e] (e.code + e.field)}<p class="domi-error"><Icon name="ring" />{e.message}</p>{/each}
<button type="button" class="ia-icon-btn" aria-label="Remove this rule" onclick={() => group.rules.splice(i, 1)}><Icon name="trash" /></button>
</div>
{/each}
<div><button type="button" class="domi-btn link" onclick={() => group.rules.push({ action: "set", name: "", kind: "value", value: "", secret: site?.secrets[0] ?? "" })}>Add a rule</button></div>
{#if group.secrets && (site?.secrets.length ?? 0) === 0}<p class="ia-hint">No secrets are listed in ianitor.toml.</p>{/if}
</div>
{/each}
</div>
{/if}
</form>
{/if}
{#snippet footer()}
{#if phase === "form" && !loading && !notFound}
{#if underFooter}<p class="ia-hint full" role="status">{underFooter}</p>{/if}
{#if blocked}<p class="ia-hint full" id="apply-blocked">{blocked}</p>{/if}
<Button onclick={onclose}>Cancel</Button>
<Button variant="primary" type="submit" form="host-form" disabled={!!blocked} describedby={blocked ? "apply-blocked" : undefined}>Apply</Button>
{:else if phase === "progress" && apply && FINAL.includes(apply.state)}
<Button onclick={onclose}>Close</Button>
{/if}
{/snippet}
</Dialog>
<style>
form { display: flex; flex-direction: column; gap: 16px; }
.row { display: flex; gap: 8px; align-items: center; }
.more { display: flex; flex-direction: column; gap: 16px; }
.rule { display: flex; flex-direction: column; gap: 8px; }
.narrow { max-width: 8rem; }
.full { flex-basis: 100%; }
</style>
@@ -0,0 +1,65 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §13.5: the intermediate banner. Renew is 1 click; the banner then shows the match
// code. Until Custos can sign (docs/custos-ticket.md) the request is signed by hand offline,
// so the waiting banner links to that page.
import { Banner, Button } from "@ianitor/ui";
import { del, post, sentence } from "../lib/api";
import { app, navigate, refresh, secondsLeft } from "../lib/app.svelte";
import { duration, longDate } from "../lib/format";
import type { PkiRequest } from "../lib/types";
const i = $derived(app.overview?.intermediate ?? null);
let pending = $state(false);
let problem = $state<string | null>(null);
async function renew() {
pending = true;
problem = null;
try {
await post<PkiRequest>("/certs/intermediate/renewal");
await refresh();
} catch (e) {
problem = sentence(e);
} finally {
pending = false;
}
}
async function cancel(id: string) {
try {
await del(`/pki-requests/${encodeURIComponent(id)}`);
await refresh();
} catch (e) {
problem = sentence(e);
}
}
</script>
{#if app.renewedUntil}
<Banner tone="kept" live="status" ondismiss={() => (app.renewedUntil = null)}>
{#snippet title()}Renewed. The Domi intermediate certificate is now valid until {longDate(app.renewedUntil, false)}.{/snippet}
</Banner>
{:else if i?.renewal}
{@const r = i.renewal}
<Banner tone="notice" label="Domi intermediate certificate">
{#snippet title()}
<span tabindex="-1">Sign the renewal on the offline computer. The next page has the files, the command and a fingerprint to check.</span>
{/snippet}
The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if}
{#snippet actions()}
<Button variant="outline" onclick={() => navigate("/certificates/renew-by-hand")}>Sign it by hand</Button>
<Button onclick={() => cancel(r.request_id)}>Cancel request</Button>
{/snippet}
</Banner>
{:else if i?.banner}
<Banner tone={i.state === "due" ? "notice" : "down"} label="Domi intermediate certificate">
{#snippet title()}<strong>{i.banner?.message}</strong>{/snippet}
{i.state === "missing" ? "Setting it up makes a request that the Domi root signs on the offline computer." : "Renewing makes a request that the Domi root signs on the offline computer."}
{#if problem} {problem}{/if}
{#snippet actions()}<Button variant="outline" onclick={renew} {pending}>{i.state === "missing" ? "Set up" : "Renew"}</Button>{/snippet}
</Banner>
{/if}
+163
View File
@@ -0,0 +1,163 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §8.2: mint on open (click 2), Copy link (click 3). Changing an option re-mints with
// `replaces`, so one link from this dialog is valid at a time; closing without copying stops it.
// Links off: "Turn on share links" applies the change, then Copy link (4 clicks: open
// question Q1 is not decided, so this is the fallback path the design allows).
import { onDestroy, onMount } from "svelte";
import { Banner, Button, Dialog, Icon, Segmented } from "@ianitor/ui";
import ApplyProgress from "./ApplyProgress.svelte";
import { ApiError, call, del, newKey, patch, sentence } from "../lib/api";
import { app } from "../lib/app.svelte";
import { follow } from "../lib/applies";
import { longDate } from "../lib/format";
import type { ApplyView, MintedLink } from "../lib/types";
let { hostname, onclose }: { hostname: string; onclose: () => void } = $props();
// Known before the Dialog mounts, so its focus lands on Copy link (§2.9), not the title.
// svelte-ignore state_referenced_locally
let on = $state(!!app.overview?.hosts.find((h) => h.hostname === hostname)?.share_links);
let link = $state<MintedLink | null>(null);
let minting = $state(false);
let copied = $state(false);
let copiedBefore = $state(false);
let refused = $state(false);
let problem = $state<string | null>(null);
let fieldErr = $state<{ field: string; message: string } | null>(null);
let days = $state<"1" | "7" | "30">("7");
let prefix = $state("/");
let showPassword = $state(false);
let password = $state("");
let usingPassword = $state(false);
let turning = $state<ApplyView | null>(null);
let stopFollow: (() => void) | undefined;
let secretBox: HTMLTextAreaElement | undefined = $state();
onMount(() => {
if (on) void mint();
});
onDestroy(() => stopFollow?.());
async function mint() {
minting = true;
problem = null;
fieldErr = null;
try {
const body: Record<string, unknown> = { path_prefix: prefix || "/", expires_in_s: Number(days) * 86400 };
if (usingPassword && password) body.password = password;
if (link) body.replaces = link.id;
const a = await call<MintedLink>("POST", `/hosts/${encodeURIComponent(hostname)}/share-links`, body, { idem: newKey() });
if (link && copied) copiedBefore = true;
link = a.data;
copied = false;
} catch (e) {
if (e instanceof ApiError && e.body.field) {
fieldErr = { field: e.body.field, message: e.body.message };
if (e.body.field === "password") usingPassword = false;
}
else problem = sentence(e);
} finally {
minting = false;
}
}
async function copy() {
if (!link) return;
try {
await navigator.clipboard.writeText(link.url);
copied = true;
refused = false;
} catch {
refused = true;
secretBox?.select();
}
}
async function turnOn() {
try {
const a = await patch<{ apply: ApplyView }>(`/hosts/${encodeURIComponent(hostname)}`, { share_links: true, base_rev: app.overview?.rev ?? null });
turning = a.apply;
stopFollow = follow(a.apply.id, async (x) => {
turning = x;
if (x.state === "kept") {
on = true;
await mint();
}
});
} catch (e) {
problem = sentence(e);
}
}
function close() {
// A link nobody copied does not stay valid.
if (link && !copied) void del(`/share-links/${encodeURIComponent(link.id)}`, { keepalive: true }).catch(() => {});
onclose();
}
const underCaddy = $derived(app.overview?.engine.running === "caddy");
</script>
<Dialog title="Share {hostname}" onclose={close}>
{#if !on}
{#if turning}
<ApplyProgress apply={turning} />
{#if turning.state === "reverted" || turning.state === "failed"}
<Banner tone="notice" live="status">{#snippet title()}Share links were not turned on. {turning?.reason?.message}{/snippet}</Banner>
{/if}
{:else}
<p><strong>Share links are off for {hostname}.</strong></p>
<p class="ia-text2">Turning them on is a change to the host, checked like any other.</p>
{#if problem}<p class="domi-error" role="alert"><Icon name="ring" />{problem}</p>{/if}
<div><Button variant="outline" onclick={turnOn} disabled={!!app.overview?.paused}>Turn on share links</Button></div>
{/if}
{:else}
<p class="ia-text2">Anyone with this link can open the site without signing in, until it expires.</p>
{#if underCaddy}
<Banner tone="notice">{#snippet title()}Caddy is serving right now, so share links do not work: visitors with this link get the normal sign-in. The link works after switching back to Pingora, until it expires.{/snippet}</Banner>
{/if}
{#if link?.warning}<p class="ia-hint">{link.warning.message}</p>{/if}
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if link}
<textarea bind:this={secretBox} class="ia-secret" readonly value={link.url} aria-label="Share link" onfocus={(e) => (e.currentTarget as HTMLTextAreaElement).select()}></textarea>
{:else if minting}
<p class="ia-muted">Making the link…</p>
{/if}
{#if copied}
<p class="ia-status" data-s="kept" role="status"><Icon name="check" /><span>Copied</span></p>
<p class="ia-hint">Expires on {longDate(link?.expires_at)}. To stop it sooner: Settings, Share links, Stop this link.</p>
{:else}
<Button variant="primary" full icon="copy" onclick={copy} disabled={!link || minting} data-autofocus>Copy link</Button>
{/if}
{#if refused}<p class="ia-hint" role="alert">Your browser did not allow copying. Press Ctrl+C to copy the selected link.</p>{/if}
{#if copiedBefore && !copied}<p class="ia-hint">The link you copied before is stopped. Copy this one.</p>{/if}
<Segmented legend="Expires after" name="expiry" bind:value={days} onchange={() => mint()}
options={[{ value: "1", label: "1 day" }, { value: "7", label: "7 days" }, { value: "30", label: "30 days" }]} />
<div class="domi-field">
<label class="domi-field-label" for="share-prefix">Only addresses starting with</label>
<input id="share-prefix" class="domi-input" bind:value={prefix} onblur={() => mint()} onkeydown={(e) => { if (e.key === "Enter") { e.preventDefault(); void mint(); } }}
aria-invalid={fieldErr?.field === "path_prefix" ? "true" : undefined} />
{#if fieldErr?.field === "path_prefix"}<p class="domi-error"><Icon name="ring" />{fieldErr.message}</p>{/if}
<p class="ia-hint">/ shares the whole site. Try /share/summer-2026 for one album.</p>
</div>
{#if usingPassword}
<p class="ia-hint">This link asks for the password.</p>
<div><button type="button" class="domi-btn link" onclick={() => { usingPassword = false; password = ""; void mint(); }}>Remove the password</button></div>
{:else if showPassword}
<div class="domi-field">
<label class="domi-field-label" for="share-password">Password</label>
<input id="share-password" class="domi-input" type="password" autocomplete="new-password" bind:value={password}
aria-invalid={fieldErr?.field === "password" ? "true" : undefined} />
{#if fieldErr?.field === "password"}<p class="domi-error"><Icon name="ring" />{fieldErr.message}</p>{/if}
<p class="ia-hint">At least 8 characters. Send it to them separately.</p>
<div><Button onclick={() => { usingPassword = true; void mint(); }}>Use this password</Button></div>
</div>
{:else}
<div><button type="button" class="domi-btn link" onclick={() => (showPassword = true)}>Add a password</button></div>
{/if}
{/if}
</Dialog>
+86
View File
@@ -0,0 +1,86 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §2.8 order: paused / needs attention, lost contact, health unavailable, the Caddy
// notice, then (on Hosts) the intermediate banner. First on every screen.
import { Banner, Button, Details } from "@ianitor/ui";
import { app, refresh, restorable as canRestore, restoreLastKept } from "../lib/app.svelte";
import { atTime, whenInline } from "../lib/format";
const o = $derived(app.overview);
let restoring = $state(false);
let problem = $state<string | null>(null);
const restorable = $derived(canRestore());
async function restore() {
restoring = true;
problem = await restoreLastKept();
restoring = false;
}
// §7.6: the bold line and line 2 by the pause's underlying code.
const pause = $derived.by(() => {
const code = o?.paused_reason ?? "";
const message = o?.paused?.message ?? "";
if (code === "apply.needs_attention")
return { bold: "Ianitor could not undo a failed change.", line2: "Visitors are served the last good settings, but the routes repository still has the change. Restore the last kept version to make them match again.", extra: "" };
if (code === "control.files_unwritten")
return { bold: "The change is live, but Ianitor could not save the proxy settings to disk.", line2: "Changes are paused until Ianitor restarts and saves them. Restoring the last kept version also clears this.", extra: "On the server: sudo systemctl restart ianitor-control" };
// control.paused wraps the reason: "Changes are paused: <reason>"; show the reason itself.
const own = message.replace(/^Changes are paused: /, "");
if (/^(repo|file|site)\./.test(code))
return { bold: own, line2: `Fix the file in the ${o?.repo?.name ?? "routes"} repository; Ianitor picks it up by itself.`, extra: "" };
return { bold: own, line2: "", extra: "" };
});
// "Show details" for every pause (§7.6): the server's detail, the restart command, or the
// full message when there is nothing more.
const pauseDetail = $derived(
[o?.paused_detail, pause.extra].filter(Boolean).join("\n") || (o?.paused ? (o.paused.message ?? "") : ""),
);
async function retry() {
await refresh();
}
</script>
{#if o?.paused}
<Banner tone="down" live="alert">
{#snippet title()}<span class="ia-status" data-s="down"><span class="word">{o.paused_reason === "apply.needs_attention" ? "needs attention" : "paused"}</span></span> <strong>{pause.bold}</strong>{/snippet}
{#if pause.line2}<span class="line2">{pause.line2}</span>{/if}
{#if restorable && o.undo?.target}<p class="ia-hint">Goes back to "{o.undo.target.summary}" from {whenInline(o.undo.target.kept_at, app.now)}. It is checked like any change.</p>{/if}
{#if problem}<p role="status">{problem}</p>{/if}
{#if pauseDetail}<Details detail={pauseDetail} />{/if}
{#snippet actions()}
{#if restorable}<Button variant="primary" onclick={restore} pending={restoring}>Restore the last kept version</Button>{/if}
{/snippet}
</Banner>
{/if}
{#if app.lostContact}
<Banner tone="down" live="alert">
{#snippet title()}<strong>{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."}</strong>{/snippet}
Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {atTime(new Date(app.lastUpdated).toISOString(), app.now)}.{/if}
{#snippet actions()}<Button onclick={retry}>Try again now</Button>{/snippet}
</Banner>
{/if}
{#if o?.health_error}
<Banner tone="notice">{#snippet title()}{o.health_error?.message}{/snippet}</Banner>
{/if}
{#if app.switchResult}
{@const r = app.switchResult}
<Banner tone={r.ok ? "kept" : "down"} live="status" ondismiss={() => (app.switchResult = null)}>
{#snippet title()}<strong>{r.title}</strong>{/snippet}
{r.text}
{#if r.detail}<Details detail={r.detail} />{/if}
</Banner>
{/if}
{#if o?.engine.running === "caddy" && (o.hosts.some((h) => h.share_links) ?? false)}
<Banner tone="notice">{#snippet title()}Caddy is serving (the fallback), so share links do not work until you switch back.{/snippet}</Banner>
{/if}
+184
View File
@@ -0,0 +1,184 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The one typed API client (handoff §0, §10, §11). It owns the base path, the UI header (CSRF),
// redirect: "manual" (sign-out detection), Idempotency-Keys, the error envelope, the server
// clock offset, rate-limit and in-progress retries, and lost-contact detection. It decides
// nothing about the data.
import type { ErrorBody, ErrorEnvelope } from "./types";
export const BASE = "/api/v1";
/** A refusal from control, with its envelope. */
export class ApiError extends Error {
constructor(
public status: number,
public body: ErrorBody,
public errors: ErrorBody[],
public requestId: string,
) {
super(body.message);
}
get code(): string {
return this.body.code;
}
}
/** Authelia's portal redirect, or a 401 without Ianitor's envelope. */
export class SignedOut extends Error {}
/** No answer (network, or a proxy error without an envelope). */
export class LostContact extends Error {}
type Listener = () => void;
export interface ClientEvents {
onSignedOut?: Listener;
onContact?: (ok: boolean) => void;
onServerTime?: (offsetMs: number) => void;
}
let events: ClientEvents = {};
export function setClientEvents(e: ClientEvents): void {
events = e;
}
/** A key for one click; reused by every retry of that click (§11.3). */
export function newKey(): string {
if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
return Math.random().toString(36).slice(2) + Date.now().toString(36);
}
export interface CallOptions {
idem?: string;
etag?: string;
/** Do not count a failure as lost contact (engine switch, §9.2). */
quiet?: boolean;
keepalive?: boolean;
}
export interface Answer<T> {
status: number;
data: T | null;
etag: string | null;
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
function envelope(v: unknown): v is ErrorEnvelope {
return typeof v === "object" && v !== null && "error" in v && typeof (v as ErrorEnvelope).error === "object";
}
export async function call<T>(
method: string,
path: string,
body?: unknown,
opts: CallOptions = {},
): Promise<Answer<T>> {
let rateRetried = false;
for (let attempt = 0; attempt < 12; attempt++) {
const headers: Record<string, string> = { "X-Ianitor-UI": "1", Accept: "application/json" };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (opts.idem) headers["Idempotency-Key"] = opts.idem;
if (opts.etag) headers["If-None-Match"] = opts.etag;
let res: Response;
try {
res = await fetch(BASE + path, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
redirect: "manual",
credentials: "same-origin",
keepalive: opts.keepalive,
});
} catch {
if (!opts.quiet) events.onContact?.(false);
throw new LostContact("no answer");
}
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400 && res.status !== 304)) {
events.onSignedOut?.();
throw new SignedOut("signed out");
}
if (res.status === 304) {
events.onContact?.(true);
return { status: 304, data: null, etag: opts.etag ?? null };
}
let json: unknown = null;
const text = await res.text();
try {
json = text ? JSON.parse(text) : null;
} catch {
json = null;
}
if (json && typeof json === "object" && "server_time" in json) {
const t = Date.parse(String((json as { server_time: string }).server_time));
if (!Number.isNaN(t)) events.onServerTime?.(t - Date.now());
}
if (!envelope(json)) {
if (res.status === 401) {
events.onSignedOut?.();
throw new SignedOut("signed out");
}
if (res.status >= 502 && res.status <= 504) {
if (!opts.quiet) events.onContact?.(false);
throw new LostContact(`proxy answered ${res.status}`);
}
events.onContact?.(true);
return { status: res.status, data: json as T, etag: res.headers.get("ETag") };
}
events.onContact?.(true);
const env = json;
if (env.error.code === "request.in_progress") {
await sleep(1000);
continue;
}
if (env.error.code === "rate.limited" && !rateRetried) {
rateRetried = true;
await sleep(Math.min(60, env.error.retry_after_s ?? 1) * 1000);
continue;
}
if (res.status === 401 && env.error.code.startsWith("token.")) {
// The UI holds no token: a token refusal means the sign-in did not reach control.
events.onSignedOut?.();
throw new SignedOut(env.error.message);
}
throw new ApiError(res.status, env.error, env.errors ?? [], env.request_id ?? "");
}
throw new ApiError(
409,
{
code: "request.in_progress",
message: "The first request with this Idempotency-Key is still being handled. Try again in a moment.",
field: null,
params: {},
retry_after_s: 1,
detail: null,
},
[],
"",
);
}
export const get = <T>(path: string, opts?: CallOptions) => call<T>("GET", path, undefined, opts).then((a) => a.data as T);
export const post = <T>(path: string, body: unknown = {}, opts?: CallOptions) =>
call<T>("POST", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
export const put = <T>(path: string, body: unknown, opts?: CallOptions) =>
call<T>("PUT", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
export const patch = <T>(path: string, body: unknown, opts?: CallOptions) =>
call<T>("PATCH", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
export const del = (path: string, opts?: CallOptions) => call<unknown>("DELETE", path, undefined, opts).then(() => undefined);
/** A UI sentence for request.* codes (handoff §12.4): bugs or a stale page, not user mistakes. */
export function sentence(e: unknown): string {
if (e instanceof ApiError) {
if (e.code.startsWith("request.") && e.code !== "request.in_progress") {
return "Ianitor refused this request from the page. Reload the page and try again.";
}
return e.body.message;
}
if (e instanceof LostContact) return "Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back.";
if (e instanceof SignedOut) return "Your sign-in has ended. Sign in again; this page keeps what you typed.";
return "Something went wrong.";
}
+180
View File
@@ -0,0 +1,180 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state,
// the server clock offset and toasts. No business logic: everything shown comes from control.
import { call, newKey, sentence, setClientEvents } from "./api";
import type { Overview } from "./types";
export interface Toast {
id: number;
text: string;
}
export const app = $state({
overview: null as Overview | null,
etag: null as string | null,
loadError: false,
lostContact: false,
lostSince: 0,
lastUpdated: 0,
signedOut: false,
offset: 0,
now: Date.now(),
path: typeof location === "undefined" ? "/" : location.pathname + location.search,
toasts: [] as Toast[],
/** Dismissed banner keys (reverted outcome, renewed, switched). */
dismissed: [] as string[],
/** The outcome of the last engine switch, until dismissed (handoff §9.2). */
switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null },
/** A renewal just installed (handoff §13.5). */
renewedUntil: null as null | string,
/** After a kept add or edit: the row whose More button gets focus (§7.5). */
focusHost: null as string | null,
/** Narrower than 720 px (the phone layout, handoff §5.2). */
phone: false,
/** Panels the main screen opens (add/edit host, share, engine). */
panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" },
});
let failures = 0;
let firstFailure = 0;
setClientEvents({
onSignedOut: () => {
app.signedOut = true;
},
onContact: (ok) => {
if (ok) {
failures = 0;
app.lostContact = false;
return;
}
if (failures === 0) firstFailure = Date.now();
failures++;
// Retry quietly for 10 s (a reload takes about 2 s), then say so (§11.1).
if (Date.now() - firstFailure >= 10_000) {
if (!app.lostContact) app.lostSince = Date.now();
app.lostContact = true;
}
},
onServerTime: (o) => {
app.offset = o;
},
});
/** Server time now, in ms (all countdowns use it, §7.2). */
export function serverNow(): number {
return app.now + app.offset;
}
/** Seconds left until an ISO time, on the server's clock. */
export function secondsLeft(iso: string | null | undefined): number {
if (!iso) return 0;
return Math.max(0, Math.ceil((Date.parse(iso) - serverNow()) / 1000));
}
export async function refresh(): Promise<void> {
if (app.signedOut) return;
try {
const a = await call<Overview>("GET", "/overview", undefined, { etag: app.etag ?? undefined });
if (a.status === 200 && a.data) {
app.overview = a.data;
app.etag = a.etag;
}
app.loadError = false;
app.lastUpdated = Date.now();
} catch {
if (!app.overview) app.loadError = true;
}
}
let timer: ReturnType<typeof setTimeout> | undefined;
let hiddenSince = 0;
/** Poll every 5 s while visible, 30 s when hidden, stop after 15 min hidden (Q9). */
export function startPolling(): () => void {
let stopped = false;
const tick = async () => {
if (stopped) return;
const hidden = typeof document !== "undefined" && document.visibilityState === "hidden";
if (hidden && !hiddenSince) hiddenSince = Date.now();
if (!hidden) hiddenSince = 0;
if (!(hidden && Date.now() - hiddenSince > 15 * 60_000)) await refresh();
const every = app.lostContact ? 5000 : hidden ? 30_000 : 5000;
timer = setTimeout(tick, every);
};
const vis = () => {
if (document.visibilityState === "visible" && hiddenSince) {
hiddenSince = 0;
clearTimeout(timer);
void tick();
}
};
document.addEventListener("visibilitychange", vis);
const clock = setInterval(() => (app.now = Date.now()), 1000);
void tick();
return () => {
stopped = true;
clearTimeout(timer);
clearInterval(clock);
document.removeEventListener("visibilitychange", vis);
};
}
let toastId = 0;
export function toast(text: string): void {
const id = ++toastId;
app.toasts = [...app.toasts.slice(-2), { id, text }];
setTimeout(() => {
app.toasts = app.toasts.filter((t) => t.id !== id);
}, 6000);
}
export function navigate(path: string): void {
if (path === app.path) return;
history.pushState({}, "", path);
app.path = path;
}
if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
const mq = window.matchMedia("(max-width: 719.98px)");
app.phone = mq.matches;
mq.addEventListener?.("change", (e) => (app.phone = e.matches));
}
if (typeof window !== "undefined") {
window.addEventListener("popstate", () => {
app.path = location.pathname + location.search;
});
}
/** Is a change allowed now? (Paused, or no contact.) */
export function changesBlocked(): string | null {
const o = app.overview;
if (app.lostContact) return "Ianitor's control service is not answering.";
if (o?.paused) return "Changes are paused.";
return null;
}
/** "Restore the last kept version" (handoff §7.6): start it and show its progress in a panel.
* Returns the sentence to show when it could not start. */
export async function restoreLastKept(): Promise<string | null> {
const o = app.overview;
if (!o?.undo?.target) return null;
try {
const a = await call<{ apply: { id: string } }>("POST", "/restore", { change_id: o.undo.target.change_id, base_rev: o.rev }, { idem: newKey() });
if (a.data) app.panel = { kind: "host", resume: a.data.apply.id };
return null;
} catch (e) {
return sentence(e);
}
}
/** Whether the pause can be cleared by restoring the last kept version. */
export function restorable(): boolean {
const o = app.overview;
return !!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target;
}
+63
View File
@@ -0,0 +1,63 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Following an apply (handoff §2.2 of ui-api, §3 here): GET /applies/{id} every second while it
// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it.
import { get } from "./api";
import { app, refresh } from "./app.svelte";
import type { ApplyView } from "./types";
export const FINAL = ["kept", "reverted", "failed", "needs_attention"];
const KEY = "ianitor.activeApply";
export function remember(id: string | null): void {
try {
if (id) sessionStorage.setItem(KEY, id);
else sessionStorage.removeItem(KEY);
} catch {
/* storage may be off; the bar still shows the running apply */
}
}
export function remembered(): string | null {
try {
return sessionStorage.getItem(KEY);
} catch {
return null;
}
}
/** Poll until the apply ends. Returns a stop function. */
export function follow(id: string, onupdate: (a: ApplyView) => void, every = 1000): () => void {
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
remember(id);
const tick = async () => {
if (stopped) return;
if (app.signedOut) {
// No requests while signed out (the overview poll stops too); look again shortly.
timer = setTimeout(tick, every);
return;
}
try {
const a = await get<ApplyView>(`/applies/${encodeURIComponent(id)}`);
if (stopped) return;
onupdate(a);
if (FINAL.includes(a.state)) {
remember(null);
void refresh();
return;
}
} catch {
/* lost contact or a reload in progress: keep trying (the banner says so after 10 s) */
}
timer = setTimeout(tick, every);
};
void tick();
return () => {
stopped = true;
clearTimeout(timer);
};
}
+115
View File
@@ -0,0 +1,115 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Formatting only (handoff §3): times in the browser's zone, 24-hour clock, counts sentences.
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const LONG = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const two = (n: number) => String(n).padStart(2, "0");
/** "Today 14:02", "Yesterday 21:14", "5 Nov 21:14", "5 Nov 2025". */
export function when(iso: string | null | undefined, now = Date.now()): string {
if (!iso) return "";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "";
const n = new Date(now);
const hm = `${two(d.getHours())}:${two(d.getMinutes())}`;
const sameDay = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
if (sameDay(d, n)) return `Today ${hm}`;
const y = new Date(n);
y.setDate(n.getDate() - 1);
if (sameDay(d, y)) return `Yesterday ${hm}`;
if (d.getFullYear() !== n.getFullYear()) return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`;
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`;
}
/** Inside a sentence: "today 14:02", "yesterday 21:14", "5 Nov 21:14". */
export function whenInline(iso: string | null | undefined, now = Date.now()): string {
return when(iso, now).replace(/^(Today|Yesterday)/, (s) => s.toLowerCase());
}
/** After "at" / "on": "at 14:03", "yesterday at 21:14", "on 5 Nov at 21:14", "on 5 Nov 2025". */
export function atTime(iso: string | null | undefined, now = Date.now()): string {
const w = when(iso, now);
if (!w) return "";
if (w.startsWith("Today ")) return `at ${w.slice(6)}`;
if (w.startsWith("Yesterday ")) return `yesterday at ${w.slice(10)}`;
const m = /^(\d+ \w+) (\d\d:\d\d)$/.exec(w);
return m ? `on ${m[1]} at ${m[2]}` : `on ${w}`;
}
/** "14 November 2026 at 14:20". */
export function longDate(iso: string | null | undefined, withTime = true): string {
if (!iso) return "";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "";
const s = `${d.getDate()} ${LONG[d.getMonth()]} ${d.getFullYear()}`;
return withTime ? `${s} at ${two(d.getHours())}:${two(d.getMinutes())}` : s;
}
/** "2 Mar 2027". */
export function shortDate(iso: string | null | undefined): string {
if (!iso) return "";
const d = new Date(iso);
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`;
}
/** "8 s", "6 minutes", "2 hours", "3 days". */
export function duration(secs: number): string {
if (secs < 60) return `${Math.max(0, Math.round(secs))} s`;
const m = Math.round(secs / 60);
if (m < 60) return m === 1 ? "1 minute" : `${m} minutes`;
const h = Math.round(secs / 3600);
if (h < 48) return h === 1 ? "1 hour" : `${h} hours`;
const days = Math.round(secs / 86400);
return `${days} days`;
}
export function ago(iso: string | null | undefined, now: number): string {
if (!iso) return "";
return duration((now - Date.parse(iso)) / 1000) + " ago";
}
/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1); short (phone, §5.2): "5 healthy, 1 degraded, 1 down". */
export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }, short = false): string {
const parts = [`${c.healthy} healthy`];
if (c.degraded) parts.push(`${c.degraded} degraded`);
if (c.down) parts.push(`${c.down} down`);
if (c.unknown) parts.push(`${c.unknown} not checked`);
if (short) return parts.join(", ");
return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`;
}
/** Split a server message on its first sentence (handoff §7.5). */
export function firstSentence(m: string): [string, string] {
const i = m.indexOf(". ");
return i < 0 ? [m, ""] : [m.slice(0, i + 1), m.slice(i + 2)];
}
/** Field labels in sentences (handoff §6.5). */
export const FIELD_LABEL: Record<string, string> = {
hostname: "address",
upstreams: "sends traffic to",
tls: "certificate",
auth: "who can open it",
"health_check.path": "health check address",
"health_check.interval_secs": "checks every",
share_links: "share links",
device_certs: "device certificates",
access_log: "visit log",
websockets: "websockets",
headers: "header rules",
};
export function fieldValue(field: string, v: string): string {
if (v === "") return "none";
if (field === "tls") return v === "domi" ? "Domi certificate" : "Let's Encrypt";
if (field === "auth") return v === "forward-auth" ? "sign in first" : "anyone";
if (field === "access_log") return v === "truncated" ? "on" : "off";
if (v === "true") return "on";
if (v === "false") return "off";
if (field === "health_check.interval_secs") return `${v} s`;
return v;
}
+251
View File
@@ -0,0 +1,251 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The shapes the UI reads from control (docs/api.md, docs/ui-api.md, GET /api/v1/openapi.json).
// Only the fields the UI uses are typed.
export interface ErrorBody {
code: string;
message: string;
field: string | null;
params: Record<string, string>;
retry_after_s: number | null;
detail: string | null;
}
export interface ErrorEnvelope {
error: ErrorBody;
errors: ErrorBody[];
request_id: string;
}
export interface Blocked {
code: string;
message: string;
}
export interface Reason {
code: string;
message: string;
hostname?: string | null;
upstream?: string | null;
field?: string | null;
detail?: string | null;
params?: Record<string, string>;
}
export interface Step {
key: "validate" | "compile" | "write" | "reload" | "watch" | "push";
state: "pending" | "running" | "done" | "failed" | "skipped";
}
export interface ApplyView {
id: string;
change_id: string;
kind: "add" | "edit" | "remove" | "undo" | "restore" | "share_links";
summary: string;
hosts: string[];
state: "queued" | "validating" | "applying" | "watching" | "kept" | "reverted" | "failed" | "needs_attention";
created_at: string;
finished_at: string | null;
steps: Step[];
queue: { position: number; waiting_for: { apply_id: string; summary: string; seconds_left: number | null } | null } | null;
watch: { ends_at: string; seconds_left: number; hosts: { hostname: string; passed: number; failed: number; total: number }[] } | null;
reason: Reason | null;
errors: ErrorBody[];
commit_short: string | null;
push: { state: "pushed" | "pending" | "failed"; at: string | null; error_code: string | null; next_try_at: string | null } | null;
attempted_host?: HostSpec | null;
}
export interface HeaderRule {
action: "set" | "remove";
name: string;
value?: string;
secret?: string;
}
export interface HostSpec {
hostname: string;
upstreams: string[];
tls: "domi" | "letsencrypt";
auth: "none" | "forward-auth";
websockets: boolean;
share_links: boolean;
device_certs?: boolean;
access_log: "off" | "truncated";
health_check?: { path: string; interval_secs: number } | null;
request_headers?: HeaderRule[];
response_headers?: HeaderRule[];
}
export interface HealthView {
state: "healthy" | "degraded" | "down" | "unknown" | "pending";
last_check_at: string | null;
latency_ms: number | null;
since: string | null;
failure: { kind: string; upstream: string | null; count: number; of: number } | null;
upstreams: { url: string; state: string; last_check_at: string | null; latency_ms: number | null; failure_kind: string | null }[];
}
export interface HostRow {
hostname: string;
upstreams: string[];
tls: string;
auth: string;
websockets: boolean;
share_links: boolean;
device_certs: boolean;
added_at: string | null;
health: HealthView;
certificate: { state: "ok" | "pending" | "failed"; not_after: string | null; error_code: string | null };
}
export interface PkiRequest {
request_id: string;
kind: "device" | "intermediate";
state: "waiting" | "approved" | "denied" | "expired" | "cancelled" | "failed";
match_code: string;
created_at: string;
expires_at: string;
approved_at: string | null;
device_id: string | null;
name: string | null;
csr_pem: string | null;
csr_sha256?: string | null;
not_after: string | null;
message_code: string;
message: string;
approve_command: string | null;
file_base?: string | null;
problem: string | null;
}
export interface IntermediateView {
state: "ok" | "due" | "urgent" | "expired" | "missing";
subject: string | null;
not_after: string | null;
days_left: number | null;
renewal: PkiRequest | null;
banner: Blocked | null;
}
export interface EngineView {
running: "pingora" | "caddy";
state: "running" | "switching" | "stopped";
since: string | null;
target: string | null;
switchable: boolean;
fallback_ready: { built_at: string | null; current: boolean; compared: number; matched: number; differences: string[] } | null;
last_error: Reason | null;
notes: Blocked[];
}
export interface UndoView {
available: boolean;
target: { change_id: string; summary: string; kept_at: string | null; commit_short: string | null } | null;
effect: string | null;
blocked: Blocked | null;
}
export interface Overview {
counts: { hosts: number; healthy: number; degraded: number; down: number; unknown: number };
hosts: HostRow[];
engine: EngineView;
last_apply: ApplyView | null;
undo: UndoView;
active_apply: { id: string; state: string; summary: string; seconds_left: number | null; kind: string; hosts: string[]; watch_ends_at: string | null; queued: number } | null;
repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null;
intermediate: IntermediateView | null;
site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean; auth_logout_url?: string | null } | null;
paused: Blocked | null;
paused_reason: string | null;
paused_detail?: string | null;
health_error: Blocked | null;
rev: string | null;
viewer?: { name: string; via: string } | null;
server_time: string;
}
export interface HistoryEntry {
change_id: string;
summary: string;
kind: string;
state: string;
at: string;
commit_short: string | null;
hosts: string[];
reason_short: string | null;
}
export interface RestorePreview {
restorable: boolean;
same_as_current: boolean;
changes: { hostname: string; effect: "added" | "removed" | "changed"; fields: { field: string; from: string; to: string }[] }[];
blocked: Blocked | null;
}
export interface ShareLink {
id: string;
hostname: string;
path_prefix: string;
created_at: string;
expires_at: string;
has_password: boolean;
state: "active" | "expired" | "stopped";
}
export interface MintedLink {
id: string;
url: string;
expires_at: string;
path_prefix: string;
has_password: boolean;
warning: Blocked | null;
}
export interface TokenRow {
id: string;
name: string;
created_at: string;
last_used_at: string | null;
expires_at: string | null;
revoked_at?: string | null;
}
export interface CreatedToken {
id: string;
name: string;
token: string;
expires_at: string | null;
}
export interface DeviceRow {
id: string;
name: string;
kind: "phone" | "computer" | "app";
created_at: string;
not_after: string;
state: "valid" | "revoked" | "expired";
revoked_at: string | null;
}
export interface CertsView {
intermediate: IntermediateView | null;
root: { offline: boolean; subject: string; not_after: string; sha256: string };
devices: DeviceRow[];
device_lifetime_days: number;
device_valid_until: string | null;
server_lifetime_days: number;
approval: string;
requests: PkiRequest[];
}
export interface Bundle {
download_url: string;
one_time_password: string;
expires_at: string;
filename: string;
qr_svg: string | null;
}
+11
View File
@@ -0,0 +1,11 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
import "@ianitor/ui/tokens.css";
import "@ianitor/ui/components.css";
import { mount } from "svelte";
import App from "./App.svelte";
const target = document.getElementById("app");
if (target) mount(App, { target });
+257
View File
@@ -0,0 +1,257 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §13: Certificates → + Device → Issue (3 clicks), approval with the match code, then
// the install (the accepted 4th click). Until Custos can approve, approval is the server
// command control names (docs/pki.md).
import { onDestroy, onMount } from "svelte";
import { Banner, Button, Dialog, Icon, Segmented, Status } from "@ianitor/ui";
import HostMenu from "../components/HostMenu.svelte";
import IntermediateBanner from "../components/IntermediateBanner.svelte";
import { ApiError, del, get, post, sentence } from "../lib/api";
import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { atTime, shortDate } from "../lib/format";
import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types";
let { newDevice }: { newDevice: boolean } = $props();
let certs = $state<CertsView | null>(null);
let problem = $state<string | null>(null);
let name = $state("");
let kind = $state<"phone" | "computer" | "app">("phone");
let nameErr = $state<string | null>(null);
let issuing = $state(false);
let request = $state<PkiRequest | null>(null);
let bundle = $state<{ device: DeviceRow | { id: string; name: string; kind: string }; b: Bundle; format: string } | null>(null);
let confirmRevoke = $state<string | null>(null);
let timer: ReturnType<typeof setTimeout> | undefined;
async function load() {
try {
certs = await get<CertsView>("/certs");
problem = null;
} catch (e) {
problem = sentence(e);
}
}
onMount(load);
onDestroy(() => clearTimeout(timer));
async function issue(e?: Event) {
e?.preventDefault();
issuing = true;
nameErr = null;
try {
request = await post<PkiRequest>("/certs/devices", { name, kind });
poll();
} catch (err) {
if (err instanceof ApiError && err.body.field === "name") nameErr = err.body.message;
else problem = sentence(err);
} finally {
issuing = false;
}
}
function poll() {
clearTimeout(timer);
timer = setTimeout(async () => {
if (!request) return;
try {
request = await get<PkiRequest>(`/pki-requests/${encodeURIComponent(request.request_id)}`);
} catch {
/* keep waiting */
}
if (request?.state === "waiting") poll();
else void load();
}, 2000);
}
async function cancelRequest() {
if (!request) return;
await del(`/pki-requests/${encodeURIComponent(request.request_id)}`).catch(() => {});
request = null;
closeForm();
}
async function install(d: { id: string; name: string; kind: string }, format: "qr" | "p12") {
try {
const b = await post<Bundle>(`/certs/devices/${encodeURIComponent(d.id)}/bundle`, { format });
bundle = { device: d, b, format };
if (format === "p12") {
// The link's GET is only a page (so link previews cannot use it up); this browser is
// signed in on the same host, so it posts to the path and saves the file itself.
const res = await fetch(new URL(b.download_url, location.href).pathname, { method: "POST", credentials: "same-origin" });
if (!res.ok) {
problem = "The install file could not be downloaded. Choose Install again for a new link.";
return;
}
const href = URL.createObjectURL(await res.blob());
const a = document.createElement("a");
a.href = href;
a.download = `${d.name}.p12`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(href), 10_000);
}
} catch (e) {
problem = sentence(e);
}
}
async function revoke(d: DeviceRow) {
try {
await del(`/certs/devices/${encodeURIComponent(d.id)}`);
toast(`Revoked. ${d.name} can no longer get in.`);
confirmRevoke = null;
await load();
} catch (e) {
problem = sentence(e);
}
}
function closeForm() {
clearTimeout(timer);
name = "";
nameErr = null;
if (request?.state !== "approved") request = null;
navigate("/certificates");
}
const lifetime = $derived(certs?.device_lifetime_days ?? 365);
// The server caps it at the intermediate's end (Q7); without one it cannot issue anyway.
const until = $derived(shortDate(certs?.device_valid_until ?? new Date(Date.now() + lifetime * 86_400_000).toISOString()));
const capped = $derived(
!!certs?.device_valid_until && Date.parse(certs.device_valid_until) < Date.now() + (lifetime - 1) * 86_400_000,
);
const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => {
switch (certs?.intermediate?.state) {
case "ok": return ["healthy", "valid"];
case "due": return ["degraded", "renew soon"];
case "urgent": return ["down", "renew now"];
case "expired": return ["down", "expired"];
default: return ["unknown", "not set up"];
}
});
const kindIcon = (k: string) => (k === "phone" ? "phone" : k === "computer" ? "laptop" : "app") as "phone" | "laptop" | "app";
const issuedDevice = $derived(request?.state === "approved" && request.device_id ? { id: request.device_id, name: request.name ?? name, kind } : null);
</script>
<div class="head">
<h1 class="ia-display">Certificates</h1>
<Button variant="outline" icon="plus" label="Add a device certificate" onclick={() => navigate("/certificates/new")}>Device</Button>
</div>
<IntermediateBanner />
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if certs}
<section class="ia-card">
<p class="ia-label">Domi intermediate</p>
<p><Status kind={intState[0]} word={intState[1]} /> {#if certs.intermediate?.not_after}expires {shortDate(certs.intermediate.not_after)}{/if}</p>
<p class="ia-sub">Root stays offline ({certs.root.subject}, until {shortDate(certs.root.not_after)}).</p>
</section>
<p class="ia-label">Devices</p>
{#if certs.devices.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No device certificates yet</h2><p class="ia-text2">A device certificate lets a phone, computer or Domi app into hosts that ask for one.</p></div>
{:else}
<ul class="devices">
{#each certs.devices as d (d.id)}
<li>
<Icon name={kindIcon(d.kind)} />
<span class="dname">{d.name}</span>
<span class="ia-muted">until {shortDate(d.not_after)}</span>
{#if d.state === "revoked"}<Status kind="unknown" word="revoked {d.revoked_at ? shortDate(d.revoked_at) : ''}" />{:else if d.state === "expired"}<Status kind="down" word="expired" />{:else if Date.parse(d.not_after) - app.now < 30 * 86_400_000}<Status kind="degraded" word="renew soon" />{/if}
{#if confirmRevoke === d.id}
<span class="confirm">Revoke the certificate of "{d.name}"? It can no longer get in.
<Button small onclick={() => (confirmRevoke = null)} data-autofocus>Cancel</Button>
<Button small variant="danger" onclick={() => revoke(d)}>Revoke</Button></span>
{:else if d.state === "valid"}
<HostMenu hostname={d.name} items={[
{ label: "Install on the device", icon: "key", run: () => install(d, d.kind === "computer" ? "p12" : "qr") },
{ label: "Revoke", icon: "trash", danger: true, divider: true, run: () => (confirmRevoke = d.id) },
]} />
{/if}
</li>
{/each}
</ul>
{/if}
{/if}
{#if newDevice}
<Dialog title="New device certificate" kind="panel" onclose={closeForm}>
{#if !request}
<form id="device-form" onsubmit={issue} class="form">
<div class="domi-field">
<label class="domi-field-label" for="device-name">Device name</label>
<input id="device-name" class="domi-input" bind:value={name} autocomplete="off" aria-invalid={nameErr ? "true" : undefined} aria-describedby="device-name-h" />
{#if nameErr}<p class="domi-error"><Icon name="ring" />{nameErr}</p>{/if}
<p class="ia-hint" id="device-name-h">Shown in this list and inside the certificate.</p>
</div>
<Segmented legend="What is it" name="kind" bind:value={kind} options={[{ value: "phone", label: "Phone or tablet" }, { value: "computer", label: "Computer" }, { value: "app", label: "Domi app" }]} />
<p class="ia-hint">{#if capped}Valid until {until}, when the Domi intermediate certificate ends (renew it to issue for a full year).{:else}Valid for {lifetime} days, until {until}.{/if} It lets this device into hosts that ask for a Domi device certificate.</p>
</form>
{:else if request.state === "waiting"}
<p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p>
<p>Custos cannot approve device certificates yet, so approve it on the server, and only if it shows the same code:</p>
<p class="ia-code" aria-label="Match code {request.match_code}">{request.match_code}</p>
{#if request.approve_command}<p class="ia-hint">Run on the server:</p><pre class="ia-secret ia-cmd">{request.approve_command}</pre>{/if}
<p class="ia-muted">The request stays open for 10 minutes ({Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")} left). Nothing is issued until it is approved.</p>
<div><Button onclick={cancelRequest}>Cancel request</Button></div>
<span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span>
{:else if issuedDevice}
<Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved {atTime(request?.approved_at, app.now)}.{/snippet}</Banner>
<div class="buttons">
<Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button>
<Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button>
</div>
<p class="ia-hint">The file is protected with a one-time password shown next to the QR code.</p>
{:else}
<Banner tone="notice" live="status">{#snippet title()}{request?.message}{/snippet}
{#snippet actions()}<Button variant="outline" onclick={() => { request = null; void issue(); }}>Try again</Button>{/snippet}</Banner>
{/if}
{#snippet footer()}
{#if !request}
<Button onclick={closeForm}>Cancel</Button>
<Button variant="primary" type="submit" form="device-form" pending={issuing}>Issue</Button>
{:else if request.state !== "waiting"}
<Button onclick={() => { request = null; closeForm(); void load(); }}>Close</Button>
{/if}
{/snippet}
</Dialog>
{/if}
{#if bundle}
<Dialog title="Install on {bundle.device.name}" onclose={() => { bundle = null; void refresh(); }}>
<div class="install">
{#if bundle.b.qr_svg}
<div class="ia-qr" role="img" aria-label="QR code for downloading the certificate">{@html bundle.b.qr_svg}</div>
{/if}
<div>
<p class="ia-label">Password for the file</p>
<p class="otp">{bundle.b.one_time_password}</p>
<p class="ia-hint">Works once, for 10 minutes ({Math.floor(secondsLeft(bundle.b.expires_at) / 60)}:{String(secondsLeft(bundle.b.expires_at) % 60).padStart(2, "0")} left).</p>
</div>
</div>
<p class="ia-text2">
{#if bundle.device.kind === "computer"}Open the downloaded file and enter the password when it asks.
{:else if bundle.device.kind === "app"}In the app, choose Import certificate, pick the file, and enter the password.
{:else}Scan the code with the device's camera, open the link, and enter the password when it asks. Then allow the certificate in the device's settings.{/if}
</p>
</Dialog>
{/if}
<style>
.head { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; flex-wrap: wrap; }
.devices { list-style: none; margin: 0; padding: 0; border: 1px solid var(--hairline); border-radius: var(--radius-lg); }
.devices li { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; min-height: 56px; padding: 6px 10px 6px 16px; border-top: 1px solid var(--hairline); }
.devices li:first-child { border-top: 0; }
.dname { font-weight: 600; flex: 1 1 140px; }
.confirm { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; flex-basis: 100%; }
.form { display: flex; flex-direction: column; gap: 16px; }
.buttons { display: flex; gap: 8px; flex-wrap: wrap; }
.install { display: flex; gap: 20px; flex-wrap: wrap; align-items: flex-start; }
.otp { font-weight: 700; font-size: 1.4rem; letter-spacing: 0.08em; }
</style>
+178
View File
@@ -0,0 +1,178 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §8.1: History → pick → Restore this version (3 clicks with the nav click).
import { onMount } from "svelte";
import { Banner, Button, Status } from "@ianitor/ui";
import type { StatusKind } from "@ianitor/ui";
import HostPanel from "../components/HostPanel.svelte";
import { get, post, sentence } from "../lib/api";
import { app, changesBlocked, navigate } from "../lib/app.svelte";
import { FIELD_LABEL, fieldValue, when } from "../lib/format";
import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types";
let { host, pick }: { host?: string; pick?: string } = $props();
let entries = $state<HistoryEntry[]>([]);
let next = $state<string | null>(null);
let loaded = $state(false);
let problem = $state<string | null>(null);
let chosen = $state<string | null>(null);
let preview = $state<RestorePreview | null>(null);
let attempt = $state<ApplyView | null>(null);
let restoring = $state(false);
let resume = $state<string | null>(null);
let editFrom = $state<HostSpec | null>(null);
async function load(before?: string) {
try {
const q = new URLSearchParams({ limit: "50" });
if (host) q.set("host", host);
if (before) q.set("before", before);
const r = await get<{ entries: HistoryEntry[]; next_before: string | null }>(`/history?${q}`);
entries = before ? [...entries, ...r.entries] : r.entries;
next = r.next_before;
problem = null;
} catch (e) {
problem = sentence(e);
} finally {
loaded = true;
}
}
async function choose(id: string) {
chosen = id;
preview = null;
attempt = null;
try {
preview = await get<RestorePreview>(`/history/${encodeURIComponent(id)}/restore-preview`);
if (preview.blocked?.code === "restore.not_kept") attempt = await get<ApplyView>(`/history/${encodeURIComponent(id)}`);
} catch (e) {
problem = sentence(e);
}
}
async function restore() {
if (!chosen) return;
restoring = true;
try {
const a = await post<{ apply: ApplyView }>("/restore", { change_id: chosen, base_rev: app.overview?.rev ?? null });
resume = a.apply.id;
} catch (e) {
problem = sentence(e);
} finally {
restoring = false;
}
}
onMount(() => {
void load().then(() => {
if (pick) void choose(pick);
});
const focus = () => void load();
window.addEventListener("focus", focus);
return () => window.removeEventListener("focus", focus);
});
function stateOf(e: HistoryEntry): [StatusKind, string] {
switch (e.state) {
case "kept": return ["kept", "kept"];
case "reverted": return ["reverted", "reverted"];
case "failed": return ["reverted", "not applied"];
case "queued": return ["running", "waiting"];
default: return ["running", "applying"];
}
}
const entry = $derived(entries.find((e) => e.change_id === chosen));
const n = $derived(preview?.changes.length ?? 0);
const paused = $derived(app.overview?.paused ? !["apply.needs_attention", "control.files_unwritten"].includes(app.overview.paused_reason ?? "") : false);
const blocked = $derived(paused ? "Changes are paused." : changesBlocked() && !app.overview?.paused ? changesBlocked() : null);
function key(e: KeyboardEvent, i: number) {
const btns = Array.from(document.querySelectorAll<HTMLButtonElement>(".entries button"));
if (e.key === "ArrowDown") { e.preventDefault(); btns[Math.min(btns.length - 1, i + 1)]?.focus(); }
if (e.key === "ArrowUp") { e.preventDefault(); btns[Math.max(0, i - 1)]?.focus(); }
}
</script>
<h1 class="ia-display">{host ? `History of ${host}` : "History"}</h1>
{#if host}<div><button type="button" class="domi-btn link" onclick={() => navigate("/history")}>Show all changes</button></div>{/if}
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
<div class="cols">
<div class="list">
{#if loaded && entries.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No changes yet</h2><p class="ia-text2">Every change you apply is listed here, newest first.</p></div>
{/if}
<ul class="entries">
{#each entries as e, i (e.change_id)}
{@const [k, w] = stateOf(e)}
<li>
<button type="button" class="entry" aria-current={chosen === e.change_id ? "true" : undefined} onclick={() => choose(e.change_id)} onkeydown={(ev) => key(ev, i)}>
<span class="sum">{e.summary}</span><Status kind={k} word={w} />
<span class="ia-sub">{when(e.at, app.now)} · {e.state === "kept" ? (e.commit_short ?? "") : (e.reason_short ?? "")}</span>
</button>
</li>
{/each}
</ul>
{#if next}<Button onclick={() => load(next ?? undefined)}>Show older changes</Button>{/if}
</div>
{#if chosen && preview}
<section class="detail" aria-label="Version">
<p class="ia-label">Version of {when(entry?.at, app.now)}</p>
{#if preview.blocked?.code === "restore.not_kept"}
<h2 class="ia-h3">This change did not stay</h2>
{#if attempt?.reason}<p>{attempt.reason.message}</p>{/if}
<p class="ia-text2">This change was undone at the time, so there is nothing to go back to.</p>
{#if attempt?.attempted_host}<div><Button variant="outline" onclick={() => (editFrom = attempt?.attempted_host ?? null)}>Edit and try again</Button></div>{/if}
{:else if preview.blocked?.code === "restore.same"}
<h2 class="ia-h3">Go back to this version?</h2>
<p class="ia-text2">This version is the same as the current one. Nothing to restore.</p>
<div class="buttons"><Button onclick={() => (chosen = null)}>Close</Button></div>
{:else}
<h2 class="ia-h3">Go back to this version?</h2>
<p>{n === 1 ? "Restoring puts 1 host back to how it was then:" : `Restoring puts ${n} hosts back to how they were then:`}</p>
<ul>
{#each preview.changes as c (c.hostname)}
{#if c.effect === "added"}<li><strong>{c.hostname}</strong> is added back</li>
{:else if c.effect === "removed"}<li><strong>{c.hostname}</strong> is removed</li>
{:else}
{#each c.fields as f (f.field)}
<li><strong>{c.hostname}</strong>: {#if f.field === "headers"}header rules change{:else}{FIELD_LABEL[f.field] ?? f.field} changes from {fieldValue(f.field, f.from)} to {fieldValue(f.field, f.to)}{/if}</li>
{/each}
{/if}
{/each}
</ul>
<p class="ia-hint">Applied as a new commit with the same {app.overview?.site?.watch_seconds ?? 60}-second watch. If health checks fail, it is undone.</p>
{#if blocked}<p class="ia-hint" id="restore-blocked">{blocked}</p>{/if}
<div class="buttons">
<Button onclick={() => (chosen = null)}>Close</Button>
<Button variant="primary" onclick={restore} pending={restoring} disabled={!!blocked} describedby={blocked ? "restore-blocked" : undefined}>Restore this version</Button>
</div>
{/if}
</section>
{/if}
</div>
{#if resume}
<HostPanel resume={resume} onclose={() => { resume = null; void load(); }} />
{/if}
{#if editFrom}
<HostPanel prefill={editFrom} hostname={undefined} onclose={() => { editFrom = null; void load(); }} />
{/if}
<style>
.cols { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; }
.list { flex: 1 1 360px; max-width: 520px; display: flex; flex-direction: column; gap: 8px; }
.entries { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
.entry { display: grid; grid-template-columns: 1fr auto; gap: 2px 12px; width: 100%; min-height: 44px; padding: 10px 12px; border-radius: var(--radius-sm); border: 1px solid transparent; background: none; color: var(--text); text-align: left; cursor: pointer; }
.entry:hover { background: var(--surface); }
.entry[aria-current="true"] { background: var(--surface-2); border-color: color-mix(in srgb, var(--accent) 55%, transparent); }
.sum { font-weight: 600; }
.detail { flex: 2 1 360px; background: var(--colonnade); border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
.detail ul { margin: 0; padding-left: 1.1rem; }
.buttons { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
</style>
+132
View File
@@ -0,0 +1,132 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §5: the main screen.
import { tick } from "svelte";
import { Banner, Button } from "@ianitor/ui";
import ChangeBar from "../components/ChangeBar.svelte";
import EngineChip from "../components/EngineChip.svelte";
import HostList from "../components/HostList.svelte";
import HostPanel from "../components/HostPanel.svelte";
import IntermediateBanner from "../components/IntermediateBanner.svelte";
import ShareDialog from "../components/ShareDialog.svelte";
import { call, newKey, post, sentence } from "../lib/api";
import { app, changesBlocked, navigate, refresh, toast } from "../lib/app.svelte";
import { atTime, countsSentence } from "../lib/format";
import type { ApplyView, HostSpec } from "../lib/types";
let { route }: { route: { newHost: boolean; edit?: string } } = $props();
const o = $derived(app.overview);
let prefill = $state<HostSpec | null>(null);
let focusField = $state<string | undefined>(undefined);
let problem = $state<string | null>(null);
const panelOpen = $derived(route.newHost || !!route.edit || app.panel?.kind === "host");
const blocked = $derived(changesBlocked());
async function closePanel() {
prefill = null;
focusField = undefined;
if (app.panel?.kind === "host") app.panel = null;
if (route.newHost || route.edit) navigate("/");
await refresh();
const h = app.focusHost;
app.focusHost = null;
if (h) {
await tick();
document.querySelector<HTMLElement>(`[aria-label="More for ${h.replace(/["\\]/g, "")}"]`)?.focus();
}
}
async function remove(h: string) {
problem = null;
try {
await call("DELETE", `/hosts/${encodeURIComponent(h)}?base_rev=${encodeURIComponent(o?.rev ?? "")}`, undefined, { idem: newKey() });
await refresh();
} catch (e) {
problem = sentence(e);
}
}
async function retry(h: string) {
try {
await post(`/hosts/${encodeURIComponent(h)}/certificate/retry`);
toast("Trying Let's Encrypt again.");
} catch (e) {
problem = sentence(e);
}
}
function editAgain(a: ApplyView, field?: string) {
prefill = a.attempted_host ?? null;
focusField = field;
if (a.kind === "add" || !a.hosts[0]) {
navigate("/hosts/new");
} else {
navigate(`/hosts/${encodeURIComponent(a.hosts[0])}/edit`);
}
}
</script>
<div class="head">
<div>
<h1 class="ia-display">Hosts</h1>
{#if o}<p class={app.phone ? "ia-sub" : "ia-text2"}>{countsSentence(o.counts, app.phone)}</p>{/if}
</div>
<div class="actions">
{#if !app.phone}<EngineChip />{/if}
<Button variant="primary" icon="plus" label="Add a host" disabled={!!blocked} describedby={blocked ? "add-blocked" : undefined} onclick={() => navigate("/hosts/new")}>Host</Button>
{#if blocked}<span class="sr-only" id="add-blocked">{blocked}</span>{/if}
</div>
</div>
<IntermediateBanner />
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
<ChangeBar onshowsteps={(id) => (app.panel = { kind: "host", resume: id })} onedit={editAgain} />
{#if !o && !app.loadError}
<div class="ia-list" aria-busy="true"><span class="sr-only">Loading hosts…</span>
{#each [0, 1, 2] as i (i)}<div class="ia-row"><span class="ia-placeholder"></span><span class="ia-placeholder"></span><span class="ia-placeholder"></span><span></span></div>{/each}
</div>
{:else if app.loadError && !o}
<Banner tone="down" live="alert">{#snippet title()}This page could not load. Ianitor's control service may be restarting.{/snippet}
{#snippet actions()}<Button onclick={() => refresh()}>Try again now</Button>{/snippet}</Banner>
{:else if o && o.hosts.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No hosts yet</h2><p class="ia-text2">Add the first one: the name people type, and where Ianitor should send them.</p></div>
{:else if o}
<HostList hosts={o.hosts}
onedit={(h) => navigate(`/hosts/${encodeURIComponent(h)}/edit`)}
onremove={remove}
onshare={(h) => (app.panel = { kind: "share", hostname: h })}
onhistory={(h) => navigate(`/history?host=${encodeURIComponent(h)}`)}
onretry={retry} />
{/if}
{#if o?.repo}
<hr class="ia-ornament" />
<p class="ia-muted footer">
Routes live in the {o.repo.name} repository, one file per host.
{#if o.repo.last_push_at}Last pushed to Gitea {atTime(o.repo.last_push_at, app.now)}.{/if}
{#if o.repo.unpushed}{o.repo.unpushed} changes not yet pushed.{/if}
<button type="button" class="domi-btn link" onclick={() => navigate("/history")}>See history</button>
</p>
{/if}
{#if panelOpen}
{#key route.edit ?? (app.panel?.kind === "host" ? app.panel.resume : "new")}
<HostPanel hostname={route.edit} resume={app.panel?.kind === "host" ? app.panel.resume : undefined} {prefill} {focusField} onclose={closePanel} />
{/key}
{/if}
{#if app.panel?.kind === "share"}
<ShareDialog hostname={app.panel.hostname} onclose={() => { app.panel = null; void refresh(); }} />
{/if}
<style>
.head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 16px; }
.actions { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
.footer { text-align: center; }
</style>
+143
View File
@@ -0,0 +1,143 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §13.6: signing the intermediate by hand on the offline computer (the temporary step
// until Custos can sign, docs/pki.md). The root key never comes to this server.
import { Banner, Button, Icon } from "@ianitor/ui";
import { ApiError, post, put, sentence } from "../lib/api";
import { app, navigate, refresh } from "../lib/app.svelte";
import type { PkiRequest } from "../lib/types";
const r = $derived(app.overview?.intermediate?.renewal ?? null);
let pem = $state("");
let paste = $state(false);
let err = $state<string | null>(null);
let pending = $state(false);
let starting = $state(false);
const base = $derived(r?.file_base ?? `domi-intermediate-${new Date().toISOString().slice(0, 10)}`);
const signCmd = $derived(r?.approve_command ?? `openssl x509 -req -in ${base}.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile ${base}.ext -out ${base}.crt`);
const checkCmd = $derived(`openssl req -in ${base}.csr -outform DER | openssl dgst -sha256`);
let copied = $state(false);
// Groups of 8, easier to compare by eye; openssl prints it without spaces.
const group = (h: string) => h.match(/.{1,8}/g)?.join(" ") ?? h;
async function copy(text: string) {
try {
await navigator.clipboard.writeText(text);
copied = true;
setTimeout(() => (copied = false), 3000);
} catch {
err = "Your browser did not allow copying. Select the command and copy it.";
}
}
function save(text: string, name: string, type: string) {
const url = URL.createObjectURL(new Blob([text], { type }));
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
function download() {
if (r?.csr_pem) save(r.csr_pem, `${base}.csr`, "application/pkcs10");
}
async function downloadExt() {
if (!r) return;
try {
const res = await fetch(`/api/v1/pki-requests/${encodeURIComponent(r.request_id)}/ext`, { headers: { "X-Ianitor-UI": "1" }, redirect: "manual", credentials: "same-origin" });
if (res.ok) save(await res.text(), `${base}.ext`, "text/plain");
else err = "The signing settings file could not be downloaded. Reload the page and try again.";
} catch {
err = "Ianitor's control service is not answering.";
}
}
async function file(e: Event) {
const f = (e.currentTarget as HTMLInputElement).files?.[0];
if (f) pem = await f.text();
}
async function use() {
if (!r) return;
pending = true;
err = null;
try {
const done = await put<PkiRequest>(`/pki-requests/${encodeURIComponent(r.request_id)}/certificate`, { certificate_pem: pem });
app.renewedUntil = done.not_after;
await refresh();
navigate("/certificates");
} catch (e) {
err = e instanceof ApiError ? e.body.message : sentence(e);
} finally {
pending = false;
}
}
async function start() {
starting = true;
try {
await post("/certs/intermediate/renewal");
await refresh();
} catch (e) {
err = sentence(e);
} finally {
starting = false;
}
}
</script>
<h1 class="ia-display">Sign the intermediate by hand</h1>
<p class="ia-text2">Custos cannot sign certificates yet, so the Domi root signs on the offline computer. The root key never comes to this server.</p>
{#if !r}
<Banner tone="notice">{#snippet title()}There is no open renewal request.{/snippet}
{#snippet actions()}<Button variant="outline" onclick={start} pending={starting}>Start a renewal</Button>{/snippet}</Banner>
{:else}
<section class="step">
<p class="ia-label">Step 1</p>
<h2 class="ia-h3">Download the request</h2>
<p class="ia-text2">This file asks the Domi root to sign a new intermediate certificate. It holds no secret.</p>
<div class="row"><Button icon="download" onclick={download}>Download the request (.csr)</Button><Button icon="download" onclick={downloadExt}>Download the signing settings (.ext)</Button></div>
</section>
<section class="step">
<p class="ia-label">Step 2</p>
<h2 class="ia-h3">Sign it on the offline computer</h2>
<p class="ia-text2">Copy both files to the offline computer that holds the Domi root.</p>
<p class="ia-text2">First check that the request is the one this server made. This prints its fingerprint:</p>
<pre class="ia-secret ia-cmd">{checkCmd}</pre>
{#if r.csr_sha256}<p>openssl must print the same fingerprint as this page: <span class="ia-cmd fp" aria-label="Fingerprint {r.csr_sha256}">{group(r.csr_sha256)}</span></p>{/if}
<p class="ia-text2">Then sign it:</p>
<pre class="ia-secret ia-cmd">{signCmd}</pre>
<div class="row"><Button icon="copy" onclick={() => copy(signCmd)}>Copy command</Button>{#if copied}<span class="ia-status" data-s="kept" role="status"><Icon name="check" />Copied</span>{/if}</div>
<p class="ia-muted">On a computer with Ianitor installed, <code>ianitor-control ca sign</code> signs it instead and shows the match code {r.match_code}.</p>
</section>
<section class="step">
<p class="ia-label">Step 3</p>
<h2 class="ia-h3">Upload the signed certificate</h2>
{#if paste}
<div class="domi-field">
<label class="domi-field-label" for="cert-paste">Signed certificate</label>
<textarea id="cert-paste" class="domi-input" rows="8" bind:value={pem} aria-invalid={err ? "true" : undefined}></textarea>
</div>
{:else}
<div class="domi-field">
<label class="domi-field-label" for="cert-file">Signed certificate (.crt)</label>
<input id="cert-file" class="domi-input" type="file" accept=".crt,.pem" onchange={file} aria-invalid={err ? "true" : undefined} />
<div><button type="button" class="domi-btn link" onclick={() => (paste = true)}>Paste it instead</button></div>
</div>
{/if}
{#if err}<p class="domi-error" role="alert"><Icon name="ring" />{err}</p>{/if}
<div><Button variant="primary" onclick={use} {pending} disabled={!pem.includes("BEGIN CERTIFICATE")}>Use this certificate</Button></div>
</section>
{/if}
<style>
.row { display: flex; gap: 8px; flex-wrap: wrap; }
.step { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
.fp { word-break: break-all; color: var(--accent-strong); }
</style>
+280
View File
@@ -0,0 +1,280 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §8.3: Settings with General, API (⚙ → API → New token = 3 clicks, Copy token the
// accepted 4th), Share links and About.
import { onMount } from "svelte";
import { Banner, Button, Dialog, Segmented } from "@ianitor/ui";
import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api";
import { app, navigate, toast } from "../lib/app.svelte";
import { longDate, shortDate, whenInline } from "../lib/format";
import type { CreatedToken, ShareLink, TokenRow } from "../lib/types";
let { tab }: { tab: string } = $props();
const TABS = [
{ id: "general", label: "General" },
{ id: "api", label: "API" },
{ id: "share-links", label: "Share links" },
{ id: "about", label: "About" },
];
let settings = $state<{ repo: { name: string; last_push_at: string | null } | null; watch_seconds: number } | null>(null);
let tokens = $state<TokenRow[]>([]);
let revoked = $state<Record<string, string>>({});
let links = $state<ShareLink[]>([]);
let problem = $state<string | null>(null);
let expiry = $state<"year" | "never">("year");
let made = $state<CreatedToken | null>(null);
let tokenName = $state("");
let tokenCopied = $state(false);
let askClose = $state(false);
let nameErr = $state<string | null>(null);
let confirmRevoke = $state<string | null>(null);
let confirmStopAll = $state(false);
let creating = $state(false);
async function load() {
try {
if (tab === "general") settings = await get("/settings");
if (tab === "api") tokens = (await get<{ items: TokenRow[] }>("/tokens")).items;
if (tab === "share-links") links = (await get<{ items: ShareLink[] }>("/share-links")).items;
problem = null;
} catch (e) {
problem = sentence(e);
}
}
$effect(() => {
void tab;
void load();
});
onMount(() => {
const f = () => void load();
window.addEventListener("focus", f);
return () => window.removeEventListener("focus", f);
});
function tabKey(e: KeyboardEvent, i: number) {
let j = i;
if (e.key === "ArrowRight") j = (i + 1) % TABS.length;
else if (e.key === "ArrowLeft") j = (i - 1 + TABS.length) % TABS.length;
else if (e.key === "Home") j = 0;
else if (e.key === "End") j = TABS.length - 1;
else return;
e.preventDefault();
navigate(`/settings/${TABS[j].id}`);
setTimeout(() => document.getElementById(`tab-${TABS[j].id}`)?.focus(), 0);
}
async function newToken() {
creating = true;
try {
const name = `Token made ${shortDate(new Date().toISOString())}`;
const body = expiry === "never" ? { name, never_expires: true } : { name, expires_in_days: 365 };
made = await post<CreatedToken>("/tokens", body);
tokenName = made.name;
tokenCopied = false;
askClose = false;
} catch (e) {
problem = sentence(e);
} finally {
creating = false;
}
}
async function copyToken() {
if (!made) return;
try {
await navigator.clipboard.writeText(made.token);
tokenCopied = true;
} catch {
problem = "Your browser did not allow copying. Select the token and press Ctrl+C.";
}
}
async function closeToken(force = false) {
if (!made) return;
if (!tokenCopied && !force) {
askClose = true;
return;
}
if (tokenName.trim() && tokenName !== made.name) {
try {
await patch(`/tokens/${encodeURIComponent(made.id)}`, { name: tokenName.trim() });
toast("Renamed.");
} catch (e) {
if (e instanceof ApiError && e.code === "token.name") {
nameErr = e.body.message;
return;
}
}
}
// The token leaves memory with the dialog.
made = null;
tokenName = "";
void load();
}
async function revoke(t: TokenRow) {
try {
await del(`/tokens/${encodeURIComponent(t.id)}`);
revoked = { ...revoked, [t.id]: new Date().toISOString() };
confirmRevoke = null;
toast(`Revoked. Anything using "${t.name}" stops working now.`);
} catch (e) {
problem = sentence(e);
}
}
async function stop(l: ShareLink) {
try {
await del(`/share-links/${encodeURIComponent(l.id)}`);
toast("Stopped. The link stops working within a few seconds.");
void load();
} catch (e) {
problem = sentence(e);
}
}
async function stopAll() {
try {
await call("POST", "/share-links/stop-all", {}, { idem: newKey() });
toast("All share links are stopped. New ones work as usual.");
confirmStopAll = false;
void load();
} catch (e) {
problem = sentence(e);
}
}
const active = $derived(links.filter((l) => l.state === "active"));
const ended = $derived(links.filter((l) => l.state !== "active"));
const viewer = $derived(app.overview?.viewer ?? null);
</script>
<h1 class="ia-display">Settings</h1>
<div class="tabs" role="tablist" aria-label="Settings">
{#each TABS as t, i (t.id)}
<button type="button" role="tab" id="tab-{t.id}" aria-selected={tab === t.id} aria-controls="panel-{t.id}" tabindex={tab === t.id ? 0 : -1}
onclick={() => navigate(`/settings/${t.id}`)} onkeydown={(e) => tabKey(e, i)}>{t.label}</button>
{/each}
</div>
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
<div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel">
{#if tab === "general"}
<p class="ia-label">Routes repository</p>
<p>{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + whenInline(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</p>
<p class="ia-label">Health watch after apply</p>
<p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p>
<p class="ia-label">Signed in</p>
<p>{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : `API token "${viewer.name}"`) : "Through Authelia"}</p>
{#if app.overview?.site?.auth_logout_url}<p><a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a></p>{/if}
{:else if tab === "api"}
<div class="row">
<h2 class="ia-h3">API tokens</h2>
<Button variant="outline" icon="plus" onclick={newToken} pending={creating}>New token</Button>
<Segmented legend="New tokens expire after" name="token-expiry" bind:value={expiry} options={[{ value: "year", label: "1 year" }, { value: "never", label: "Never" }]} />
</div>
<p class="ia-hint">The API listens on 127.0.0.1 only. Ianitor keeps a hash of each token, never the token.</p>
{#if tokens.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No API tokens</h2><p class="ia-text2">Scripts and other Domi apps use a token to talk to Ianitor.</p></div>
{:else}
<ul class="rows">
{#each tokens as t (t.id)}
<li>
<div class="grow">
<span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span>
<span class="ia-sub" style="display:block">
{#if revoked[t.id]}Revoked {whenInline(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${whenInline(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if}
</span>
</div>
{#if !revoked[t.id] && !t.revoked_at}
{#if confirmRevoke === t.id}
<span>Revoke "{t.name}"? Anything using it stops working now.</span>
<Button small onclick={() => (confirmRevoke = null)} data-autofocus>Cancel</Button>
<Button small variant="danger" onclick={() => revoke(t)}>Revoke</Button>
{:else}
<Button small variant="danger" onclick={() => (confirmRevoke = t.id)}>Revoke</Button>
{/if}
{/if}
</li>
{/each}
</ul>
{/if}
{:else if tab === "share-links"}
<div class="row">
<h2 class="ia-h3">Share links</h2>
{#if active.length}<Button variant="danger" onclick={() => (confirmStopAll = true)}>Stop all share links</Button>{/if}
</div>
{#if app.overview?.engine.running === "caddy"}
<Banner tone="notice">{#snippet title()}Caddy is serving, so these links do not work right now. They work again after switching back to Pingora.{/snippet}</Banner>
{/if}
{#if confirmStopAll}
<p>Stop all {active.length} active links? Every link made so far stops working. New ones work as usual.
<Button small onclick={() => (confirmStopAll = false)}>Cancel</Button> <Button small variant="danger" onclick={stopAll}>Stop all</Button></p>
{/if}
{#if links.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No share links</h2><p class="ia-text2">Make one from a host's menu (⋯), Share link.</p></div>
{:else}
<ul class="rows">
{#each active as l (l.id)}
<li>
<div class="grow"><strong>{l.hostname}</strong>{l.path_prefix !== "/" ? l.path_prefix : ""}
<span class="ia-sub" style="display:block">Made {whenInline(l.created_at, app.now)} · expires {whenInline(l.expires_at, app.now)}{l.has_password ? " · password" : ""}</span></div>
<Button small onclick={() => stop(l)}>Stop this link</Button>
</li>
{/each}
</ul>
{#if ended.length}
<details><summary>Ended ({ended.length})</summary>
<ul class="rows">{#each ended as l (l.id)}<li><span class="grow">{l.hostname}{l.path_prefix !== "/" ? l.path_prefix : ""}</span><span class="ia-sub">{l.state} {shortDate(l.expires_at)}</span></li>{/each}</ul>
</details>
{/if}
{/if}
{:else}
<p>Ianitor Domi 0.1.0</p>
<p>MPL-2.0</p>
<p>Built, tested and signed by Fabrica Domi</p>
<p><a class="domi-btn link" href="https://gitea.marek-novak.cz/mnovak/Ianitor" rel="noreferrer">Source on Gitea</a></p>
{/if}
</div>
{#if made}
<Dialog title="Your new token" escape={false} onclose={() => closeToken()}>
<p><strong>Copy it now and save it in Custos.</strong></p>
<p class="ia-text2">Ianitor cannot show it again; if it is lost, make a new one and revoke this one.</p>
<input class="ia-secret" readonly value={made.token} aria-label="New API token" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} />
<div class="grid">
<div class="domi-field">
<label class="domi-field-label" for="token-name">Name</label>
<input id="token-name" class="domi-input" bind:value={tokenName} aria-invalid={nameErr ? "true" : undefined} />
{#if nameErr}<p class="domi-error">{nameErr}</p>{/if}
<p class="ia-hint">Rename it now or later, so you know what uses it.</p>
</div>
<Button variant={tokenCopied ? "quiet" : "primary"} icon="copy" onclick={copyToken} data-autofocus>{tokenCopied ? "Copy again" : "Copy token"}</Button>
</div>
{#if tokenCopied}<p role="status">Copied. Paste it into Custos now. Ianitor cannot show it again.</p>{/if}
<p class="ia-muted">{made.expires_at ? `Expires on ${longDate(made.expires_at, false)}.` : "Never expires."}</p>
{#if askClose}
<p role="alert">Close without copying? The token cannot be shown again.
<Button small onclick={() => (askClose = false)}>Go back</Button> <Button small variant="danger" onclick={() => closeToken(true)}>Close anyway</Button></p>
{/if}
{#snippet footer()}<Button onclick={() => closeToken()}>I have saved it</Button>{/snippet}
</Dialog>
{/if}
<style>
.tabs { display: flex; gap: 4px; overflow-x: auto; }
.tabs [role="tab"] { min-height: 44px; padding: 0 1rem; border-radius: var(--radius-sm); border: 0; background: none; color: var(--text-2); font-weight: 600; cursor: pointer; }
.tabs [role="tab"][aria-selected="true"] { background: var(--surface-2); color: var(--text); }
.panel { display: flex; flex-direction: column; gap: 10px; }
.row { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; }
.rows { list-style: none; margin: 0; padding: 0; }
.rows li { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; min-height: 44px; padding: 8px 0; border-top: 1px solid var(--hairline); }
.grow { flex: 1 1 200px; min-width: 0; }
.tname { font-weight: 600; }
.struck { text-decoration: line-through; color: var(--muted); }
.grid { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: end; }
@media (max-width: 719.98px) { .grid { grid-template-columns: 1fr; } }
</style>
+33
View File
@@ -0,0 +1,33 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §10.2: Authelia sends the sign-in tab back here; it tells the first tab and closes.
import { onMount } from "svelte";
onMount(() => {
const back = new URL(location.href).searchParams.get("back");
try {
const ch = new BroadcastChannel("ianitor-auth");
ch.postMessage("signed-in");
ch.close();
} catch {
/* the first tab rechecks with "I have signed in" */
}
if (back && back.startsWith("/") && !back.startsWith("//")) {
location.replace(back);
return;
}
setTimeout(() => window.close(), 300);
});
</script>
<main class="signed-in">
<p class="ia-wordmark">IANITOR DOMI</p>
<h1 class="ia-h3">You are signed in again.</h1>
<p class="ia-text2">You can close this tab and go back to Ianitor.</p>
</main>
<style>
.signed-in { max-width: 420px; margin: 20vh auto; padding: 0 16px; display: flex; flex-direction: column; gap: 12px; }
</style>
+7
View File
@@ -0,0 +1,7 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
export default { preprocess: vitePreprocess() };
+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;
}
+245
View File
@@ -0,0 +1,245 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The smoke test of every ROADMAP §4 flow with its clicks counted (handoff §4, §15): the real
// app against a stand-in for control's API. Typing, focus and waiting are not clicks.
import { cleanup, render, screen, waitFor, within } from "@testing-library/svelte";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import App from "../src/App.svelte";
import { app } from "../src/lib/app.svelte";
import { installMock, type Mock } from "./mockApi";
let mock: Mock;
let clicks = 0;
let user: ReturnType<typeof userEvent.setup>;
async function click(el: Element) {
clicks++;
await user.click(el);
}
function start(path = "/") {
history.replaceState({}, "", path);
app.path = path;
app.panel = null;
app.overview = null;
app.etag = null;
app.signedOut = false;
app.switchResult = null;
app.renewedUntil = null;
app.dismissed = [];
mock = installMock();
clicks = 0;
user = userEvent.setup();
render(App);
}
const called = (method: string, path: string) => mock.calls.some((c) => c.method === method && c.path.startsWith(path));
const T = { timeout: 5000 };
beforeEach(() => {
try {
sessionStorage.clear();
} catch {
/* none */
}
});
afterEach(() => cleanup());
describe("ROADMAP §4 flows, clicks counted", () => {
it("Add host: + Host → fill → Apply = 2 clicks, auto-kept", async () => {
start();
await click(await screen.findByRole("button", { name: "Add a host" }));
await user.type(await screen.findByLabelText("Hostname"), "recipes.home.test");
await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080");
await click(screen.getByRole("button", { name: "Apply" }));
// Kept: the panel closes by itself and the new host is in the list.
await waitFor(() => expect(called("GET", "/applies/ch_new")).toBe(true), T);
await waitFor(() => expect(document.querySelector("dialog.ia-panel")).toBeNull(), T);
await screen.findByRole("button", { name: "More for recipes.home.test" }, T);
expect(called("POST", "/hosts")).toBe(true);
const sent = mock.calls.find((c) => c.method === "POST" && c.path === "/hosts")?.body as { host: Record<string, unknown> };
// Every field is sent explicitly, with the design's defaults.
expect(sent.host).toMatchObject({ hostname: "recipes.home.test", tls: "domi", auth: "forward-auth", websockets: true });
expect(clicks).toBe(2);
});
it("Undo last change = 1 click", async () => {
start();
await click(await screen.findByRole("button", { name: /^Undo: Added recipes\.home\.test/ }));
await waitFor(() => expect(called("POST", "/undo")).toBe(true));
const body = mock.calls.find((c) => c.path === "/undo" && c.method === "POST")?.body as Record<string, string>;
expect(body.target_change_id).toBe("ch_1");
expect(clicks).toBe(1);
});
it("Restore: History → pick → Restore = 3 clicks", async () => {
start();
await screen.findByRole("button", { name: "Add a host" });
const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
await click(within(nav).getByRole("link", { name: "History" }));
await click(await screen.findByRole("button", { name: /Changed wiki\.home\.test/ }));
await screen.findByText(/sends traffic to changes from/);
await click(await screen.findByRole("button", { name: "Restore this version" }));
await waitFor(() => expect(called("POST", "/restore")).toBe(true));
expect(clicks).toBe(3);
});
it("Share link: ⋯ → Share link → Copy = 3 clicks (default expiry 7 days)", async () => {
start();
await click(await screen.findByRole("button", { name: "More for wiki.home.test" }));
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
const copy = await screen.findByRole("button", { name: "Copy link" });
await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull());
await click(copy);
await screen.findByText("Copied");
const mint = mock.calls.find((c) => c.method === "POST" && c.path.endsWith("/share-links"))?.body as Record<string, unknown>;
expect(mint.expires_in_s).toBe(604800);
expect(await navigator.clipboard.readText()).toContain("?share=ish1.");
expect(clicks).toBe(3);
});
it("Share link on a host with links off: 4 clicks (Mark, Q1: the accepted 4th)", async () => {
start();
await click(await screen.findByRole("button", { name: "More for photos.home.test" }));
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
await click(await screen.findByRole("button", { name: "Turn on share links" }));
const copy = await screen.findByRole("button", { name: "Copy link" }, T);
await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull());
await click(copy);
await screen.findByText("Copied");
expect(called("PATCH", "/hosts/photos.home.test")).toBe(true);
expect(clicks).toBe(4);
});
it("Switch engine: engine chip → Switch to Caddy = 2 clicks", async () => {
start();
await click(await screen.findByRole("button", { name: /^Engine: Pingora/ }));
await click(await screen.findByRole("button", { name: "Switch to Caddy" }));
await waitFor(() => expect(called("POST", "/engine")).toBe(true));
const body = mock.calls.find((c) => c.method === "POST" && c.path === "/engine")?.body as Record<string, string>;
expect(body.target).toBe("caddy");
await screen.findByText("Now serving with Caddy.", {}, T);
expect(clicks).toBe(2);
});
it("Device certificate: Certificates → + Device → Issue = 3 clicks; install is the accepted 4th", async () => {
start();
await screen.findByRole("button", { name: "Add a host" });
const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
await click(within(nav).getByRole("link", { name: "Certificates" }));
await click(await screen.findByRole("button", { name: "Add a device certificate" }));
await user.type(await screen.findByLabelText("Device name"), "Mark's phone");
await click(screen.getByRole("button", { name: "Issue" }));
await screen.findByLabelText("Match code 47 19 83");
expect(clicks).toBe(3);
// Approved on the server (the stand-in approves on the first poll).
await click(await screen.findByRole("button", { name: "Show QR code" }, T));
await screen.findByText("ABCD-EFGH-JKLM-NPQR");
expect(clicks).toBe(4);
});
it("Renew intermediate: banner Renew = 1 click", async () => {
start();
await click(await screen.findByRole("button", { name: "Renew" }));
await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true));
// The renewal is waiting: the banner says where to sign it (no code to compare with openssl).
await screen.findByRole("button", { name: "Sign it by hand" });
expect(clicks).toBe(1);
});
it("API token: ⚙ → API → New token = 3 clicks; Copy token is the accepted 4th", async () => {
start();
await screen.findByRole("button", { name: "Add a host" });
const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
await click(within(nav).getByRole("link", { name: "Settings" }));
await click(await screen.findByRole("tab", { name: "API" }));
await click(await screen.findByRole("button", { name: "New token" }));
const box = (await screen.findByLabelText("New API token")) as HTMLInputElement;
expect(box.value).toBe("ian_tk1_secretvalue");
expect(clicks).toBe(3);
await click(screen.getByRole("button", { name: "Copy token" }));
expect(await navigator.clipboard.readText()).toBe("ian_tk1_secretvalue");
expect(clicks).toBe(4);
// The token is never stored by the page.
expect(JSON.stringify({ ...sessionStorage })).not.toContain("ian_tk1");
expect(JSON.stringify({ ...localStorage })).not.toContain("ian_tk1");
});
});
describe("focus", () => {
it("+ Host puts the cursor in Hostname, so typing right after the click lands there", async () => {
start();
await click(await screen.findByRole("button", { name: "Add a host" }));
await user.keyboard("recipes.home.test");
expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("recipes.home.test");
});
it("the share dialog opens on Copy link and gives focus back to the row's More button", async () => {
start();
const more = await screen.findByRole("button", { name: "More for wiki.home.test" });
await click(more);
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
const copy = await screen.findByRole("button", { name: "Copy link" });
await waitFor(() => expect(document.activeElement).toBe(copy));
// jsdom fires no cancel event on Esc for a modal dialog: close it with its button.
await click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("button", { name: "Copy link" })).toBeNull());
await waitFor(() => expect(document.activeElement).toBe(more));
});
it("the engine popover closes with Esc and focus goes back to the chip", async () => {
start();
const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
await click(chip);
await screen.findByRole("button", { name: "Switch to Caddy" });
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
expect(document.activeElement).toBe(screen.getByRole("button", { name: /^Engine: Pingora/ }));
});
it("a click on the engine chip while its popover is open closes it", async () => {
start();
const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
await click(chip);
await screen.findByRole("button", { name: "Switch to Caddy" });
await new Promise((r) => setTimeout(r, 10));
await click(chip);
await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
});
});
describe("sign-in and contact", () => {
it("a 401 without Ianitor's envelope shows the signed-out dialog", async () => {
start();
await screen.findByRole("button", { name: "Add a host" });
globalThis.fetch = (async () => new Response("", { status: 401 })) as typeof fetch;
app.etag = null;
await click(screen.getByRole("button", { name: "Add a host" }));
await user.type(await screen.findByLabelText("Hostname"), "x.home.test");
await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080");
await click(screen.getByRole("button", { name: "Apply" }));
await screen.findByRole("alertdialog", { name: "Your sign-in has ended" });
// What was typed is still there.
expect((screen.getByLabelText("Hostname") as HTMLInputElement).value).toBe("x.home.test");
});
it("every request carries the UI header and no token", async () => {
const seen: Headers[] = [];
start();
const inner = globalThis.fetch;
globalThis.fetch = (async (i: RequestInfo | URL, init?: RequestInit) => {
seen.push(new Headers(init?.headers));
return inner(i, init);
}) as typeof fetch;
await click(await screen.findByRole("button", { name: /^Undo:/ }));
await waitFor(() => expect(seen.length).toBeGreaterThan(0));
for (const h of seen) {
expect(h.get("X-Ianitor-UI")).toBe("1");
expect(h.get("Authorization")).toBeNull();
}
});
});
+194
View File
@@ -0,0 +1,194 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// A stateful stand-in for control's API, shaped like the real answers (docs/api.md), so the
// smoke tests can walk every §4 flow and count its clicks. Its builders and routes are also the
// base of the screenshots' demo control plane (demo.ts, docs/release.md).
type Json = Record<string, unknown>;
export interface Mock {
calls: { method: string; path: string; body: unknown }[];
state: {
engine: "pingora" | "caddy";
switching: number;
intermediate: "ok" | "due";
renewal: boolean;
requestPolls: number;
hostsAdded: string[];
};
}
/** The stand-in's clock: the real one, or a fixed instant (the e2e suite's, so two takes of a screen match). */
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();
export function host(hostname: string, share: boolean) {
return {
hostname,
upstreams: ["http://10.0.0.2:3000"],
tls: "domi",
auth: "forward-auth",
websockets: true,
share_links: share,
device_certs: false,
added_at: null,
health: { state: "healthy", last_check_at: now(), latency_ms: 12, since: now(), failure: null, upstreams: [] },
certificate: { state: "ok", not_after: later(86400 * 80), error_code: null },
};
}
export function apply(id: string, state: string, summary: string, hosts: string[]) {
return {
id,
change_id: id,
kind: "add",
summary,
hosts,
state,
created_at: now(),
finished_at: state === "kept" ? now() : null,
steps: ["validate", "compile", "write", "reload", "watch", "push"].map((key) => ({ key, state: state === "kept" ? "done" : "pending" })),
queue: null,
watch: null,
reason: state === "kept" ? { code: "apply.kept", message: `${hosts[0]} is live. Health checks passed for 60 s.` } : null,
errors: [],
commit_short: "4f1c2ab",
push: null,
attempted_host: null,
};
}
/** One API call: method, the path after /api/v1, and its answer as [status, body]. */
export type Route = [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]];
export function newMock(): Mock {
return {
calls: [],
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 => ({
counts: { hosts: 2 + m.state.hostsAdded.length, healthy: 2, degraded: 0, down: 0, unknown: 0 },
hosts: [host("wiki.home.test", true), host("photos.home.test", false), ...m.state.hostsAdded.map((h) => host(h, false))],
engine: {
running: m.state.engine,
state: m.state.switching > 0 ? "switching" : "running",
since: now(),
target: null,
switchable: true,
fallback_ready: { built_at: now(), current: true, compared: 3, matched: 3, differences: ["Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."] },
last_error: null,
notes: [],
},
last_apply: apply("ch_1", "kept", "Added recipes.home.test", ["recipes.home.test"]),
undo: {
available: true,
target: { change_id: "ch_1", summary: "Added recipes.home.test", kept_at: now(), commit_short: "4f1c2ab" },
effect: "Removes recipes.home.test",
blocked: null,
},
active_apply: null,
repo: { name: "ianitor-routes", last_push_at: now(), unpushed: 0, push_error_code: null },
intermediate:
m.state.intermediate === "due"
? {
state: "due",
subject: "Ianitor Domi Intermediate 2025-12",
not_after: later(86400 * 23),
days_left: 23,
renewal: m.state.renewal
? { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(3600), approved_at: null, device_id: null, name: null, csr_pem: "-----BEGIN CERTIFICATE REQUEST-----\nx\n-----END CERTIFICATE REQUEST-----\n", not_after: null, message_code: "pki.renew.manual", message: "Sign this request…", approve_command: "ianitor-control ca sign …", problem: null }
: null,
banner: m.state.renewal ? null : { code: "pki.renew_due", message: "The Domi intermediate certificate expires in 23 days, on 30 November 2026." },
}
: { state: "ok", subject: "x", not_after: later(86400 * 300), days_left: 300, renewal: null, banner: null },
site: { forward_auth_configured: true, acme_configured: true, secrets: ["api_key"], watch_seconds: 60, share_links_available: true },
paused: null,
paused_reason: null,
health_error: null,
rev: "rev1",
viewer: { name: "mark", via: "authelia" },
server_time: now(),
});
return [
["GET", /^\/overview$/, () => [200, overview()]],
["POST", /^\/hosts\/validate/, () => [200, { message: "This host can be applied." }]],
["POST", /^\/hosts$/, (_, b) => {
const h = (b.host as Json).hostname as string;
m.state.hostsAdded.push(h);
return [202, { apply: apply("ch_new", "queued", `Added ${h}`, [h]) }];
}],
["GET", /^\/applies\/ch_new$/, () => [200, apply("ch_new", "kept", `Added ${m.state.hostsAdded.at(-1)}`, [m.state.hostsAdded.at(-1) ?? ""])]],
["GET", /^\/applies\/(.+)$/, (mm) => [200, apply(mm[1], "kept", "Done", ["x.home.test"])]],
["POST", /^\/undo$/, () => [202, { apply: apply("ch_undo", "queued", "Undid: Added recipes.home.test", ["recipes.home.test"]) }]],
["GET", /^\/history(\?.*)?$/, () => [200, { entries: [{ change_id: "ch_old", summary: "Changed wiki.home.test", kind: "edit", state: "kept", at: now(), commit_short: "9b20e7d", hosts: ["wiki.home.test"], reason_short: null }], next_before: null }]],
["GET", /^\/history\/ch_old\/restore-preview$/, () => [200, { restorable: true, same_as_current: false, changes: [{ hostname: "wiki.home.test", effect: "changed", fields: [{ field: "upstreams", from: "http://10.0.0.2:3000", to: "http://10.0.0.9:3000" }] }], blocked: null }]],
["POST", /^\/restore$/, () => [202, { apply: apply("ch_restore", "queued", "Restored the version of 5 November 2026", ["wiki.home.test"]) }]],
["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_1", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.abc`, expires_at: later(7 * 86400), path_prefix: "/", has_password: false, warning: null }]],
["PATCH", /^\/hosts\/([^/]+)$/, (mm) => [202, { apply: apply("ch_share", "queued", `Turned share links on for ${decodeURIComponent(mm[1])}`, [decodeURIComponent(mm[1])]) }]],
["DELETE", /^\/share-links\/.+$/, () => [204, null]],
["GET", /^\/engine$/, () => {
if (m.state.switching > 0) {
m.state.switching--;
if (m.state.switching === 0) m.state.engine = "caddy";
}
return [200, { running: m.state.engine, state: m.state.switching > 0 ? "switching" : "running", target: null, since: now(), switchable: true, last_error: null, notes: [] }];
}],
["POST", /^\/engine$/, () => {
m.state.switching = 1;
return [202, { running: m.state.engine, state: "switching", target: "caddy", since: now(), switchable: true, last_error: null, notes: [] }];
}],
["GET", /^\/certs$/, () => [200, { intermediate: overview().intermediate, root: { offline: true, subject: "Domi PKI Root", not_after: later(86400 * 3000), sha256: "ab" }, devices: [], device_lifetime_days: 365, server_lifetime_days: 90, approval: "manual", requests: [] }]],
["POST", /^\/certs\/devices$/, (_, b) => [202, { request_id: "pr_dev", kind: "device", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: null, device_id: null, name: b.name, csr_pem: null, not_after: null, message_code: "pki.waiting.manual", message: "Approve it on the server…", approve_command: "ianitor-control pki approve 47 19 83", problem: null }]],
["GET", /^\/pki-requests\/pr_dev$/, () => {
m.state.requestPolls++;
return [200, { request_id: "pr_dev", kind: "device", state: "approved", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: now(), device_id: "dv_1", name: "Mark's phone", csr_pem: null, not_after: null, message_code: "pki.issued", message: "Mark's phone has a certificate.", approve_command: null, problem: null }];
}],
["POST", /^\/certs\/devices\/dv_1\/bundle$/, () => [200, { download_url: "https://ui.home.test/api/v1/device-bundles/abc", one_time_password: "ABCD-EFGH-JKLM-NPQR", expires_at: later(600), filename: "domi-device.p12", qr_svg: "<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>" }]],
["POST", /^\/certs\/intermediate\/renewal$/, () => {
m.state.renewal = true;
return [202, { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83" }];
}],
["GET", /^\/settings$/, () => [200, { repo: { name: "ianitor-routes", last_push_at: now() }, watch_seconds: 60 }]],
["GET", /^\/tokens$/, () => [200, { items: [] }]],
["POST", /^\/tokens$/, (_, b) => [201, { id: "tk_1", name: b.name, token: "ian_tk1_secretvalue", expires_at: later(365 * 86400) }]],
["GET", /^\/share-links$/, () => [200, { items: [], epoch: 0 }]],
];
}
export function installMock(): Mock {
const m = newMock();
const routes = mockRoutes(m);
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url;
const path = url.replace(/^.*\/api\/v1/, "");
const method = (init?.method ?? "GET").toUpperCase();
const body = init?.body ? JSON.parse(String(init.body)) : {};
m.calls.push({ method, path, body });
const a = respond(routes, method, path, body);
return new Response(a.text, { status: a.status, headers: { "Content-Type": "application/json" } });
}) as typeof fetch;
return m;
}
+39
View File
@@ -0,0 +1,39 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// jsdom lacks a few browser features the UI uses.
if (typeof HTMLDialogElement !== "undefined") {
const p = HTMLDialogElement.prototype as HTMLDialogElement & Record<string, unknown>;
if (!p.showModal) {
p.showModal = function (this: HTMLDialogElement) {
this.setAttribute("open", "");
};
p.show = function (this: HTMLDialogElement) {
this.setAttribute("open", "");
};
p.close = function (this: HTMLDialogElement) {
this.removeAttribute("open");
};
}
}
const clipboard = { text: "", writeText: async (t: string) => void (clipboard.text = t) };
Object.defineProperty(globalThis.navigator, "clipboard", { value: clipboard, configurable: true });
(globalThis as unknown as { __clipboard: typeof clipboard }).__clipboard = clipboard;
if (!("BroadcastChannel" in globalThis)) {
(globalThis as unknown as { BroadcastChannel: unknown }).BroadcastChannel = class {
onmessage: unknown = null;
postMessage() {}
close() {}
};
}
if (!("randomUUID" in crypto)) {
Object.defineProperty(crypto, "randomUUID", { value: () => Math.random().toString(36).slice(2) });
}
window.open = () => null;
HTMLAnchorElement.prototype.click = function () {};
+19
View File
@@ -0,0 +1,19 @@
{
"extends": "@tsconfig/svelte/tsconfig.json",
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"skipLibCheck": true,
"types": ["vite/client"],
"lib": ["ES2022", "DOM", "DOM.Iterable"]
},
"include": ["src/**/*.ts", "src/**/*.svelte", "tests/**/*.ts", "../../packages/ui/src/**/*.ts", "../../packages/ui/src/**/*.svelte"]
}
+38
View File
@@ -0,0 +1,38 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { defineConfig } from "vitest/config";
// Dev server: 127.0.0.1 only (CLAUDE.md), never --host 0.0.0.0. /api goes to control's --dev on
// 127.0.0.1:7878. In production edge sends Authelia's identity and the per-boot proof; in dev
// there is no Authelia, so the dev proxy (never the browser) adds the dev API token from
// $IANITOR_DEV_TOKEN, which `ianitor-control --dev` prints.
const control = process.env.IANITOR_CONTROL ?? "http://127.0.0.1:7878";
const token = process.env.IANITOR_DEV_TOKEN;
export default defineConfig({
plugins: [svelte()],
server: {
host: "127.0.0.1",
port: 5173,
strictPort: true,
proxy: {
"/api": {
target: control,
changeOrigin: true,
headers: token ? { Authorization: `Bearer ${token}` } : {},
},
},
},
preview: { host: "127.0.0.1" },
build: { outDir: "dist", sourcemap: false, assetsInlineLimit: 0 },
resolve: process.env.VITEST ? { conditions: ["browser"] } : undefined,
test: {
environment: "jsdom",
setupFiles: ["./tests/setup.ts"],
include: ["tests/**/*.test.ts"],
testTimeout: 20000,
},
});
+15 -3
View File
@@ -15,8 +15,17 @@ path = "src/lib.rs"
name = "ianitor-control"
path = "src/main.rs"
[features]
# The crash and write-failure hooks of the crash-safety tests (src/crash.rs). The Nix release
# build turns them off with --no-default-features.
default = ["test-hooks"]
test-hooks = []
[dependencies]
ianitor-core.workspace = true
rustls.workspace = true
rustls-pki-types.workspace = true
tokio-rustls.workspace = true
axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "matched-path"] }
utoipa = "5"
tokio.workspace = true
@@ -29,13 +38,16 @@ ring.workspace = true
base64.workspace = true
http.workspace = true
bytes.workspace = true
# Dev mode only: a throw-away CA for the dev hosts (the Domi CA arrives in phase 3).
rcgen.workspace = true
# Device certificate install files (PKCS#12) and their QR codes.
p12-keystore = "0.4"
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
# The offline root CLI asks for its passphrase without echo.
rpassword = "7"
[dev-dependencies]
ianitor-testkit.workspace = true
p12-keystore = "0.4"
ianitor-edge.workspace = true
rustls.workspace = true
[lints]
workspace = true
+132 -22
View File
@@ -124,11 +124,50 @@ fn replay(st: &AppState, s: Stored) -> Response {
// ---------------------------------------------------------------- overview and hosts
/// What is known to differ on Caddy for these routes (decision Q3: switch allowed, the
/// differences listed). Control cannot run the differential suite at runtime; these are the
/// suite's known differences (tests/diff, KD-*) applied to the hosts that use the feature.
/// Returns (hosts compared, hosts that behave the same, sentences).
pub fn fallback_differences(m: &ianitor_core::Model) -> (u32, u32, Vec<String>) {
let mut out = Vec::new();
let mut matched = 0u32;
for h in m.hosts() {
let before = out.len();
if h.share_links {
out.push(format!(
"{}: share links do not work; visitors with a link get the normal sign-in.",
h.hostname
));
}
if h.auth == ianitor_core::AuthMode::ForwardAuth {
out.push(format!(
"{}: if Authelia's answer is broken or cut off, Pingora refuses the visit; Caddy goes by its status alone.",
h.hostname
));
}
if out.len() == before {
matched += 1;
}
}
if !m.hosts().is_empty() {
out.push(
"Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."
.into(),
);
}
let n = u32::try_from(m.hosts().len()).unwrap_or(u32::MAX);
(n, matched, out)
}
/// Everything the main screen shows, in one call. Answers 304 to a matching If-None-Match.
#[utoipa::path(get, path = "/api/v1/overview", tag = "overview",
responses((status = 200, body = Overview), (status = 304, description = "Unchanged since the ETag"), (status = 401, body = ErrorEnvelope)),
security(("bearer" = [])))]
pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result<Response, ApiError> {
pub async fn overview(
State(st): Shared,
Extension(actor): Extension<Actor>,
headers: HeaderMap,
) -> Result<Response, ApiError> {
let c = &st.ctl;
let (status, error, since) = {
let h = c
@@ -169,6 +208,9 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result<Response,
state: r.state.clone(),
summary: r.summary.clone(),
seconds_left: r.watch.as_ref().map(|w| w.ends.saturating_sub(now())),
kind: r.kind.clone(),
hosts: r.hosts.clone(),
watch_ends_at: r.watch.as_ref().map(|w| rfc3339(w.ends)),
queued: c.queued_count(),
});
let site = tree
@@ -179,40 +221,90 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result<Response,
acme_configured: true,
secrets: m.site().secrets.iter().map(|s| s.to_string()).collect(),
watch_seconds: c.cfg.watch_secs,
share_links_available: c.share_key.is_some(),
share_links_available: c.share_key.is_some() && c.engine_running() != "caddy",
auth_logout_url: c.cfg.ui.as_ref().and_then(|u| u.logout_url.clone()),
});
let es = super::pki::engine_view(c);
let on_caddy = es.running == "caddy";
let caddy_built = std::fs::metadata(&c.cfg.caddy.config)
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| rfc3339(d.as_secs()));
let caddy_current = tree
.as_ref()
.and_then(|t| t.model().ok())
.and_then(|m| ianitor_core::compile::caddy(&m, &c.cfg.caddy_compile().options()).ok())
.is_some_and(|text| {
std::fs::read_to_string(&c.cfg.caddy.config).ok().as_deref() == Some(text.as_str())
});
let ov = Overview {
counts,
hosts,
engine: EngineView {
running: "pingora".into(),
state: if status.is_some() && error.is_none() {
"running"
state: if es.state == "switching" {
"switching".into()
} else if on_caddy || (status.is_some() && error.is_none()) {
"running".into()
} else {
"stopped"
}
.into(),
since: status.as_ref().map(|s| rfc3339(s.started_at)),
fallback_ready: None,
"stopped".into()
},
since: if on_caddy || es.state == "switching" {
Some(es.since.clone())
} else {
status.as_ref().map(|s| rfc3339(s.started_at))
},
running: es.running,
target: es.target,
switchable: es.switchable,
fallback_ready: Some({
let (compared, matched, differences) = tree
.as_ref()
.and_then(|t| t.model().ok())
.map(|m| fallback_differences(&m))
.unwrap_or_default();
FallbackReady {
built_at: caddy_built,
current: caddy_current,
compared,
matched,
differences,
}
}),
last_error: es.last_error,
notes: es.notes,
},
last_apply,
undo: undo_view(c),
active_apply: active,
repo: Some(repo_view(c, &head)),
intermediate: None,
intermediate: super::pki::intermediate_view(c),
site,
paused: c.paused().map(|p| Blocked {
paused_reason: c.effective_pause().map(|p| p.code),
paused_detail: c.effective_pause().and_then(|p| p.detail),
paused: c.effective_pause().map(|p| Blocked {
code: "control.paused".into(),
message: message("control.paused", &messages::params([("reason", p.message)])),
}),
health_error: error.filter(|_| c.edge.attached()).map(|_| Blocked {
code: "health.unavailable".into(),
message: message(
"health.unavailable",
&messages::params([("engine", "Pingora".into())]),
),
}),
// Under Caddy, health is not read (edge is stopped); the chip says Caddy serves.
health_error: error
.filter(|_| c.edge.attached() && !on_caddy)
.map(|_| Blocked {
code: "health.unavailable".into(),
message: message(
"health.unavailable",
&messages::params([("engine", "Pingora".into())]),
),
}),
rev: Some(head),
viewer: Some(Viewer {
via: if actor.token_id.starts_with("user:") {
"authelia".into()
} else {
"token".into()
},
name: actor.name.clone(),
}),
};
let body = serde_json::to_vec(&ov).map_err(|e| ApiError::internal(e.to_string()))?;
let etag = format!("\"{}\"", &sha256_hex(&body)[..32]);
@@ -1038,6 +1130,14 @@ async fn mint_inner(
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
})?;
let c = &st.ctl;
if c.engine_running() == "caddy" {
// G7: Caddy cannot check share links; control does not serve visitors itself.
return Err(ApiError::new(
StatusCode::CONFLICT,
"share.engine_caddy",
Params::new(),
));
}
let (_, _, model) = c.head_model()?;
let Some(host) = model
.hosts()
@@ -1138,6 +1238,9 @@ pub async fn list_share_links(State(st): Shared) -> Result<Response, ApiError> {
.links
.iter()
.rev()
// A device install link carries its one-time token in the path: never listed. It
// expires within minutes, and "Stop all" stops it with the others.
.filter(|l| !l.path_prefix.starts_with("/api/v1/device-bundles/"))
.map(|l| ShareLinkView {
id: l.id.clone(),
hostname: l.hostname.clone(),
@@ -1278,19 +1381,26 @@ impl Modify for Bearer {
overview, list_hosts, get_host, validate_host, create_host, update_host, patch_host, delete_host,
retry_certificate, list_applies, get_apply, cancel_apply, history, history_entry, restore_preview,
get_undo, undo, restore, push_now, settings, list_tokens, create_token, rename_token, revoke_token,
mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi
mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi,
super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request,
super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device,
super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine
),
components(schemas(
HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate,
TokenRename, MintBody, ErrorEnvelope, ErrorBody, ApplyAccepted, ApplyView, ApplyList, Step, WatchHost,
Reason, FieldError, Overview, HostList, HostDetail, History, RestorePreview, UndoView, TokenList,
TokenView, CreatedToken, ShareLinkList, ShareLinkView, MintedLink, StoppedAll, Settings, RepoView,
HealthReport, Done
HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView,
super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody,
super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody,
FallbackReady
)),
modifiers(&Bearer),
tags(
(name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"),
(name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links")
(name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"),
(name = "certs"), (name = "engine")
)
)]
pub struct ApiDoc;
+125 -5
View File
@@ -16,6 +16,8 @@
#![allow(clippy::result_large_err)]
pub mod handlers;
pub mod pki;
pub mod ui;
pub mod views;
use std::collections::HashMap;
@@ -317,7 +319,7 @@ fn body_error(e: &serde_json::Error) -> ApiError {
// ---------------------------------------------------------------- middleware
fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
pub(crate) fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else {
return false;
};
@@ -328,7 +330,14 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
format!("127.0.0.1:{port}"),
format!("[::1]:{port}"),
];
ok.iter().any(|o| o.eq_ignore_ascii_case(host))
// The admin host edge forwards the UI on, with or without edge's HTTPS port.
let ui = ctl.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
let ui_ok = ui.is_some_and(|u| {
let edge_port = ctl.cfg.compile.https_listen.port();
host.eq_ignore_ascii_case(u) || host.eq_ignore_ascii_case(&format!("{u}:{edge_port}"))
});
ui_ok
|| ok.iter().any(|o| o.eq_ignore_ascii_case(host))
|| ctl
.cfg
.allowed_hosts
@@ -336,6 +345,55 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
.any(|a| a.eq_ignore_ascii_case(host))
}
enum UiIdentity {
/// No sign-in headers: an API-token request.
None,
/// `Remote-*` or a proof header without the right proof.
Forged,
/// The right proof but no usable `Remote-User`.
NoUser,
/// The Authelia user name, and the name to show (`Remote-Name` when it is usable).
User(String, String),
}
fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity {
let names_user = headers.keys().any(|k| k.as_str().starts_with("remote-"));
let proof = headers.get("x-ianitor-proof");
if !names_user && proof.is_none() {
return UiIdentity::None;
}
let ok = match (proof, &ctl.ui_proof) {
(Some(p), Some(want)) => crate::util::ct_eq(p.as_bytes(), want),
_ => false,
};
if !ok {
return UiIdentity::Forged;
}
let users: Vec<&HeaderValue> = headers.get_all("remote-user").iter().collect();
match users.as_slice() {
[one] => match one.to_str() {
Ok(u)
if !u.is_empty()
&& u.len() <= 64
&& u.bytes().all(|c| c.is_ascii_graphic() && c != b':') =>
{
let display = headers
.get("remote-name")
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|n| {
!n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control)
})
.unwrap_or(u)
.to_owned();
UiIdentity::User(u.to_owned(), display)
}
_ => UiIdentity::NoUser,
},
_ => UiIdentity::NoUser,
}
}
/// Host check, CSRF check, token, rate limit; logs method, route template, status, time.
async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
let started = Instant::now();
@@ -367,6 +425,46 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
Params::new(),
));
}
// The web UI, through edge on the admin host (docs/api.md, "Sign-in"): only a request
// with the per-boot proof edge adds is identified by its Remote-User. Any other
// request that names a user is refused, so a local process cannot claim to be one.
match ui_identity(&st.ctl, req.headers()) {
UiIdentity::None => {}
UiIdentity::Forged => {
return Err(ApiError::new(
StatusCode::UNAUTHORIZED,
"ui.no_proof",
Params::new(),
));
}
UiIdentity::NoUser => {
return Err(ApiError::new(
StatusCode::UNAUTHORIZED,
"ui.no_user",
Params::new(),
));
}
UiIdentity::User(user, display) => {
// Cookie-based sign-in: every write carries the UI header, browser or not.
if write && !ui {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"request.csrf",
Params::new(),
));
}
st.limit(&format!("user:{user}"), RATE_PER_MINUTE, 60)
.map_err(|s| {
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new())
.retry(s)
})?;
req.extensions_mut().insert(Actor {
token_id: format!("user:{user}"),
name: display,
});
return Ok(next.run(req).await);
}
}
let auth = req
.headers()
.get(header::AUTHORIZATION)
@@ -429,7 +527,7 @@ async fn finish(req: Request, next: Next) -> Response {
let out = match serde_json::from_slice::<serde_json::Value>(&bytes) {
Ok(serde_json::Value::Object(mut m)) => {
m.insert("server_time".into(), rfc3339(now()).into());
if m.contains_key("error") {
if m.get("error").is_some_and(serde_json::Value::is_object) {
m.insert("request_id".into(), request_id.into());
}
serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec())
@@ -503,14 +601,36 @@ pub fn router(st: Arc<AppState>) -> Router {
post(h::stop_all_share_links),
)
.route("/api/v1/share-links/{id}", delete(h::stop_share_link))
.route("/api/v1/certs", get(pki::get_certs))
.route("/api/v1/certs/devices", post(pki::request_device))
.route("/api/v1/certs/devices/{id}", delete(pki::revoke_device))
.route("/api/v1/certs/devices/{id}/bundle", post(pki::make_bundle))
.route("/api/v1/certs/intermediate/renewal", post(pki::renew))
.route(
"/api/v1/pki-requests/{id}",
get(pki::get_request).delete(pki::cancel_request),
)
.route("/api/v1/pki-requests/{id}/csr", get(pki::get_csr))
.route("/api/v1/pki-requests/{id}/ext", get(pki::get_ext))
.route(
"/api/v1/pki-requests/{id}/certificate",
axum::routing::put(pki::put_certificate),
)
.route(
"/api/v1/engine",
get(pki::get_engine).post(pki::switch_engine),
)
.route("/api/v1/health", get(h::health))
.route("/api/v1/openapi.json", get(h::openapi))
.method_not_allowed_fallback(method_not_allowed)
.fallback(not_found)
.layer(middleware::from_fn_with_state(st.clone(), guard))
.layer(DefaultBodyLimit::max(MAX_BODY))
.with_state(st);
api.layer(middleware::from_fn(finish))
.with_state(st.clone());
// In front of the guard: the built UI (static files, no token: they hold no data) and
// the one-time device downloads (the link is the secret). Both still check the Host.
api.layer(middleware::from_fn_with_state(st, ui::front))
.layer(middleware::from_fn(finish))
}
/// The OpenAPI document.
+839
View File
@@ -0,0 +1,839 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Certificates (docs/ui-api.md §1.7, §1.8, §3.6) and the engine switch (§1.9).
// An error answer is built once per failed request; boxing it buys nothing.
#![allow(clippy::result_large_err)]
use std::sync::Arc;
use axum::Extension;
use axum::extract::{Path, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use super::views::Blocked;
use super::{Actor, ApiError, AppState, Body};
use crate::engine::Control;
use crate::messages::{self, Params, message};
use crate::pki::{Device, PkiFail, Request};
use crate::pki_ctl::pki_fail;
use crate::switch::engine_name;
use crate::util::{now, rfc3339};
type Shared = State<Arc<AppState>>;
fn json<T: serde::Serialize>(status: StatusCode, v: &T) -> Response {
(status, axum::Json(v)).into_response()
}
fn plain_id(s: &str) -> bool {
!s.is_empty() && s.len() <= 64 && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
}
fn not_found(code: &str) -> ApiError {
ApiError::new(StatusCode::NOT_FOUND, code, Params::new())
}
/// Run blocking PKI work (key unlock, file writes) off the async threads.
async fn blocking<T: Send + 'static>(
st: &Arc<AppState>,
f: impl FnOnce(&Control) -> Result<T, PkiFail> + Send + 'static,
) -> Result<T, ApiError> {
let c = st.ctl.clone();
if c.pki.is_none() {
return Err(ApiError::new(
StatusCode::CONFLICT,
"pki.not_configured",
Params::new(),
));
}
tokio::task::spawn_blocking(move || f(&c))
.await
.map_err(|e| ApiError::internal(e.to_string()))?
.map_err(|e| ApiError::from(pki_fail(e)))
}
fn pki(c: &Control) -> Result<&crate::pki::Pki, PkiFail> {
c.pki.as_ref().ok_or(PkiFail::Code("pki.not_configured"))
}
// ---------------------------------------------------------------- views
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct PkiRequestView {
pub request_id: String,
/// `device` or `intermediate`.
pub kind: String,
/// `waiting`, `approved`, `denied`, `expired`, `cancelled` or `failed`.
pub state: String,
pub match_code: String,
pub created_at: String,
pub expires_at: String,
pub approved_at: Option<String>,
pub device_id: Option<String>,
pub name: Option<String>,
/// Renewals: the request to sign offline (also `GET /pki-requests/{id}/csr`).
pub csr_pem: Option<String>,
/// Renewals: SHA-256 of the request (DER, lowercase hex), what
/// `openssl req -in X.csr -outform DER | openssl dgst -sha256` prints on the offline computer.
pub csr_sha256: Option<String>,
/// Renewals, once installed: the new intermediate's expiry.
pub not_after: Option<String>,
/// What to tell the user now (`pki.waiting.manual`, `pki.renew.manual`, `pki.denied`, …).
pub message_code: String,
pub message: String,
/// The command that approves it on the server (manual approval).
pub approve_command: Option<String>,
/// Renewals: the base name of the files (`<base>.csr`, `<base>.ext`, `<base>.crt`).
pub file_base: Option<String>,
/// Why it failed, when it did.
pub problem: Option<String>,
}
pub fn request_view(c: &Control, r: &Request) -> PkiRequestView {
let (message_code, message_text) = match r.state.as_str() {
"waiting" => c.waiting_message(&r.kind, &r.match_code),
"approved" if r.kind == "intermediate" => {
let date = r
.not_after
.map(|t| ianitor_core::time::long_date(t.max(0) as u64))
.unwrap_or_default();
(
"pki.renewed".to_owned(),
message("pki.renewed", &messages::params([("date", date)])),
)
}
"approved" => (
"pki.issued".to_owned(),
message(
"pki.issued",
&messages::params([("name", r.name.clone().unwrap_or_default())]),
),
),
"denied" => (
"pki.denied".to_owned(),
message("pki.denied", &Params::new()),
),
"expired" => (
"pki.expired".to_owned(),
message("pki.expired", &Params::new()),
),
"cancelled" => (
"pki.cancelled".to_owned(),
"Cancelled. Nothing was issued.".to_owned(),
),
_ => ("internal".to_owned(), message("internal", &Params::new())),
};
let manual = c.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual");
PkiRequestView {
request_id: r.id.clone(),
kind: r.kind.clone(),
state: r.state.clone(),
match_code: r.match_code.clone(),
created_at: rfc3339(r.created_at),
expires_at: rfc3339(r.expires_at),
approved_at: r.approved_at.map(rfc3339),
device_id: r.device_id.clone(),
name: r.name.clone(),
csr_pem: r.csr_pem.clone(),
csr_sha256: r
.csr_pem
.as_deref()
.and_then(|c| ianitor_core::pki::csr_der(c).ok())
.map(|d| ianitor_core::pki::sha256_hex(&d)),
not_after: r.not_after.map(|t| rfc3339(t.max(0) as u64)),
message_code,
message: message_text,
approve_command: (r.state == "waiting" && manual).then(|| {
if r.kind == "intermediate" {
ianitor_core::pki::openssl_sign_command(&file_base(r))
} else {
format!("ianitor-control pki approve {}", r.match_code)
}
}),
file_base: (r.kind == "intermediate").then(|| file_base(r)),
problem: r.error.clone(),
}
}
/// `domi-intermediate-2026-11-07`, from the day the request was made.
pub fn file_base(r: &Request) -> String {
format!(
"domi-intermediate-{}",
rfc3339(r.created_at).get(..10).unwrap_or("request")
)
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct IntermediateView {
/// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`.
pub state: String,
pub subject: Option<String>,
pub not_after: Option<String>,
pub days_left: Option<i64>,
pub renewal: Option<PkiRequestView>,
/// The banner text for `due`, `urgent`, `expired` and `missing`; `null` when `ok`.
pub banner: Option<Blocked>,
}
pub fn intermediate_view(c: &Control) -> Option<IntermediateView> {
let p = c.pki.as_ref()?;
let s = p.status(now());
let date = s
.not_after
.map(|t| ianitor_core::time::long_date(t.max(0) as u64))
.unwrap_or_default();
let days = s.days_left.unwrap_or(0).to_string();
let banner = match s.state {
"due" => Some("pki.renew_due"),
"urgent" => Some("pki.renew_urgent"),
"expired" => Some("pki.intermediate_expired"),
"missing" => Some("pki.no_intermediate"),
_ => None,
}
.map(|code| Blocked {
code: code.into(),
message: message(
code,
&messages::params([("days", days.clone()), ("date", date.clone())]),
),
});
Some(IntermediateView {
state: s.state.into(),
subject: s.subject,
not_after: s.not_after.map(|t| rfc3339(t.max(0) as u64)),
days_left: s.days_left,
renewal: s.renewal.as_ref().map(|r| request_view(c, r)),
banner,
})
}
#[derive(Debug, Serialize, ToSchema)]
pub struct RootView {
/// The root key is never on this server.
pub offline: bool,
pub subject: String,
pub not_after: String,
pub sha256: String,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct DeviceView {
pub id: String,
pub name: String,
/// `phone`, `computer` or `app`.
pub kind: String,
pub created_at: String,
pub not_after: String,
/// `valid`, `revoked` or `expired`.
pub state: String,
pub revoked_at: Option<String>,
pub serial: String,
}
fn device_view(d: &Device, t: u64) -> DeviceView {
DeviceView {
id: d.id.clone(),
name: d.name.clone(),
kind: d.kind.clone(),
created_at: rfc3339(d.created_at),
not_after: rfc3339(d.not_after.max(0) as u64),
state: d.state(t).into(),
revoked_at: d.revoked_at.map(rfc3339),
serial: d.serial.clone(),
}
}
#[derive(Debug, Serialize, ToSchema)]
pub struct CertsView {
pub intermediate: Option<IntermediateView>,
pub root: RootView,
pub devices: Vec<DeviceView>,
pub device_lifetime_days: u32,
/// When a device certificate issued now would end: a year, but never past the
/// intermediate's end (decision Q7). None without an intermediate.
pub device_valid_until: Option<String>,
pub server_lifetime_days: u32,
/// `manual` (on the server, until Custos can) or `custos`.
pub approval: String,
/// Open device requests.
pub requests: Vec<PkiRequestView>,
/// Set while the device list is not in force (could not be written or handed to the
/// proxy); Ianitor retries every few seconds.
pub devices_problem: Option<Blocked>,
}
// ---------------------------------------------------------------- handlers
/// The certificates screen.
#[utoipa::path(get, path = "/api/v1/certs", tag = "certs",
responses((status = 200, body = CertsView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn get_certs(State(st): Shared) -> Result<Response, ApiError> {
let view = blocking(&st, |c| {
let p = pki(c)?;
let t = now();
let root = ianitor_core::pki::inspect(p.root_pem())?;
let requests = p_requests(c, t)?;
Ok(CertsView {
intermediate: intermediate_view(c),
root: RootView {
offline: true,
subject: root.subject_cn,
not_after: rfc3339(root.not_after.max(0) as u64),
sha256: root.sha256_hex,
},
devices: p
.devices()?
.iter()
.rev()
.map(|d| device_view(d, t))
.collect(),
device_lifetime_days: ianitor_core::pki::DEVICE_DAYS,
device_valid_until: p.intermediate_info().map(|i| {
let end = (t as i64 + i64::from(ianitor_core::pki::DEVICE_DAYS) * 86_400)
.min(i.not_after);
rfc3339(end.max(0) as u64)
}),
server_lifetime_days: ianitor_core::pki::SERVER_DAYS,
approval: c
.cfg
.pki
.as_ref()
.map(|p| p.approval.clone())
.unwrap_or_default(),
requests,
devices_problem: c
.devices_problem
.lock()
.ok()
.and_then(|p| p.clone())
.map(|_| Blocked {
code: "pki.devices_unwritten".into(),
message: message("pki.devices_unwritten", &Params::new()),
}),
})
})
.await?;
Ok(json(StatusCode::OK, &view))
}
fn p_requests(c: &Control, t: u64) -> Result<Vec<PkiRequestView>, PkiFail> {
let path = crate::pki::requests_path(&c.cfg.state_dir);
let rs: Vec<Request> = crate::util::read_json(&path)
.map_err(PkiFail::Internal)?
.unwrap_or_default();
Ok(rs
.iter()
.filter(|r| r.kind == "device" && r.state == "waiting" && r.expires_at > t)
.map(|r| request_view(c, r))
.collect())
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct DeviceRequestBody {
pub name: String,
/// `phone`, `computer` or `app`.
pub kind: String,
}
/// Ask for a device certificate; it is issued once the request is approved with its code.
#[utoipa::path(post, path = "/api/v1/certs/devices", tag = "certs", request_body = DeviceRequestBody,
responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn request_device(
State(st): Shared,
Extension(actor): Extension<Actor>,
body: Body<DeviceRequestBody>,
) -> Result<Response, ApiError> {
st.limit(&format!("pki:{}", actor.token_id), 20, 3600)
.map_err(|s| {
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
})?;
let b = body.value;
let name_for_err = b.name.clone();
let r = blocking(&st, move |c| {
let r = pki(c)?.request_device(&b.name, &b.kind, now(), &actor.name)?;
Ok(request_view(c, &r))
})
.await
.map_err(|mut e| {
if e.body.code == "pki.device_name_taken" || e.body.code == "pki.device_name" {
e.body.field = Some("name".into());
e.body
.params
.insert("name".into(), name_for_err.chars().take(64).collect());
} else if e.body.code == "pki.device_kind" {
e.body.field = Some("kind".into());
}
e
})?;
log::info!(target: "ianitor::pki", "device certificate requested ({})", r.request_id);
Ok(json(StatusCode::ACCEPTED, &r))
}
/// One approval request.
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}", tag = "certs",
responses((status = 200, body = PkiRequestView), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn get_request(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
if !plain_id(&id) {
return Err(not_found("pki.request_not_found"));
}
let v = blocking(&st, move |c| {
let r = pki(c)?
.request(&id, now())?
.ok_or(PkiFail::Code("pki.request_not_found"))?;
Ok(request_view(c, &r))
})
.await?;
Ok(json(StatusCode::OK, &v))
}
/// Cancel a request that waits.
#[utoipa::path(delete, path = "/api/v1/pki-requests/{id}", tag = "certs",
responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn cancel_request(
State(st): Shared,
Path(id): Path<String>,
) -> Result<Response, ApiError> {
if !plain_id(&id) {
return Err(not_found("pki.request_not_found"));
}
blocking(&st, move |c| {
pki(c)?
.cancel(&id)?
.map(|_| ())
.ok_or(PkiFail::Code("pki.request_not_found"))
})
.await?;
Ok(StatusCode::NO_CONTENT.into_response())
}
/// A renewal's CSR, as a file to carry to the offline machine.
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/csr", tag = "certs",
responses((status = 200, description = "PEM PKCS#10"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn get_csr(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
if !plain_id(&id) {
return Err(not_found("pki.request_not_found"));
}
let csr = blocking(&st, move |c| {
pki(c)?
.request(&id, now())?
.and_then(|r| r.csr_pem.clone().map(|c| (c, file_base(&r))))
.ok_or(PkiFail::Code("pki.request_not_found"))
})
.await?;
let (csr, base) = csr;
let mut r = csr.into_response();
r.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/pkcs10"),
);
if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{base}.csr\"")) {
r.headers_mut().insert(header::CONTENT_DISPOSITION, v);
}
Ok(r)
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CertificateBody {
/// The intermediate certificate signed by the Domi root (PEM).
pub certificate_pem: String,
}
/// Install the signed intermediate for an open renewal.
#[utoipa::path(put, path = "/api/v1/pki-requests/{id}/certificate", tag = "certs", request_body = CertificateBody,
responses((status = 200, body = PkiRequestView), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn put_certificate(
State(st): Shared,
Path(id): Path<String>,
body: Body<CertificateBody>,
) -> Result<Response, ApiError> {
if !plain_id(&id) {
return Err(not_found("pki.request_not_found"));
}
let pem = body.value.certificate_pem;
if pem.len() > 16 * 1024 {
return Err(ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"pki.bad_certificate",
Params::new(),
));
}
let v = blocking(&st, move |c| {
let r = pki(c)?.install_intermediate(&id, &pem, now())?;
Ok(request_view(c, &r))
})
.await?;
let c = st.ctl.clone();
tokio::spawn(async move { c.refresh_certificates(true).await });
Ok(json(StatusCode::OK, &v))
}
/// Start the renewal of the intermediate (or set up the first one).
#[utoipa::path(post, path = "/api/v1/certs/intermediate/renewal", tag = "certs",
responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn renew(
State(st): Shared,
Extension(actor): Extension<Actor>,
) -> Result<Response, ApiError> {
let v = blocking(&st, move |c| {
let r = pki(c)?.request_renewal(now(), &actor.name)?;
Ok(request_view(c, &r))
})
.await?;
Ok(json(StatusCode::ACCEPTED, &v))
}
/// Revoke a device: it is off the allow list at once.
#[utoipa::path(delete, path = "/api/v1/certs/devices/{id}", tag = "certs",
responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn revoke_device(
State(st): Shared,
Extension(actor): Extension<Actor>,
Path(id): Path<String>,
) -> Result<Response, ApiError> {
if !plain_id(&id) {
return Err(not_found("pki.device_not_found"));
}
let d = blocking(&st, move |c| {
pki(c)?
.revoke(&id, now())?
.ok_or(PkiFail::Code("pki.device_not_found"))
})
.await?;
log::info!(target: "ianitor::pki", "device {} revoked by {}", d.id, actor.token_id);
// The revocation is recorded; it is in force only once the engines have the new list.
if let Err(e) = st.ctl.devices_changed().await {
let mut err = ApiError::new(
StatusCode::SERVICE_UNAVAILABLE,
"pki.devices_unwritten",
Params::new(),
);
err.body.detail = Some(e);
return Err(err);
}
Ok(StatusCode::NO_CONTENT.into_response())
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct BundleBody {
/// `p12` (a file to download) or `qr` (the same link as a QR code).
#[serde(default = "p12")]
pub format: String,
}
fn p12() -> String {
"p12".into()
}
#[derive(Debug, Serialize, ToSchema)]
pub struct BundleView {
/// Works once, for 10 minutes.
pub download_url: String,
/// Asked for when the file is installed. Shown once.
pub one_time_password: String,
pub expires_at: String,
pub filename: String,
/// `format = "qr"`: the link as an SVG QR code.
pub qr_svg: Option<String>,
}
/// A one-time install file for a device (G15): PKCS#12, behind a link that works once.
#[utoipa::path(post, path = "/api/v1/certs/devices/{id}/bundle", tag = "certs", request_body = BundleBody,
responses((status = 200, body = BundleView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn make_bundle(
State(st): Shared,
Path(id): Path<String>,
body: Body<BundleBody>,
) -> Result<Response, ApiError> {
if !plain_id(&id) {
return Err(not_found("pki.device_not_found"));
}
let format = body.value.format;
if format != "p12" && format != "qr" {
return Err(ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"request.body",
messages::params([("problem", "format must be \"p12\" or \"qr\".".into())]),
));
}
let (token, password, expires) =
blocking(&st, move |c| pki(c)?.make_bundle(&id, now())).await?;
let url = bundle_url(&st, &token).await;
let qr_svg = if format == "qr" {
Some(crate::pki::qr_svg(&url).map_err(|e| ApiError::from(pki_fail(e)))?)
} else {
None
};
Ok(json(
StatusCode::OK,
&BundleView {
download_url: url,
one_time_password: password,
expires_at: rfc3339(expires),
filename: "domi-device.p12".into(),
qr_svg,
},
))
}
/// Where a device downloads its file: through edge on the admin host when there is one
/// (as a share link when that host has share links on, so a device without a sign-in can
/// reach it; the link covers only this one-time path), else control's own address.
async fn bundle_url(st: &AppState, token: &str) -> String {
let c = &st.ctl;
let path = format!("/api/v1/device-bundles/{token}");
let Some(ui) = c.cfg.ui.as_ref().and_then(|u| u.hostname.clone()) else {
return format!("http://{}{path}", c.cfg.listen);
};
let port = c.cfg.compile.https_listen.port();
let authority = if port == 443 {
ui.clone()
} else {
format!("{ui}:{port}")
};
let shares_on = c
.head_model()
.ok()
.and_then(|(_, _, m)| {
m.hosts()
.iter()
.find(|h| h.hostname.as_str() == ui)
.map(|h| h.share_links)
})
.unwrap_or(false);
if shares_on
&& c.engine_running() != "caddy"
&& let Some(key) = &c.share_key
&& let Ok(m) = c.shares.mint(
key,
&ui,
&path,
crate::shares::MIN_EXPIRY,
None,
None,
"device install",
)
{
return format!(
"https://{authority}{}?{}={}",
m.record.path_prefix,
ianitor_core::share::QUERY_PARAM,
m.token
);
}
format!("https://{authority}{path}")
}
/// `GET` on a one-time link: a small page with a Download button that posts back. Link
/// previews and prefetchers only ever GET, so they cannot use up the download.
pub async fn bundle_page(st: Arc<AppState>, token: String) -> Response {
let valid = token.len() == 64 && token.bytes().all(|c| c.is_ascii_hexdigit());
let name = if valid {
let ctl = st.ctl.clone();
tokio::task::spawn_blocking(move || {
ctl.pki.as_ref().and_then(|p| p.peek_bundle(&token, now()))
})
.await
.ok()
.flatten()
} else {
None
};
let (status, body) = match name {
Some(n) => (
StatusCode::OK,
format!(
"<h1>Install the certificate for {}</h1>\
<p>This link works once. After the download, open the file and enter the \
one-time password shown in Ianitor.</p>\
<form method=\"post\"><button type=\"submit\">Download domi-device.p12</button></form>",
html_escape(&n)
),
),
None => (
StatusCode::GONE,
format!(
"<h1>This link has been used</h1><p>{}</p>",
html_escape(&message("pki.bundle_used", &Params::new()))
),
),
};
let page = format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
<meta name=\"robots\" content=\"noindex\"><title>Ianitor: device certificate</title>\
<style>body{{margin:0;padding:24px 16px;background:#0f1115;color:#e6e8ee;\
font:16px/1.5 system-ui,sans-serif}}main{{max-width:32rem;margin:0 auto}}\
h1{{font-size:1.25rem}}button{{font:inherit;padding:10px 16px;border-radius:8px;\
border:0;background:#7aa2ff;color:#0f1115;cursor:pointer}}\
button:focus-visible{{outline:2px solid #e6e8ee;outline-offset:2px}}</style>\
</head><body><main>{body}</main></body></html>"
);
let mut r = (status, page).into_response();
let h = r.headers_mut();
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/html; charset=utf-8"),
);
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
h.insert(
"content-security-policy",
HeaderValue::from_static(
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
),
);
r
}
fn html_escape(s: &str) -> String {
let mut o = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => o.push_str("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
'\'' => o.push_str("&#39;"),
c => o.push(c),
}
}
o
}
/// The one-time download itself (`POST`, from the link's page). The link is the secret: no
/// token or sign-in is needed, and it works once.
#[utoipa::path(post, path = "/api/v1/device-bundles/{token}", tag = "certs",
responses((status = 200, description = "application/x-pkcs12"), (status = 410, body = super::views::ErrorEnvelope)))]
pub async fn download_bundle(
State(st): Shared,
Path(token): Path<String>,
) -> Result<Response, ApiError> {
if token.len() != 64 || !token.bytes().all(|c| c.is_ascii_hexdigit()) {
return Err(ApiError::new(
StatusCode::GONE,
"pki.bundle_used",
Params::new(),
));
}
let (bytes, _name) = blocking(&st, move |c| pki(c)?.take_bundle(&token, now())).await?;
log::info!(target: "ianitor::pki", "a device install file was downloaded");
let mut r = bytes.into_response();
let h = r.headers_mut();
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/x-pkcs12"),
);
h.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_static("attachment; filename=\"domi-device.p12\""),
);
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
Ok(r)
}
// ---------------------------------------------------------------- engine
#[derive(Debug, Serialize, ToSchema)]
pub struct EngineSwitchView {
/// `pingora` or `caddy`.
pub running: String,
/// `running`, `switching` or `stopped`.
pub state: String,
pub target: Option<String>,
pub since: String,
/// Whether this server lets control switch (an `[engine]` section and its units).
pub switchable: bool,
/// Why the last switch did not happen.
pub last_error: Option<crate::records::Reason>,
/// What changes while Caddy serves.
pub notes: Vec<Blocked>,
}
pub fn engine_view(c: &Control) -> EngineSwitchView {
let e = c.engine_state();
let notes = if e.running == "caddy" {
["share.engine_caddy"]
.iter()
.map(|code| Blocked {
code: (*code).into(),
message: message(code, &Params::new()),
})
.collect()
} else {
Vec::new()
};
EngineSwitchView {
running: e.running,
state: e.state,
target: e.target,
since: rfc3339(e.since),
switchable: c.engine_cfg().is_some() && c.units.is_some(),
last_error: e.last_error,
notes,
}
}
/// Which engine serves.
#[utoipa::path(get, path = "/api/v1/engine", tag = "engine",
responses((status = 200, body = EngineSwitchView)), security(("bearer" = [])))]
pub async fn get_engine(State(st): Shared) -> Response {
json(StatusCode::OK, &engine_view(&st.ctl))
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct EngineBody {
/// `pingora` or `caddy`.
pub target: String,
}
/// Switch the engine. Answers at once; poll `GET /engine` until `state` is `running`.
#[utoipa::path(post, path = "/api/v1/engine", tag = "engine", request_body = EngineBody,
responses((status = 202, body = EngineSwitchView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn switch_engine(
State(st): Shared,
Extension(actor): Extension<Actor>,
body: Body<EngineBody>,
) -> Result<Response, ApiError> {
let target = body.value.target;
st.ctl.request_switch(&target).map_err(ApiError::from)?;
log::info!(target: "ianitor::engine", "switch to {} asked by {}", engine_name(&target), actor.token_id);
Ok(json(StatusCode::ACCEPTED, &engine_view(&st.ctl)))
}
/// The openssl extensions file for signing a renewal by hand (the same profile Custos will
/// use; docs/pki.md).
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/ext", tag = "certs",
responses((status = 200, description = "openssl -extfile"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn get_ext(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
if !plain_id(&id) {
return Err(not_found("pki.request_not_found"));
}
let r = blocking(&st, move |c| {
pki(c)?
.request(&id, now())?
.filter(|r| r.kind == "intermediate")
.ok_or(PkiFail::Code("pki.request_not_found"))
})
.await?;
let mut resp = ianitor_core::pki::INTERMEDIATE_OPENSSL_EXT.into_response();
resp.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/plain; charset=utf-8"),
);
if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{}.ext\"", file_base(&r)))
{
resp.headers_mut().insert(header::CONTENT_DISPOSITION, v);
}
Ok(resp)
}
+124
View File
@@ -0,0 +1,124 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! In front of the API guard: the built web UI (`[ui] static_dir`) and the one-time device
//! downloads. The UI's files hold no data (it reads everything from the API, which the guard
//! protects), so they need no token; the Host check still applies against DNS rebinding.
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use axum::body::Body as AxumBody;
use axum::extract::{Path as AxPath, Request, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use super::{ApiError, AppState, host_allowed};
use crate::messages::Params;
const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; \
script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
pub async fn front(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Response {
let path = req.uri().path().to_owned();
if let Some(token) = path.strip_prefix("/api/v1/device-bundles/") {
if !host_allowed(&st.ctl, req.headers()) {
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new())
.into_response();
}
let token = token.to_owned();
// GET shows the page; only its button (POST) uses the link up.
return match req.method().as_str() {
"GET" | "HEAD" => super::pki::bundle_page(st, token).await,
"POST" => super::pki::download_bundle(State(st), AxPath(token))
.await
.unwrap_or_else(IntoResponse::into_response),
_ => ApiError::new(
StatusCode::METHOD_NOT_ALLOWED,
"request.method",
Params::new(),
)
.into_response(),
};
}
if path.starts_with("/api/") || path == "/api" {
return next.run(req).await;
}
if !host_allowed(&st.ctl, req.headers()) {
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()).into_response();
}
let Some(dir) = st.ctl.cfg.ui.as_ref().and_then(|u| u.static_dir.clone()) else {
return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
.into_response();
};
if !matches!(req.method().as_str(), "GET" | "HEAD") {
return ApiError::new(
StatusCode::METHOD_NOT_ALLOWED,
"request.method",
Params::new(),
)
.into_response();
}
serve_static(&dir, &path).await
}
/// A file from the UI build. Paths with `..`, odd characters or hidden names are refused;
/// a path without a file extension is the single-page app (`index.html`).
async fn serve_static(dir: &Path, url_path: &str) -> Response {
let rel = url_path.trim_start_matches('/');
let clean = !rel.contains('\\')
&& rel
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c))
&& Path::new(rel)
.components()
.all(|c| matches!(c, Component::Normal(n) if !n.to_string_lossy().starts_with('.')));
if !clean {
return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
.into_response();
}
let has_ext = Path::new(rel).extension().is_some();
let file: PathBuf = if rel.is_empty() || !has_ext {
dir.join("index.html")
} else {
dir.join(rel)
};
let Ok(bytes) = tokio::fs::read(&file).await else {
return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
.into_response();
};
let ctype = match file.extension().and_then(|e| e.to_str()).unwrap_or("") {
"html" => "text/html; charset=utf-8",
"js" | "mjs" => "text/javascript; charset=utf-8",
"css" => "text/css; charset=utf-8",
"svg" => "image/svg+xml",
"png" => "image/png",
"ico" => "image/x-icon",
"woff2" => "font/woff2",
"json" | "webmanifest" => "application/json",
"txt" => "text/plain; charset=utf-8",
_ => "application/octet-stream",
};
let immutable = rel.starts_with("assets/") || rel.starts_with("_app/immutable/");
let mut r = Response::new(AxumBody::from(bytes));
let h = r.headers_mut();
h.insert(header::CONTENT_TYPE, HeaderValue::from_static(ctype));
h.insert(
header::CACHE_CONTROL,
HeaderValue::from_static(if immutable {
"public, max-age=31536000, immutable"
} else {
"no-cache"
}),
);
h.insert("content-security-policy", HeaderValue::from_static(CSP));
h.insert(
"x-content-type-options",
HeaderValue::from_static("nosniff"),
);
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
h.insert("x-frame-options", HeaderValue::from_static("DENY"));
r
}
+52 -8
View File
@@ -406,6 +406,8 @@ pub struct HostRow {
pub auth: String,
pub websockets: bool,
pub share_links: bool,
/// Visitors need a Domi device certificate.
pub device_certs: bool,
pub added_at: Option<String>,
pub health: HealthView,
pub certificate: CertView,
@@ -439,13 +441,34 @@ pub struct Counts {
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct EngineView {
/// `pingora` (the Caddy switch waits on Mark, ROADMAP §10 (b)).
/// `pingora` or `caddy`.
pub running: String,
/// `running` or `stopped` (control cannot reach it).
/// `running`, `switching` or `stopped` (control cannot reach it).
pub state: String,
pub since: Option<String>,
#[schema(value_type = Option<Object>)]
pub fallback_ready: Option<serde_json::Value>,
/// The engine a running switch goes to.
pub target: Option<String>,
/// Whether control can switch on this server (`[engine]` in control.toml).
pub switchable: bool,
/// The fallback's config: when it was written and whether it is the current tree's.
pub fallback_ready: Option<FallbackReady>,
/// Why the last switch did not happen.
pub last_error: Option<Reason>,
/// What is different while Caddy serves (`engine.caddy`, `share.engine_caddy`).
pub notes: Vec<Blocked>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct FallbackReady {
pub built_at: Option<String>,
/// caddy.json is the compiled current tree.
pub current: bool,
/// Hosts in the current routes, and how many of them behave the same on Caddy as far as
/// Ianitor knows (the differential tests' known differences, applied to these hosts).
pub compared: u32,
pub matched: u32,
/// What is different on Caddy, in plain English (per host first, then for every host).
pub differences: Vec<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
@@ -477,6 +500,11 @@ pub struct ActiveApply {
pub state: String,
pub summary: String,
pub seconds_left: Option<u64>,
/// `add`, `edit`, `remove`, `undo`, `restore`, `share_links`: the UI writes the heading.
pub kind: String,
pub hosts: Vec<String>,
/// When the health watch ends (only while watching), for a local countdown.
pub watch_ends_at: Option<String>,
pub queued: usize,
}
@@ -496,6 +524,8 @@ pub struct SiteView {
pub secrets: Vec<String>,
pub watch_seconds: u64,
pub share_links_available: bool,
/// Authelia's logout address, for "Sign out" (`[ui] logout_url`); `null` hides the link.
pub auth_logout_url: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
@@ -507,14 +537,27 @@ pub struct Overview {
pub undo: UndoView,
pub active_apply: Option<ActiveApply>,
pub repo: Option<RepoView>,
/// The Domi intermediate; arrives in phase 3.
#[schema(value_type = Option<Object>)]
pub intermediate: Option<serde_json::Value>,
/// The Domi intermediate; `null` when the Domi CA is not set up (`[pki]`).
pub intermediate: Option<super::pki::IntermediateView>,
pub site: Option<SiteView>,
pub paused: Option<Blocked>,
/// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`,
/// `repo.unreadable`, …), so the UI can offer the right action.
pub paused_reason: Option<String>,
/// The technical detail behind the pause, for "Show details" (never a secret).
pub paused_detail: Option<String>,
/// Set when control cannot read health from edge (`health.unavailable`).
pub health_error: Option<Blocked>,
pub rev: Option<String>,
/// Who is looking: the Authelia user (through edge) or the API token's name.
pub viewer: Option<Viewer>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Viewer {
pub name: String,
/// `authelia` or `token`.
pub via: String,
}
pub fn added_at(c: &Control, hostname: &str) -> Option<String> {
@@ -526,7 +569,7 @@ pub fn added_at(c: &Control, hostname: &str) -> Option<String> {
}
pub fn undo_view(c: &Control) -> UndoView {
let blocked = if let Some(p) = c.paused() {
let blocked = if let Some(p) = c.effective_pause() {
Some(Blocked {
code: "undo.paused".into(),
message: message("undo.paused", &messages::Params::new()) + " " + &p.message,
@@ -621,6 +664,7 @@ pub fn host_rows(
auth: spec.as_ref().map(|s| s.auth.clone()).unwrap_or_default(),
websockets: spec.as_ref().is_none_or(|s| s.websockets),
share_links: spec.as_ref().is_some_and(|s| s.share_links),
device_certs: spec.as_ref().is_some_and(|s| s.device_certs),
added_at: added_at(c, &h),
health: health_view(st, spec.as_ref(), since.get(&h).copied()),
certificate: cert_view(st, spec.as_ref()),
+269
View File
@@ -0,0 +1,269 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The deadline of a trial under Caddy (QC round 2, B2; the Phase 2 guarantee that an
//! unconfirmed change never outlives control). Edge drops a trial by itself when control does
//! not confirm it in time; Caddy has no such clock, so two things outside control's own process
//! stand in for it:
//!
//! - `ianitor-control caddy-revert` (systemd `ExecStopPost=` of ianitor-control, so it runs
//! after every stop, a crash included): with a trial out, Caddy goes back to caddy.json (the
//! last good config) at once;
//! - `ianitor-control caddy-guard` (its own unit next to caddy-fallback, so a hung control is
//! covered too): once a second, it reverts a trial whose deadline has passed.
//!
//! Control *arms* the deadline (`caddy-trial.json` in its state dir) before it loads a trial,
//! and *claims* it (an atomic rename) right after its journal says `confirmed`; the guard
//! takes it with the same kind of rename (to `.reverting`, then `.expired` once Caddy is
//! verified on caddy.json; given back if the load fails, so it is tried again). A crash between
//! `confirmed` and the claim leaves both: the guard and caddy-revert see `confirmed` and leave
//! the trial to recovery, which promotes it. Whoever renames first wins, so a trial is either confirmed by control or
//! reverted by the guard, never both. caddy.json itself is only ever written with a confirmed
//! config, so loading it is always safe.
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::config::Config;
use crate::records::Journal;
use crate::util::{read_json, write_json};
pub const DEADLINE_FILE: &str = "caddy-trial.json";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TrialDeadline {
pub apply_id: String,
/// Unix seconds.
pub deadline: u64,
}
fn path(state_dir: &Path, suffix: &str) -> PathBuf {
state_dir.join(format!("{DEADLINE_FILE}{suffix}"))
}
/// Before a trial goes into Caddy.
pub fn arm(state_dir: &Path, apply_id: &str, deadline: u64) -> Result<(), String> {
write_json(
&path(state_dir, ""),
&TrialDeadline {
apply_id: apply_id.to_owned(),
deadline,
},
)
}
/// Control, before it confirms: `true` if it got the deadline first (the guard has not
/// reverted the trial), `false` if the guard did.
pub fn claim(state_dir: &Path) -> bool {
let claimed = path(state_dir, ".claimed");
if std::fs::rename(path(state_dir, ""), &claimed).is_err() {
return false;
}
let _ = std::fs::remove_file(claimed);
true
}
/// After a trial is reverted (or at start): nothing is out any more.
pub fn disarm(state_dir: &Path) {
for s in ["", ".claimed", ".expired", ".reverting"] {
let _ = std::fs::remove_file(path(state_dir, s));
}
}
pub fn armed(state_dir: &Path) -> Option<TrialDeadline> {
read_json(&path(state_dir, "")).ok().flatten()
}
/// Whether control's journal says the change is confirmed (then it is being promoted and
/// caddy.json will hold it; nothing to revert).
fn confirmed(state_dir: &Path) -> bool {
read_json::<Journal>(&state_dir.join("journal.json"))
.ok()
.flatten()
.is_some_and(|j| j.stage == "confirmed" || j.stage == "promoted")
}
/// What to do now, for a deadline file as found (pure, for the tests).
#[derive(Debug, PartialEq, Eq)]
pub enum Verdict {
Nothing,
Revert,
}
pub fn verdict(armed: Option<&TrialDeadline>, confirmed: bool, now: u64, at_stop: bool) -> Verdict {
match armed {
Some(d) if !confirmed && (at_stop || now > d.deadline) => Verdict::Revert,
_ => Verdict::Nothing,
}
}
/// Whether Caddy is the engine that serves (the engine file; Pingora without `[engine]`).
fn caddy_serves(cfg: &Config) -> bool {
cfg.engine
.as_ref()
.is_some_and(|e| crate::switch::read_engine_file(&e.file) == "caddy")
}
/// A revert that stopped half way (the guard died while loading) counts as armed again.
fn resume_half_done(dir: &Path) {
let reverting = path(dir, ".reverting");
if reverting.exists() && !path(dir, "").exists() {
let _ = std::fs::rename(reverting, path(dir, ""));
}
}
/// Take the deadline away from control (rename to `.reverting`), load the last good
/// caddy.json and check that Caddy runs it; only then is the deadline marked expired. If the
/// load fails, the deadline is given back, so the next try (or control's own claim, while
/// Caddy still runs the trial) decides.
async fn revert(cfg: &Config, why: &str) -> Result<bool, String> {
let dir = &cfg.state_dir;
let reverting = path(dir, ".reverting");
if std::fs::rename(path(dir, ""), &reverting).is_err() {
// Control claimed it a moment ago: it confirms; nothing to do.
return Ok(false);
}
let loaded = async {
let sock = cfg
.caddy_compile()
.caddy_admin_socket
.clone()
.ok_or("no caddy_admin_socket is configured")?;
let text = std::fs::read(&cfg.caddy.config)
.map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?;
crate::caddy_link::load(Path::new(&sock), &text).await?;
if !crate::caddy_link::runs(Path::new(&sock), &text).await? {
return Err("Caddy took caddy.json but does not run it".to_owned());
}
Ok::<_, String>(())
}
.await;
match loaded {
Ok(()) => {
let _ = std::fs::rename(&reverting, path(dir, ".expired"));
log::warn!(target: "ianitor::caddy-guard", "{why}: Caddy is back on the last good config");
Ok(true)
}
Err(e) => {
let _ = std::fs::rename(&reverting, path(dir, ""));
Err(format!("{why}, but Caddy could not be put back yet: {e}"))
}
}
}
/// `ianitor-control caddy-revert`: after control stops, a trial still out goes back at once
/// (retried a few times, 1, 2, 4 and 8 s apart). With another engine serving there is no
/// Caddy trial: a deadline left behind is cleared and nothing fails.
pub async fn revert_after_stop(cfg: &Config) -> Result<bool, String> {
let dir = &cfg.state_dir;
if !caddy_serves(cfg) {
disarm(dir);
return Ok(false);
}
resume_half_done(dir);
let mut wait = 1;
loop {
let r = match verdict(
armed(dir).as_ref(),
confirmed(dir),
crate::util::now(),
true,
) {
Verdict::Revert => revert(cfg, "control stopped with a trial loaded into Caddy").await,
Verdict::Nothing => Ok(false),
};
match r {
Err(e) if wait <= 8 => {
log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {wait} s");
tokio::time::sleep(std::time::Duration::from_secs(wait)).await;
wait *= 2;
}
other => return other,
}
}
}
/// One tick of `ianitor-control caddy-guard`.
pub async fn tick(cfg: &Config) -> Result<bool, String> {
let dir = &cfg.state_dir;
if !caddy_serves(cfg) {
return Ok(false);
}
resume_half_done(dir);
match verdict(
armed(dir).as_ref(),
confirmed(dir),
crate::util::now(),
false,
) {
Verdict::Revert => revert(cfg, "a trial under Caddy passed its deadline unconfirmed").await,
Verdict::Nothing => Ok(false),
}
}
/// `ianitor-control caddy-guard`: forever, once a second; after a failed revert it tries
/// again with a growing pause (2, 4, … 30 s).
pub async fn run(cfg: Config) -> Result<(), String> {
log::info!(target: "ianitor::caddy-guard", "watching {} for trials under Caddy", cfg.state_dir.display());
let mut pause = 1u64;
loop {
match tick(&cfg).await {
Ok(_) => pause = 1,
Err(e) => {
pause = (pause * 2).min(30);
log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {pause} s");
}
}
tokio::time::sleep(std::time::Duration::from_secs(pause)).await;
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
fn d(deadline: u64) -> TrialDeadline {
TrialDeadline {
apply_id: "ch_1".into(),
deadline,
}
}
#[test]
fn the_guard_reverts_only_an_unconfirmed_trial_past_its_deadline() {
assert_eq!(verdict(None, false, 100, false), Verdict::Nothing);
assert_eq!(verdict(Some(&d(100)), false, 100, false), Verdict::Nothing);
assert_eq!(verdict(Some(&d(100)), false, 101, false), Verdict::Revert);
assert_eq!(verdict(Some(&d(100)), true, 500, false), Verdict::Nothing);
}
#[test]
fn after_a_stop_an_unconfirmed_trial_goes_back_at_once() {
assert_eq!(verdict(Some(&d(1000)), false, 1, true), Verdict::Revert);
assert_eq!(verdict(Some(&d(1000)), true, 1, true), Verdict::Nothing);
assert_eq!(verdict(None, false, 1, true), Verdict::Nothing);
}
#[test]
fn control_and_the_guard_cannot_both_have_the_deadline() {
let dir = std::env::temp_dir().join(format!("ianitor-guard-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
arm(&dir, "ch_1", 10).unwrap();
assert_eq!(armed(&dir), Some(d(10)));
// The guard took it (as `revert` does): control's claim fails.
std::fs::rename(path(&dir, ""), path(&dir, ".expired")).unwrap();
assert!(!claim(&dir));
disarm(&dir);
// Control claims first: nothing is left for the guard.
arm(&dir, "ch_1", 10).unwrap();
assert!(claim(&dir));
assert!(armed(&dir).is_none());
assert!(std::fs::rename(path(&dir, ""), path(&dir, ".expired")).is_err());
disarm(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
}
+366
View File
@@ -0,0 +1,366 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep
//! working under Caddy): loading a config through Caddy's admin API on its Unix socket
//! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host
//! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch,
//! judged like edge's), and the certificate Caddy serves.
use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
const TIMEOUT: Duration = Duration::from_secs(10);
/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked).
async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec<u8>), String> {
#[cfg(unix)]
{
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let exchange = async {
let mut s = tokio::net::UnixStream::connect(socket).await?;
s.write_all(request).await?;
let mut buf = Vec::new();
s.read_to_end(&mut buf).await?;
Ok::<_, std::io::Error>(buf)
};
let buf = tokio::time::timeout(TIMEOUT, exchange)
.await
.map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())?
.map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?;
let split = buf
.windows(4)
.position(|w| w == b"\r\n\r\n")
.ok_or("no answer from Caddy's admin API")?;
let head = String::from_utf8_lossy(&buf[..split]);
let status: u16 = head
.split(' ')
.nth(1)
.and_then(|s| s.parse().ok())
.ok_or("no answer from Caddy's admin API")?;
Ok((status, buf[split + 4..].to_vec()))
}
#[cfg(not(unix))]
{
let _ = (socket, request);
Err("Caddy's admin socket needs Unix".into())
}
}
/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the
/// old one). `Cache-Control: must-revalidate` makes Caddy load it even when it is the same as
/// the running one, so certificate and device files are read again (without it an identical
/// config is a no-op: QC round 2, B1; `qc_reloading_the_same_caddy_json_rereads_the_certificate_files`).
pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
let mut req = format!(
"POST /load HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n",
config.len()
)
.into_bytes();
req.extend_from_slice(config);
let (status, body) = admin(socket, &req).await?;
if (200..300).contains(&status) {
Ok(())
} else {
Err(format!(
"Caddy refused the config ({status}): {}",
String::from_utf8_lossy(&body)
.trim()
.chars()
.take(400)
.collect::<String>()
))
}
}
/// The config Caddy runs now.
pub async fn running_config(socket: &Path) -> Result<serde_json::Value, String> {
let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?;
if status != 200 {
return Err(format!(
"Caddy's admin API answered {status} to GET /config/"
));
}
serde_json::from_slice(&body).map_err(|e| format!("Caddy's running config is not JSON: {e}"))
}
/// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter).
pub async fn runs(socket: &Path, config: &[u8]) -> Result<bool, String> {
let want: serde_json::Value =
serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?;
Ok(running_config(socket).await? == want)
}
/// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Probe {
/// The status Caddy answered with (its own 502/503 when the upstream is down).
Status(u16),
/// No answer at all (connection, TLS or timeout).
NoAnswer(String),
}
/// The probe does not check Caddy's certificate: it talks to this machine's own listener
/// on loopback to see whether the *upstream* answers through it, nothing else.
#[derive(Debug)]
struct AnyCert;
impl rustls::client::danger::ServerCertVerifier for AnyCert {
fn verify_server_cert(
&self,
_end_entity: &rustls_pki_types::CertificateDer<'_>,
_intermediates: &[rustls_pki_types::CertificateDer<'_>],
_server_name: &rustls_pki_types::ServerName<'_>,
_ocsp: &[u8],
_now: rustls_pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
rustls::crypto::ring::default_provider()
.signature_verification_algorithms
.supported_schemes()
}
}
pub async fn probe(addr: SocketAddr, host: &str, path: &str) -> Probe {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let started = Instant::now();
let run = async {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let cfg = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.dangerous()
.with_custom_certificate_verifier(Arc::new(AnyCert))
.with_no_client_auth();
let name =
rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?;
let tcp = tokio::net::TcpStream::connect(addr)
.await
.map_err(|e| e.to_string())?;
let mut tls = tokio_rustls::TlsConnector::from(Arc::new(cfg))
.connect(name, tcp)
.await
.map_err(|e| e.to_string())?;
let req = format!(
"GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: ianitor-watch\r\nConnection: close\r\n\r\n"
);
tls.write_all(req.as_bytes())
.await
.map_err(|e| e.to_string())?;
let mut head = [0u8; 64];
let mut n = 0;
while n < 13 {
let k = tls.read(&mut head[n..]).await.map_err(|e| e.to_string())?;
if k == 0 {
break;
}
n += k;
}
let line = String::from_utf8_lossy(&head[..n]);
line.split(' ')
.nth(1)
.and_then(|s| s.parse::<u16>().ok())
.ok_or_else(|| "no HTTP status".to_owned())
};
match tokio::time::timeout(Duration::from_secs(5), run).await {
Ok(Ok(s)) => Probe::Status(s),
Ok(Err(e)) => Probe::NoAnswer(e),
Err(_) => Probe::NoAnswer(format!(
"no answer within {} s",
started.elapsed().as_secs()
)),
}
}
/// SHA-256 (hex) of the leaf certificate Caddy serves for this name: after a reload, whether
/// Caddy really read the certificate files again (the backstop for B1).
pub async fn served_cert_sha256(addr: SocketAddr, host: &str) -> Result<String, String> {
let run = async {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let cfg = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.dangerous()
.with_custom_certificate_verifier(Arc::new(AnyCert))
.with_no_client_auth();
let name =
rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?;
let tcp = tokio::net::TcpStream::connect(addr)
.await
.map_err(|e| e.to_string())?;
let tls = tokio_rustls::TlsConnector::from(Arc::new(cfg))
.connect(name, tcp)
.await
.map_err(|e| e.to_string())?;
let (_, conn) = tls.get_ref();
let leaf = conn
.peer_certificates()
.and_then(|c| c.first())
.ok_or("Caddy sent no certificate")?;
Ok::<_, String>(crate::util::sha256_hex(leaf.as_ref()))
};
tokio::time::timeout(Duration::from_secs(5), run)
.await
.map_err(|_| "Caddy did not finish the handshake within 5 s".to_owned())?
}
/// One health probe of an upstream, made by control while Caddy serves, with edge's rules
/// (crates/edge/src/health.rs): a host with a health check gets `GET <path>` with the upstream
/// address as Host and passes on 2xx; a host without one gets `GET /` with its own name as
/// Host and passes on any answer below 500. 5 s timeout. `kind` uses edge's words.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpstreamProbe {
pub ok: bool,
pub kind: Option<&'static str>,
pub status: Option<u16>,
pub latency_ms: Option<u64>,
}
fn status_kind(status: u16) -> &'static str {
match status {
300..=399 => "redirect",
401 | 403 => "sign_in",
404 => "not_found",
500..=599 => "server_error",
_ => "bad_answer",
}
}
fn io_kind(e: &std::io::Error) -> &'static str {
use std::io::ErrorKind as K;
match e.kind() {
K::ConnectionRefused | K::ConnectionReset | K::ConnectionAborted | K::BrokenPipe => {
"refused"
}
K::TimedOut => "timeout",
_ if e.to_string().contains("lookup") => "name",
_ => "refused",
}
}
/// The roots an `https://` upstream is checked against: the system bundle (`SSL_CERT_FILE`,
/// else the usual Debian/NixOS path), read once.
fn system_roots() -> Arc<rustls::RootCertStore> {
static ROOTS: std::sync::OnceLock<Arc<rustls::RootCertStore>> = std::sync::OnceLock::new();
ROOTS
.get_or_init(|| {
let mut store = rustls::RootCertStore::empty();
let path = std::env::var("SSL_CERT_FILE")
.unwrap_or_else(|_| "/etc/ssl/certs/ca-certificates.crt".into());
if let Ok(pem) = std::fs::read_to_string(path) {
for der in ianitor_core::pki::chain_der(&pem).unwrap_or_default() {
let _ = store.add(rustls_pki_types::CertificateDer::from(der));
}
}
Arc::new(store)
})
.clone()
}
pub async fn probe_upstream(
u: &ianitor_core::Upstream,
path: &str,
host_header: &str,
watch_only: bool,
) -> UpstreamProbe {
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
let started = Instant::now();
let fail = |kind: &'static str| UpstreamProbe {
ok: false,
kind: Some(kind),
status: None,
latency_ms: None,
};
async fn ask<S: AsyncRead + AsyncWrite + Unpin>(
mut s: S,
req: &[u8],
) -> Result<Option<u16>, std::io::Error> {
s.write_all(req).await?;
let mut head = [0u8; 64];
let mut n = 0;
while n < 13 {
let k = s.read(&mut head[n..]).await?;
if k == 0 {
break;
}
n += k;
}
Ok(String::from_utf8_lossy(&head[..n])
.split(' ')
.nth(1)
.and_then(|x| x.parse::<u16>().ok()))
}
let req = format!(
"GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n"
);
let run = async {
let tcp = match tokio::net::TcpStream::connect(u.authority()).await {
Ok(t) => t,
Err(e) => return Err(io_kind(&e)),
};
if u.scheme == ianitor_core::Scheme::Https {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let Ok(b) = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
else {
return Err("tls");
};
let cfg = b
.with_root_certificates(system_roots())
.with_no_client_auth();
let Ok(name) = rustls_pki_types::ServerName::try_from(u.host_str()) else {
return Err("name");
};
let tls = match tokio_rustls::TlsConnector::from(Arc::new(cfg))
.connect(name, tcp)
.await
{
Ok(t) => t,
Err(_) => return Err("tls"),
};
ask(tls, req.as_bytes()).await.map_err(|e| io_kind(&e))
} else {
ask(tcp, req.as_bytes()).await.map_err(|e| io_kind(&e))
}
};
match tokio::time::timeout(Duration::from_secs(5), run).await {
Err(_) => fail("timeout"),
Ok(Err(kind)) => fail(kind),
Ok(Ok(None)) => fail("bad_answer"),
Ok(Ok(Some(status))) => {
let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
let ok = if watch_only {
(100..500).contains(&status)
} else {
(200..300).contains(&status)
};
UpstreamProbe {
ok,
kind: (!ok).then(|| status_kind(status)),
status: Some(status),
latency_ms: Some(latency),
}
}
}
}
+103
View File
@@ -48,6 +48,16 @@ pub struct Config {
pub compile: Compile,
/// Different facts for the Caddy output (only tests need this: both engines side by side).
pub compile_caddy: Option<Compile>,
/// The Domi CA; without it `tls = "domi"` certificates are expected in `cert_dir` already
/// and the certificate screens say the CA is not set up.
#[serde(default)]
pub pki: Option<PkiConfig>,
/// The web UI behind edge (sign-in through Authelia, see docs/api.md).
#[serde(default)]
pub ui: Option<UiConfig>,
/// Switching between Pingora and the Caddy fallback at runtime.
#[serde(default)]
pub engine: Option<EngineConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -100,6 +110,12 @@ pub struct Compile {
pub access_log: String,
pub caddy_credentials_dir: String,
pub caddy_admin: Option<SocketAddr>,
/// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves.
#[serde(default)]
pub caddy_admin_socket: Option<String>,
/// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy).
#[serde(default)]
pub trusted_proxies: Vec<std::net::IpAddr>,
}
impl Compile {
@@ -112,6 +128,8 @@ impl Compile {
access_log: self.access_log.clone(),
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
caddy_admin: self.caddy_admin,
caddy_admin_socket: self.caddy_admin_socket.clone(),
trusted_proxies: self.trusted_proxies.clone(),
}
}
}
@@ -213,6 +231,15 @@ impl Config {
"routes.push_credential must be a plain credential name".into(),
));
}
// The keys at rest are only as strong as this; only test builds may lower it.
if let Some(p) = &self.pki
&& p.kdf_iterations < MIN_KDF_ITERATIONS
&& !cfg!(feature = "test-hooks")
{
return Err(ConfigError::Invalid(format!(
"pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}"
)));
}
if let Some(m) = empty_model() {
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
ianitor_core::compile::edge(&m, &c.options())
@@ -280,3 +307,79 @@ fn empty_model() -> Option<ianitor_core::Model> {
)
.ok()
}
/// The PBKDF2 floor for keys at rest (OWASP 2023 for PBKDF2-HMAC-SHA256).
pub const MIN_KDF_ITERATIONS: u32 = 600_000;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PkiConfig {
/// The Domi root certificate (public; may be a Nix store path). The root key is never on
/// the server.
pub root_cert: PathBuf,
/// Credential with the password that encrypts the intermediate and device keys at rest.
#[serde(default = "default_pki_password")]
pub password_credential: String,
/// How requests are approved: `manual` (`ianitor-control pki approve <code>` on the
/// server) until Custos can (docs/custos-ticket.md).
#[serde(default = "default_approval")]
pub approval: String,
/// PBKDF2 iterations for the keys control encrypts (only tests lower it).
#[serde(default = "default_kdf")]
pub kdf_iterations: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UiConfig {
/// The admin host edge serves the UI on (a host in the routes repository with
/// `auth = "forward-auth"`, upstream this API, and the proof header rule). Added to
/// `allowed_hosts`; used for device install links.
pub hostname: Option<String>,
/// Credential holding the per-boot secret edge adds as `X-Ianitor-Proof` on the admin
/// host. With it, a request carrying the proof is identified by its `Remote-User`.
pub proof_credential: Option<String>,
/// The built web UI (served at `/`).
pub static_dir: Option<PathBuf>,
/// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out".
#[serde(default)]
pub logout_url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EngineConfig {
/// Which engine runs at boot: `pingora` or `caddy` (read by the engine-select unit).
pub file: PathBuf,
/// `systemctl` (through the polkit rule for exactly the two units) or `none`.
#[serde(default = "default_units")]
pub units: String,
#[serde(default = "default_systemctl")]
pub systemctl: PathBuf,
#[serde(default = "default_edge_unit")]
pub edge_unit: String,
#[serde(default = "default_caddy_unit")]
pub caddy_unit: String,
}
fn default_pki_password() -> String {
"pki-password".into()
}
fn default_approval() -> String {
"manual".into()
}
fn default_kdf() -> u32 {
ianitor_core::pki::KEY_KDF_ITERATIONS
}
fn default_units() -> String {
"systemctl".into()
}
fn default_systemctl() -> PathBuf {
PathBuf::from("systemctl")
}
fn default_edge_unit() -> String {
"ianitor-edge.service".into()
}
fn default_caddy_unit() -> String {
"caddy-fallback.service".into()
}
+25 -4
View File
@@ -3,11 +3,17 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Crash points for the crash-safety tests: with `IANITOR_TEST_CRASH_AT=<stage>` in its
//! environment, control aborts (no cleanup, like a kill -9) when an apply reaches that stage.
//! Without the variable this does nothing; the NixOS unit never sets it.
//! environment, control exits at once with status 134 (no cleanup in Ianitor's code, like a
//! kill -9) when an apply reaches that stage. It does not raise SIGABRT: a signal would make
//! the kernel log a register dump per crash test and could hand the process to the host's
//! core-dump handler, and the tests must not reach into the host's systemd.
//!
//! `IANITOR_TEST_FAIL_WRITE=<file name>` makes every write of a state file with that name
//! fail, as on a full disk (fault injection for the same tests).
//!
//! Both exist only with the `test-hooks` cargo feature (on by default, so `cargo test` has
//! them). The release build (`nix build .#ianitor`) is built with `--no-default-features`:
//! there these functions do nothing and read no environment variable.
/// The stages, in order.
pub const STAGES: [&str; 9] = [
@@ -22,14 +28,23 @@ pub const STAGES: [&str; 9] = [
"reverting",
];
/// Whether this binary has the test hooks.
pub const ENABLED: bool = cfg!(feature = "test-hooks");
#[cfg(feature = "test-hooks")]
pub fn point(stage: &str) {
if std::env::var("IANITOR_TEST_CRASH_AT").as_deref() == Ok(stage) {
log::error!(target: "ianitor::crash", "IANITOR_TEST_CRASH_AT={stage}: aborting on purpose");
std::process::abort();
log::error!(target: "ianitor::crash", "IANITOR_TEST_CRASH_AT={stage}: exiting on purpose");
std::process::exit(134);
}
}
#[cfg(not(feature = "test-hooks"))]
#[inline(always)]
pub fn point(_stage: &str) {}
/// Fail a state-file write when `IANITOR_TEST_FAIL_WRITE` names this file.
#[cfg(feature = "test-hooks")]
pub fn fail_write(path: &std::path::Path) -> Result<(), String> {
match (
std::env::var_os("IANITOR_TEST_FAIL_WRITE"),
@@ -42,3 +57,9 @@ pub fn fail_write(path: &std::path::Path) -> Result<(), String> {
_ => Ok(()),
}
}
#[cfg(not(feature = "test-hooks"))]
#[inline(always)]
pub fn fail_write(_path: &std::path::Path) -> Result<(), String> {
Ok(())
}
+54 -40
View File
@@ -18,42 +18,17 @@ use ianitor_control::repo::Repo;
use ianitor_control::tokens::Tokens;
use ianitor_control::util::{hex, random, write_atomic};
/// Hosts that get a certificate from the dev CA, so `tls = "domi"` works for them.
const DEV_HOSTS: [&str; 3] = ["app.dev.test", "wiki.dev.test", "photos.dev.test"];
/// A throw-away CA and certificates for [`DEV_HOSTS`] in `certs/`; the CA as `dev-ca.crt`.
fn dev_certs(dir: &Path) -> Result<(), String> {
use rcgen::{
BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair, KeyUsagePurpose,
};
let e = |x: rcgen::Error| x.to_string();
let ca_key = KeyPair::generate().map_err(e)?;
let mut ca = CertificateParams::new(Vec::<String>::new()).map_err(e)?;
ca.distinguished_name
.push(DnType::CommonName, "Ianitor dev CA");
ca.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
ca.key_usages = vec![
KeyUsagePurpose::KeyCertSign,
KeyUsagePurpose::DigitalSignature,
];
let ca_cert = ca.self_signed(&ca_key).map_err(e)?;
std::fs::write(dir.join("certs/dev-ca.crt"), ca_cert.pem()).map_err(|x| x.to_string())?;
let issuer = Issuer::new(ca, ca_key);
for h in DEV_HOSTS {
let key = KeyPair::generate().map_err(e)?;
let mut p = CertificateParams::new(vec![h.to_owned()]).map_err(e)?;
p.distinguished_name.push(DnType::CommonName, h);
let cert = p.signed_by(&key, &issuer).map_err(e)?;
std::fs::write(dir.join(format!("certs/{h}.crt")), cert.pem())
.map_err(|x| x.to_string())?;
write_atomic(
&dir.join(format!("certs/{h}.key")),
key.serialize_pem().as_bytes(),
0o600,
)
.map_err(|x| x.to_string())?;
}
Ok(())
/// A throw-away Domi root for dev mode, in `offline-root/` (its key stays in memory, like
/// on the offline machine), and the PKI password credential. Control then works like
/// production: it issues server certificates for every `tls = "domi"` host.
fn dev_pki(dir: &Path) -> Result<(String, ianitor_core::pki::KeyPair), String> {
let (root, key) = ianitor_core::pki::create_root(ianitor_control::util::now() as i64)
.map_err(|e| e.to_string())?;
std::fs::write(dir.join("offline-root/domi-root.crt"), &root).map_err(|e| e.to_string())?;
let pass = hex(&random::<24>().map_err(|e| e.to_string())?);
write_atomic(&dir.join("creds/pki-password"), pass.as_bytes(), 0o600)
.map_err(|e| e.to_string())?;
Ok((root, key))
}
const SITE: &str = "# Dev site settings. Sign-in goes to an Authelia that may not run here.\n\
@@ -125,10 +100,11 @@ pub async fn run(args: &[String]) -> Result<(), String> {
"creds",
"logs",
"edge-state",
"offline-root",
] {
std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?;
}
dev_certs(&dir)?;
let (root_pem, root_key) = dev_pki(&dir)?;
let key = hex(&random::<32>().map_err(|e| e.to_string())?);
write_atomic(&dir.join("creds/share-link-key"), key.as_bytes(), 0o600)
.map_err(|e| e.to_string())?;
@@ -172,8 +148,28 @@ pub async fn run(args: &[String]) -> Result<(), String> {
access_log: s("logs/access.log"),
caddy_credentials_dir: s("creds"),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
},
compile_caddy: None,
pki: Some(ianitor_control::config::PkiConfig {
root_cert: dir.join("offline-root/domi-root.crt"),
password_credential: "pki-password".into(),
approval: "manual".into(),
// Fast in test builds; the real floor in a release build.
kdf_iterations: if cfg!(feature = "test-hooks") {
10_000
} else {
ianitor_control::config::MIN_KDF_ITERATIONS
},
}),
ui: arg(args, "--ui-dir").map(|d| ianitor_control::config::UiConfig {
hostname: None,
proof_credential: None,
static_dir: Some(PathBuf::from(d)),
logout_url: None,
}),
engine: None,
};
cfg.check().map_err(|e| e.to_string())?;
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
@@ -183,6 +179,21 @@ pub async fn run(args: &[String]) -> Result<(), String> {
// Control writes edge.json first; then edge can start from it.
let ctl_cfg = cfg.clone();
let opened = ianitor_control::Control::open(ctl_cfg).await?;
// Dev only: sign the first intermediate with the throw-away root at once (in production
// this is the offline step in docs/pki.md).
if let Some(p) = &opened.pki {
let now = ianitor_control::util::now();
let r = p.request_renewal(now, "dev").map_err(|e| e.to_string())?;
let signed = ianitor_core::pki::sign_intermediate(
&root_pem,
&root_key,
r.csr_pem.as_deref().unwrap_or_default(),
now as i64,
)
.map_err(|e| e.to_string())?;
p.install_intermediate(&r.id, &signed, now)
.map_err(|e| e.to_string())?;
}
drop(opened);
if let Some(bin) = &edge_bin {
cleanup.edge = Some(start_edge(bin, &dir, &cfg)?);
@@ -192,16 +203,19 @@ pub async fn run(args: &[String]) -> Result<(), String> {
println!("Routes repository: {}", cfg.routes.repo.display());
match &edge_bin {
Some(b) => println!(
"Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080). tls = \"domi\" works for {}; CA: {}",
"Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080). tls = \"domi\" works for any name; Domi root: {}",
b.display(),
DEV_HOSTS.join(", "),
dir.join("certs/dev-ca.crt").display()
dir.join("offline-root/domi-root.crt").display()
),
None => println!(
"No ianitor-edge found: applies are written but not loaded or watched (use --edge-bin)."
),
}
println!("API token (shown once): {token}");
println!(
"Approve a device request: ianitor-control pki approve <code> --state-dir {}",
dir.join("state").display()
);
println!("Press Ctrl-C to stop and remove {}", dir.display());
let r = ianitor_control::serve(cfg, ianitor_control::stop_signal()).await;
drop(cleanup);
+7
View File
@@ -174,6 +174,13 @@ impl EdgeLink {
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
}
/// Re-read the device CA bundle and allow list (works during a trial too).
pub async fn reload_devices(&self) -> Result<(), EdgeLinkError> {
self.call("POST", "/v1/device-certs/reload", None)
.await
.map(|_| ())
}
pub async fn reload_revocations(&self) -> Result<(), EdgeLinkError> {
self.call("POST", "/v1/share-revocations/reload", None)
.await
+118 -2
View File
@@ -15,6 +15,8 @@
// A refusal is built once per failed request or apply; boxing it buys nothing.
#![allow(clippy::result_large_err)]
mod caddy_apply;
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -141,6 +143,14 @@ pub struct Control {
pub tokens: Tokens,
pub shares: Shares,
pub share_key: Option<ShareKey>,
/// The Domi CA, when `[pki]` is configured.
pub pki: Option<crate::pki::Pki>,
/// The per-boot secret edge adds on the admin host (`X-Ianitor-Proof`), from `[ui]`.
pub ui_proof: Option<Vec<u8>>,
/// Which engine serves (see `switch`).
pub engine: Mutex<crate::switch::EngineState>,
/// How control starts and stops the engines; `None` without `[engine]`.
pub units: Option<Arc<dyn crate::switch::Units>>,
records: Mutex<Vec<ApplyRecord>>,
queue: Mutex<VecDeque<Job>>,
wake: Notify,
@@ -151,7 +161,14 @@ pub struct Control {
/// False while the pause is only in memory (paused.json could not be written).
pause_saved: std::sync::atomic::AtomicBool,
/// Serialises applies with share-revocation writes and recovery.
apply_lock: tokio::sync::Mutex<()>,
pub(crate) apply_lock: tokio::sync::Mutex<()>,
/// Held while an engine is switched or told to reload its device or certificate files.
pub(crate) engine_lock: tokio::sync::Mutex<()>,
/// Serialises reading the device records and writing the device files (never held
/// across an apply or a switch).
pub(crate) devices_lock: tokio::sync::Mutex<()>,
/// Why the device files are not (yet) in force, until a retry succeeds.
pub devices_problem: Mutex<Option<String>>,
}
const MAX_RECORDS: usize = 1000;
@@ -207,6 +224,21 @@ impl Control {
if share_key.is_none() {
log::warn!(target: "ianitor::control", "no usable share-link-key credential: share links cannot be made");
}
let keys = crate::pki::root_key_files(&cfg.state_dir);
if let Some(k) = keys.first() {
return Err(format!(
"{} looks like a root CA key inside the state directory; the Domi root key must never be on the server (ROADMAP §1.2). Move it to the offline machine.",
k.display()
));
}
let pki = match &cfg.pki {
Some(p) => Some(crate::pki::Pki::open(
p,
&cfg.state_dir,
cfg.credential(&p.password_credential),
)?),
None => None,
};
let records: Vec<ApplyRecord> =
read_json(&cfg.state_dir.join("applies.json"))?.unwrap_or_default();
let push: PushState = read_json(&cfg.state_dir.join("push.json"))?.unwrap_or_default();
@@ -217,6 +249,25 @@ impl Control {
repo,
edge,
share_key,
ui_proof: cfg
.ui
.as_ref()
.and_then(|u| u.proof_credential.as_deref())
.and_then(|n| cfg.credential(n))
.filter(|p| p.len() >= 32),
pki,
engine: Mutex::new(crate::switch::EngineState {
running: cfg
.engine
.as_ref()
.map(|e| crate::switch::read_engine_file(&e.file))
.unwrap_or_else(|| "pingora".into()),
state: "running".into(),
since: now(),
target: None,
last_error: None,
}),
units: crate::switch::units_for(cfg.engine.as_ref()),
records: Mutex::new(records),
queue: Mutex::new(VecDeque::new()),
wake: Notify::new(),
@@ -226,8 +277,16 @@ impl Control {
paused: Mutex::new(paused),
pause_saved: std::sync::atomic::AtomicBool::new(true),
apply_lock: tokio::sync::Mutex::new(()),
engine_lock: tokio::sync::Mutex::new(()),
devices_lock: tokio::sync::Mutex::new(()),
devices_problem: Mutex::new(None),
cfg,
});
if let Ok((_, _, m)) = c.head_model()
&& let Err(f) = c.pki_prepare(&m)
{
log::error!(target: "ianitor::pki", "{}", f.reason.message);
}
c.recover().await?;
Ok(c)
}
@@ -619,6 +678,31 @@ impl Control {
errors: fe,
}
})?;
// The UI proof belongs to the [ui] host only (core already demands forward-auth for it).
let ui_host = self.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
for h in model.hosts() {
let proof = h.request_headers.iter().any(|r| {
matches!(r, ianitor_core::HeaderRule::Set { value: ianitor_core::HeaderValue::Secret(s), .. } if s.as_str() == ianitor_core::UI_PROOF_SECRET)
});
if proof && ui_host != Some(h.hostname.as_str()) {
let p = messages::params([("hostname", h.hostname.to_string())]);
let fe = FieldError {
code: "host.header.proof_host".into(),
message: message("host.header.proof_host", &p),
field: Some("request_headers".into()),
params: p.clone(),
detail: None,
};
return Err(Fail {
status: 422,
reason: reason(
"apply.failed.validation",
messages::params([("first_error", fe.message.clone())]),
),
errors: vec![fe],
});
}
}
Ok(Plan {
kind,
verb: host_verb(kind),
@@ -863,6 +947,11 @@ impl Control {
Ok(x) => x,
Err(f) => return self.finish(&id, "failed", Some(f.reason), Vec::new()),
};
// Domi certificates for the hosts of the new tree, before anything is committed (new
// files only: a certificate edge serves now is never replaced by a worse one).
if let Err(f) = self.pki_prepare(&plan.model) {
return self.finish(&id, "failed", Some(f.reason), Vec::new());
}
self.update(&id, |r| {
r.step("compile", "done");
r.step("write", "running");
@@ -969,6 +1058,13 @@ impl Control {
r.step("reload", "running");
});
// Caddy serves: load the trial into Caddy and watch through it (Mark, 2026-11-08).
if self.engine_running() == "caddy" {
return self
.run_under_caddy(&id, j, &plan, &caddy_text, &job.change)
.await;
}
// Which hosts to judge: those this change adds or changes, not those it removes.
let watch_hosts: Vec<String> = plan
.hosts
@@ -1411,7 +1507,8 @@ impl Control {
/// The idempotent part of a revert. Returns the revert commit, if one was needed.
async fn finish_revert(&self, j: &Journal) -> Result<Option<String>, String> {
if self.edge.attached() {
let caddy = self.engine_running() == "caddy";
if self.edge.attached() && !caddy {
match self.edge.abort().await {
Ok(_) => {}
// Edge down: it starts from edge.json, which is still the last good config.
@@ -1447,6 +1544,15 @@ impl Control {
for p in [self.cfg.trial_path(), self.cfg.caddy_trial_path()] {
remove_if_exists(&p).map_err(|e| e.to_string())?;
}
if caddy {
// Caddy must run caddy.json again, the last good config (with the device files as
// they are now); then no trial is out any more. Under the engine lock, so a device
// change that saw the trial and left the reload to this point is not lost.
let _engine = self.engine_lock.lock().await;
self.caddy_reload().await?;
crate::caddy_guard::disarm(&self.cfg.state_dir);
return Ok(rev);
}
// Edge must now run edge.json, the last good config. If it confirmed the trial after
// all (an answer lost on the way) it does not: reload it. If edge cannot be asked,
// this is not a finished revert (a restart asks again).
@@ -1605,6 +1711,16 @@ impl Control {
self.unpause();
self.sync_files().await;
}
if self.engine_running() == "caddy" {
match self.caddy_reload().await {
Ok(()) => crate::caddy_guard::disarm(&self.cfg.state_dir),
Err(e) => {
log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}")
}
}
} else {
crate::caddy_guard::disarm(&self.cfg.state_dir);
}
if let Err(e) = self.shares.ensure_revocation_file() {
log::error!(target: "ianitor::share", "{e}");
}
+466
View File
@@ -0,0 +1,466 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Applies while Caddy serves (Mark, 2026-11-08: changes keep working under Caddy). The same
//! pipeline and journal as with edge; only the trial, the watch and the revert differ:
//!
//! - the trial is loaded into Caddy through its admin socket, after its deadline is armed
//! (crate::caddy_guard: a crashed or hung control cannot leave it serving);
//! - the watch judges health the way edge does (QC round 2, M1): control probes the upstreams
//! itself with edge's rules, and the probe *through* Caddy only asks whether Caddy answers
//! at all (any status counts, also its auth redirect, 401, 403 or 421);
//! - every round checks that Caddy still runs the trial (M2: a reload by anyone else drops it);
//! - a revert loads caddy.json (the last good config) again; a confirm claims the deadline,
//! then promotes, loads caddy.json and checks that Caddy runs it.
use std::net::SocketAddr;
use super::*;
use crate::caddy_guard;
use crate::caddy_link::{self, Probe};
/// Where control reaches Caddy's HTTPS listener (its own machine).
fn local(addr: SocketAddr) -> SocketAddr {
if addr.ip().is_unspecified() {
let ip: std::net::IpAddr = if addr.is_ipv6() {
std::net::Ipv6Addr::LOCALHOST.into()
} else {
std::net::Ipv4Addr::LOCALHOST.into()
};
SocketAddr::new(ip, addr.port())
} else {
addr
}
}
/// How one host is probed (edge's rules, crates/edge/src/health.rs).
struct Rule {
upstreams: Vec<ianitor_core::Upstream>,
path: String,
has_check: bool,
}
impl Control {
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> {
self.cfg
.caddy_compile()
.caddy_admin_socket
.as_ref()
.map(std::path::PathBuf::from)
}
/// Load caddy.json (the last good config) into the running Caddy, even when it is the
/// config Caddy already runs (so it reads its files again), and check that it runs it.
pub async fn caddy_reload(&self) -> Result<(), String> {
let sock = self
.caddy_socket()
.ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?;
let text = std::fs::read(&self.cfg.caddy.config)
.map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?;
caddy_link::load(&sock, &text).await?;
if !caddy_link::runs(&sock, &text).await? {
return Err("Caddy took the config but does not run it".into());
}
Ok(())
}
/// `caddy_reload`, then the backstop for certificate and device changes: Caddy must serve
/// the certificate that is on disk now for a Domi host (it proves the files were read).
pub async fn caddy_reload_checked(&self) -> Result<(), String> {
self.caddy_reload().await?;
let Ok((_, _, model)) = self.head_model() else {
return Ok(());
};
let Some(h) = model
.hosts()
.iter()
.find(|h| h.tls == ianitor_core::TlsMode::Domi)
else {
return Ok(());
};
let file = std::path::Path::new(&self.cfg.caddy_compile().cert_dir)
.join(format!("{}.crt", h.hostname));
let want = std::fs::read_to_string(&file)
.ok()
.and_then(|pem| ianitor_core::pki::chain_der(&pem).ok())
.and_then(|c| c.into_iter().next())
.map(|der| crate::util::sha256_hex(&der))
.ok_or_else(|| format!("cannot read {}", file.display()))?;
let addr = local(self.cfg.caddy_compile().https_listen);
let got = caddy_link::served_cert_sha256(addr, h.hostname.as_str()).await?;
if got != want {
return Err(format!(
"Caddy still serves an older certificate for {} after the reload",
h.hostname
));
}
Ok(())
}
fn caddy_rules(&self, plan: &Plan) -> BTreeMap<String, Rule> {
plan.model
.hosts()
.iter()
.map(|h| {
(
h.hostname.to_string(),
Rule {
upstreams: h.upstreams.clone(),
path: h
.health_check
.as_ref()
.map_or("/".to_owned(), |c| c.path.clone()),
has_check: h.health_check.is_some(),
},
)
})
.collect()
}
/// One round of edge-style upstream probes for one host; `(address, probe)` per upstream.
async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> {
let mut out = Vec::new();
for u in &r.upstreams {
let host_header = if r.has_check {
u.authority()
} else {
hostname.to_owned()
};
let p = caddy_link::probe_upstream(u, &r.path, &host_header, !r.has_check).await;
out.push((u.authority(), p));
}
out
}
pub(super) async fn run_under_caddy(
&self,
id: &str,
mut j: Journal,
plan: &Plan,
caddy_text: &str,
change: &Change,
) {
let fail = |code: &str, detail: String| {
let mut r = reason(code, messages::params([("engine", "Caddy".into())]));
r.detail = Some(detail);
r
};
let Some(sock) = self.caddy_socket() else {
let r = fail(
"apply.failed.reload",
"no caddy_admin_socket is configured".into(),
);
return self.revert(id, &j, r, "failed").await;
};
let watch_hosts: Vec<String> = plan
.hosts
.iter()
.filter(|h| plan.target.host(h).is_some())
.cloned()
.collect();
let addr = local(self.cfg.caddy_compile().https_listen);
let rules = self.caddy_rules(plan);
// A host whose upstreams already failed before the change is no reason to revert
// (edge: `down_hosts`). Judged by the upstreams, as edge does.
let existed: BTreeSet<String> = self
.repo
.tree(&j.base)
.map(|t| {
watch_hosts
.iter()
.filter(|h| t.host(h).is_some())
.cloned()
.collect()
})
.unwrap_or_default();
let mut was_down = BTreeSet::new();
for h in &existed {
if let Some(r) = rules.get(h)
&& !Self::probe_host(h, r).await.iter().any(|(_, p)| p.ok)
{
was_down.insert(h.clone());
}
}
let window = self.cfg.watch_secs;
// The deadline goes out before the trial does (crate::caddy_guard).
let deadline = now() + window + self.cfg.trial_margin_secs + 5;
// Under the engine lock: a device change that looked a moment ago saw no trial and
// reloads caddy.json; it must not land after the trial is in.
let loaded = {
let _engine = self.engine_lock.lock().await;
match caddy_guard::arm(&self.cfg.state_dir, id, deadline) {
Err(e) => {
let mut r = reason("internal", Params::new());
r.detail = Some(e);
Err((r, "failed"))
}
Ok(()) => caddy_link::load(&sock, caddy_text.as_bytes())
.await
.map_err(|e| (fail("apply.failed.reload", e), "failed")),
}
};
if let Err((r, state)) = loaded {
return self.revert(id, &j, r, state).await;
}
j.stage = "trial_loaded".into();
if let Err(e) = self.journal(&j) {
let mut r = reason("internal", Params::new());
r.detail = Some(e);
return self.revert(id, &j, r, "failed").await;
}
crash::point("trial_loaded");
self.update(id, |r| r.step("reload", "done"));
let judged: Vec<String> = watch_hosts
.iter()
.filter(|h| !was_down.contains(*h))
.cloned()
.collect();
let mut kept_reason = if watch_hosts.is_empty() {
reason(
"apply.kept.removed",
messages::params([("hostname", plan.hosts.join(", "))]),
)
} else {
reason(
"apply.kept",
messages::params([
("hostname", watch_hosts.join(", ")),
("seconds", window.to_string()),
]),
)
};
let ends = now() + window;
if judged.is_empty() {
self.update(id, |r| r.step("watch", "skipped"));
} else {
self.update(id, |r| {
r.state = "watching".into();
r.step("watch", "running");
r.watch = Some(Watch {
ends,
hosts: judged
.iter()
.map(|h| WatchHost {
hostname: h.clone(),
..Default::default()
})
.collect(),
});
});
}
if let Err(r) = self
.caddy_watch(id, &sock, caddy_text, &judged, &rules, plan, addr, ends)
.await
{
return self.revert(id, &j, r, "reverted").await;
}
if !judged.is_empty() {
let no_check: Vec<String> = judged
.iter()
.filter(|h| rules.get(*h).is_some_and(|r| !r.has_check))
.cloned()
.collect();
if !no_check.is_empty() && no_check.len() == judged.len() {
kept_reason = reason(
"apply.kept.no_watch",
messages::params([("hostname", no_check.join(", "))]),
);
}
self.update(id, |r| r.step("watch", "done"));
}
crash::point("watched");
// Confirmed first, then the deadline is claimed (fix round 3): a crash in between
// leaves the deadline armed *and* the journal confirmed, so the guard and caddy-revert
// leave the trial alone and recovery promotes it. The other order would leave a window
// with nothing armed and nothing confirmed, where nobody reverts Caddy.
j.stage = "confirmed".into();
if let Err(e) = self.journal(&j) {
let mut r = reason("internal", Params::new());
r.detail = Some(e);
return self.revert(id, &j, r, "failed").await;
}
crash::point("confirmed");
// From the claim to Caddy running the promoted caddy.json, no device reload may load
// the old caddy.json in between.
let engine = self.engine_lock.lock().await;
// The guard may have reverted a trial that ran past its deadline (a stalled control):
// then this change is not kept.
if !caddy_guard::claim(&self.cfg.state_dir) {
drop(engine);
let mut r = reason("apply.interrupted", Params::new());
r.detail = Some(
"the trial ran past its deadline, so Caddy went back to the last good config"
.into(),
);
return self.revert(id, &j, r, "reverted").await;
}
if let Err(e) = self.promote() {
drop(engine);
log::error!(target: "ianitor::apply", "cannot write the config files: {e}");
let mut p = reason("control.files_unwritten", Params::new());
p.detail = Some(e.to_string());
p.params.insert("apply_id".into(), id.to_owned());
if let Err(pe) = self.pause(p) {
log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it");
}
let push_step = self.push_step();
self.update(id, |r| r.step("push", push_step));
self.finish(id, "kept", Some(kept_reason), Vec::new());
return;
}
crash::point("promoted");
// caddy.json now holds the change: Caddy loads what was written (with the device and
// certificate files as they are now) and must run it.
if let Err(e) = self.caddy_reload().await {
log::error!(target: "ianitor::apply", "Caddy did not load the promoted caddy.json: {e}");
}
drop(engine);
let push_step = self.push_step();
self.update(id, |r| r.step("push", push_step));
self.finish(id, "kept", Some(kept_reason), Vec::new());
self.clear_journal();
if self.paused().is_some() && matches!(change, Change::Restore { .. }) {
self.unpause();
}
self.push_wake.notify_one();
}
/// The watch under Caddy until `ends`: the reason to revert, if any.
#[allow(clippy::too_many_arguments)]
async fn caddy_watch(
&self,
id: &str,
sock: &std::path::Path,
trial: &str,
judged: &[String],
rules: &BTreeMap<String, Rule>,
plan: &Plan,
addr: SocketAddr,
ends: u64,
) -> Result<(), Reason> {
let mut seen: HashMap<(String, String), BTreeMap<u64, Check>> = HashMap::new();
let mut seq = 0u64;
let mut silent: BTreeMap<String, (u32, String)> = BTreeMap::new();
let paths: HashMap<String, String> = rules
.iter()
.map(|(h, r)| (h.clone(), r.path.clone()))
.collect();
let mut first = true;
loop {
// Anyone else's reload (a device change, a restart of caddy-fallback) drops the
// trial: then this is not a verdict on the change.
match caddy_link::runs(sock, trial.as_bytes()).await {
Ok(true) => {}
Ok(false) => {
let mut r = reason("apply.reverted.edge_lost", Params::new());
r.detail = Some("Caddy no longer runs the trial config".into());
return Err(r);
}
Err(e) => {
let mut r = reason("apply.reverted.edge_lost", Params::new());
r.detail = Some(e);
return Err(r);
}
}
if first {
crash::point("watching");
first = false;
}
let mut counts = Vec::new();
for h in judged {
let Some(rule) = rules.get(h) else { continue };
// Does Caddy answer for this host at all? Any status does.
match caddy_link::probe(addr, h, "/").await {
Probe::Status(_) => {
silent.remove(h);
}
Probe::NoAnswer(e) => {
let s = silent.entry(h.clone()).or_insert((0, String::new()));
s.0 += 1;
s.1 = e;
}
}
if let Some((n, e)) = silent.get(h)
&& *n >= 3
{
let mut r = reason(
"apply.reverted.no_answer",
messages::params([
("hostname", h.clone()),
("verb", plan.verb.into()),
("seconds", self.cfg.watch_secs.to_string()),
]),
);
r.hostname = Some(h.clone());
r.detail = Some(format!("Caddy does not answer for {h}: {e}"));
return Err(r);
}
for (address, p) in Self::probe_host(h, rule).await {
seq += 1;
seen.entry((h.clone(), address)).or_default().insert(
seq,
Check {
seq,
at: now(),
ok: p.ok,
source: if rule.has_check {
"health_check".into()
} else {
"watch".into()
},
kind: p.kind.map(str::to_owned),
status: p.status,
latency_ms: p.latency_ms,
},
);
}
let mut passed = 0u32;
let mut failed = 0u32;
let mut all_failing = !rule.upstreams.is_empty();
for ((host, _), m) in &seen {
if host != h {
continue;
}
passed += m.values().filter(|c| c.ok).count() as u32;
failed += m.values().filter(|c| !c.ok).count() as u32;
if m.values().rev().take_while(|c| !c.ok).count() < 3 {
all_failing = false;
}
}
counts.push(WatchHost {
hostname: h.clone(),
passed,
failed,
total: passed + failed,
});
if all_failing {
return Err(self.revert_reason(h, plan, &seen, &paths));
}
}
self.update(id, |r| {
if let Some(w) = &mut r.watch {
w.hosts = counts;
}
});
if now() >= ends {
break;
}
tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await;
}
// At the end, as with edge: every judged host needs an upstream whose last probe passed.
for h in judged {
let last_ok = seen
.iter()
.filter(|((host, _), _)| host == h)
.any(|(_, m)| m.values().next_back().is_some_and(|c| c.ok));
if !last_ok {
return Err(self.revert_reason(h, plan, &seen, &paths));
}
}
Ok(())
}
}
+9
View File
@@ -26,6 +26,9 @@ pub struct HostSpec {
pub websockets: bool,
#[serde(default)]
pub share_links: bool,
/// Visitors need a Domi device certificate (mTLS).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub device_certs: bool,
/// `off` or `truncated`.
#[serde(default = "off")]
pub access_log: String,
@@ -115,6 +118,11 @@ impl HostSpec {
to.share_links.to_string(),
);
push("access_log", self.access_log.clone(), to.access_log.clone());
push(
"device_certs",
self.device_certs.to_string(),
to.device_certs.to_string(),
);
let hc =
|h: &Option<HealthCheckSpec>| h.as_ref().map(|h| (h.path.clone(), h.interval_secs));
let (a, b) = (hc(&self.health_check), hc(&to.health_check));
@@ -157,6 +165,7 @@ mod tests {
auth: "none".into(),
websockets: false,
share_links: true,
device_certs: true,
access_log: "truncated".into(),
health_check: Some(HealthCheckSpec {
path: "/health".into(),
+6
View File
@@ -7,6 +7,8 @@
//! edge keeps serving the last good config.
pub mod api;
pub mod caddy_guard;
pub mod caddy_link;
pub mod config;
pub mod crash;
pub mod edgelink;
@@ -14,9 +16,12 @@ pub mod engine;
pub mod hostspec;
pub mod logger;
pub mod messages;
pub mod pki;
pub mod pki_ctl;
pub mod records;
pub mod repo;
pub mod shares;
pub mod switch;
pub mod tokens;
pub mod util;
@@ -36,6 +41,7 @@ pub async fn serve(
tokio::spawn(ctl.clone().worker());
tokio::spawn(ctl.clone().health_poller());
tokio::spawn(ctl.clone().pusher());
tokio::spawn(ctl.clone().pki_poller());
let app = api::router(api::AppState::new(ctl.clone()));
if !listen.ip().is_loopback() {
return Err("ianitor-control only listens on loopback".into());
+198 -1
View File
@@ -9,6 +9,11 @@
//! ianitor-control token list (--config <c> | --state-dir <d>)
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
//! ianitor-control openapi print the OpenAPI document
//! ianitor-control pki approve|deny <code> (--config <c> | --state-dir <d>) approve a device request
//! ianitor-control pki install <intermediate.crt> (--config <c>) install a signed intermediate
//! ianitor-control pki status (--config <c>) open requests
//! ianitor-control ca init --out <dir> [--passphrase-file <f>] the offline root (never on the server)
//! ianitor-control ca sign --root <dir> --csr <f> --out <f> [--yes] sign an intermediate offline
//! ianitor-control check --config <control.toml> check the config and exit
//! ```
//! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`),
@@ -25,7 +30,8 @@ fn usage() -> ExitCode {
eprintln!(
"usage: ianitor-control --config <control.toml> | --dev [--edge-bin <path>] | \
token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) | \
token list (...) | token revoke <id> (...) | openapi | check --config <c>"
token list (...) | token revoke <id> (...) | openapi | check --config <c> | \
caddy-revert --config <c> | caddy-guard --config <c>"
);
ExitCode::from(2)
}
@@ -197,6 +203,174 @@ fn token(args: &[String]) -> Result<(), String> {
}
}
fn arg_after(args: &[String], name: &str) -> Option<String> {
let mut it = args.iter();
while let Some(a) = it.next() {
if a == name {
return it.next().cloned();
}
}
None
}
/// A passphrase from `--passphrase-file`, or asked on the terminal without echo.
fn passphrase(args: &[String], confirm: bool) -> Result<String, String> {
if let Some(f) = arg_after(args, "--passphrase-file") {
let v = std::fs::read_to_string(&f).map_err(|e| format!("cannot read {f}: {e}"))?;
let v = v.trim_end_matches(['\r', '\n']).to_owned();
if v.chars().count() < 12 {
return Err("the passphrase must have at least 12 characters".into());
}
return Ok(v);
}
let p = rpassword::prompt_password("Root key passphrase: ").map_err(|e| e.to_string())?;
if p.chars().count() < 12 {
return Err("the passphrase must have at least 12 characters".into());
}
if confirm {
let again = rpassword::prompt_password("Again: ").map_err(|e| e.to_string())?;
if again != p {
return Err("the two passphrases differ".into());
}
}
Ok(p)
}
/// `ca init` and `ca sign`: the offline root (ROADMAP §1.2; docs/pki.md). Never run on the
/// server.
fn ca(args: &[String]) -> Result<(), String> {
use ianitor_core::pki;
let now = ianitor_control::util::now() as i64;
match args.first().map(String::as_str) {
Some("init") => {
let out = PathBuf::from(arg_after(args, "--out").ok_or("ca init --out <dir>")?);
let crt = out.join("domi-root.crt");
let key = out.join("domi-root.key");
if crt.exists() || key.exists() {
return Err(format!(
"{} already has a root; refusing to replace it",
out.display()
));
}
std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
let pass = passphrase(args, true)?;
let (cert, k) = pki::create_root(now).map_err(|e| e.to_string())?;
let sealed = pki::encrypt_key(&k, pass.as_bytes()).map_err(|e| e.to_string())?;
ianitor_control::util::write_atomic(&key, sealed.as_bytes(), 0o600)
.map_err(|e| e.to_string())?;
ianitor_control::util::write_atomic(&crt, cert.as_bytes(), 0o644)
.map_err(|e| e.to_string())?;
let info = pki::inspect(&cert).map_err(|e| e.to_string())?;
eprintln!(
"Domi root created in {}: {} (valid until {}).\nSHA-256 {}\n\
Copy domi-root.crt to the server's configuration (services.ianitor.pki.rootCertificate).\n\
Keep domi-root.key and its passphrase offline (Custos, once it can hold it).",
out.display(),
info.subject_cn,
ianitor_core::time::long_date(info.not_after.max(0) as u64),
info.sha256_hex
);
Ok(())
}
Some("sign") => {
let root = PathBuf::from(
arg_after(args, "--root")
.ok_or("ca sign --root <dir> --csr <file> --out <file>")?,
);
let csr_path = arg_after(args, "--csr").ok_or("--csr <file> is required")?;
let out = PathBuf::from(arg_after(args, "--out").ok_or("--out <file> is required")?);
let csr = std::fs::read_to_string(&csr_path)
.map_err(|e| format!("cannot read {csr_path}: {e}"))?;
let code = pki::match_code(&pki::csr_der(&csr).map_err(|e| e.to_string())?);
eprintln!("This request's code is {code}. It must be the code Ianitor shows.");
if !args.iter().any(|a| a == "--yes") {
let typed = rpassword::prompt_password("Type the code to sign (no echo): ")
.map_err(|e| e.to_string())?;
if ianitor_control::pki::normalise_code(&typed)
!= ianitor_control::pki::normalise_code(&code)
{
return Err("the code does not match; nothing was signed".into());
}
}
let cert =
std::fs::read_to_string(root.join("domi-root.crt")).map_err(|e| e.to_string())?;
let sealed =
std::fs::read_to_string(root.join("domi-root.key")).map_err(|e| e.to_string())?;
let pass = passphrase(args, false)?;
let key = pki::decrypt_key(&sealed, pass.as_bytes()).map_err(|e| e.to_string())?;
let signed =
pki::sign_intermediate(&cert, &key, &csr, now).map_err(|e| e.to_string())?;
ianitor_control::util::write_atomic(&out, signed.as_bytes(), 0o644)
.map_err(|e| e.to_string())?;
let info = pki::inspect(&signed).map_err(|e| e.to_string())?;
eprintln!(
"Signed {} until {}. Install it on the server: ianitor-control pki install {}",
info.subject_cn,
ianitor_core::time::long_date(info.not_after.max(0) as u64),
out.display()
);
Ok(())
}
_ => Err("ca init --out <dir> | ca sign --root <dir> --csr <file> --out <file>".into()),
}
}
/// `pki approve|deny|install|status` on the server, as the user control runs as.
fn pki_cli(args: &[String]) -> Result<(), String> {
let dir = state_dir(args)?;
same_owner(&dir)?;
let now = ianitor_control::util::now();
match args.first().map(String::as_str) {
Some(verb @ ("approve" | "deny")) => {
// The code may be given as one word or three (47 19 83).
let code: String = args
.iter()
.skip(1)
.take_while(|a| !a.starts_with("--"))
.cloned()
.collect::<Vec<_>>()
.join("");
let r = ianitor_control::pki::cli_approve(&dir, &code, verb == "deny", now)?;
let name = r.name.clone().unwrap_or_default();
eprintln!("Handed to control; waiting for it ...");
let state = ianitor_control::pki::cli_wait(&dir, &r.id, now)
.map_err(|e| format!("not done for \"{name}\" ({}): {e}", r.id))?;
eprintln!(
"{} the request for \"{name}\" ({}).",
if state == "approved" { "Approved" } else { "Turned down" },
r.id
);
Ok(())
}
Some("install") => {
let f = args.get(1).filter(|a| !a.starts_with("--")).ok_or("pki install <intermediate.crt>")?;
let pem = std::fs::read_to_string(f).map_err(|e| format!("cannot read {f}: {e}"))?;
let r = ianitor_control::pki::cli_install(&dir, &pem, now)?;
eprintln!("Handed to renewal {}; waiting for control to install it ...", r.id);
ianitor_control::pki::cli_wait(&dir, &r.id, now)
.map_err(|e| format!("not installed: {e}"))?;
eprintln!("Installed. Server certificates are reissued from it now.");
Ok(())
}
Some("status") => {
let rs: Vec<ianitor_control::pki::Request> =
ianitor_control::util::read_json(&ianitor_control::pki::requests_path(&dir))?.unwrap_or_default();
for r in rs.iter().filter(|r| r.state == "waiting" && r.expires_at > now) {
println!(
"{} {} {} code {} until {}",
r.id,
r.kind,
r.name.clone().unwrap_or_default(),
r.match_code,
ianitor_control::util::rfc3339(r.expires_at)
);
}
Ok(())
}
_ => Err("pki approve <code> | pki deny <code> | pki install <cert> | pki status (--config <c> | --state-dir <d>)".into()),
}
}
fn main() -> ExitCode {
if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") {
return askpass();
@@ -215,11 +389,34 @@ fn main() -> ExitCode {
};
let result = match args.first().map(String::as_str) {
Some("token") => token(&args[1..]),
Some("pki") => pki_cli(&args[1..]),
Some("ca") => ca(&args[1..]),
Some("openapi") => {
println!("{}", ianitor_control::api::openapi_json());
Ok(())
}
Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")),
// Caddy trial deadline (ianitor_control::caddy_guard): after control stops, and the guard.
Some(verb @ ("caddy-revert" | "caddy-guard")) => match args
.iter()
.position(|a| a == "--config")
.and_then(|i| args.get(i + 1))
{
Some(p) => match Config::load(&PathBuf::from(p)) {
Ok(cfg) if verb == "caddy-guard" => {
rt.block_on(ianitor_control::caddy_guard::run(cfg))
}
Ok(cfg) => rt
.block_on(ianitor_control::caddy_guard::revert_after_stop(&cfg))
.map(|done| {
if done {
eprintln!("Caddy is back on the last good config.");
}
}),
Err(e) => Err(e.to_string()),
},
None => return usage(),
},
Some("--dev") => rt.block_on(dev::run(&args[1..])),
Some("--config") => match args.get(1) {
Some(p) => match Config::load(&PathBuf::from(p)) {
+125
View File
@@ -228,6 +228,131 @@ fn template(code: &str) -> &'static str {
"health.unavailable" => {
"Ianitor cannot read health from {engine} right now. Traffic is not affected."
}
// 3.6 PKI
"pki.waiting" => {
"Open Custos on your phone. Approve only if it shows the same code: {code}."
}
"pki.waiting.manual" => {
"Approve it on the server: run ianitor-control pki approve {code}. Approve only if the code matches."
}
"pki.renew.manual" => {
"Sign this request on the offline computer and check that its fingerprint matches (Sign by hand shows both), then install the certificate."
}
"pki.denied" => "The request was turned down. Nothing was issued.",
"pki.expired" => "Nobody approved it in time, so the request closed. Nothing was issued.",
"pki.custos_unreachable" => "Custos is not answering, so the request could not be sent.",
"pki.device_name_taken" => {
"A device with this name already has a certificate or an open request. Use another name, or revoke the old one first."
}
"pki.device_name" => "Give the device a name of 1 to 64 characters.",
"pki.device_kind" => "Choose phone, computer or app.",
"pki.issued" => "{name} has a certificate.",
"pki.bundle_used" => {
"This download was already used or has expired. Make a new one from the device's row."
}
"pki.renew_due" => "The Domi intermediate certificate expires in {days} days, on {date}.",
"pki.renew_urgent" => {
"The Domi intermediate certificate expires in {days} days. After that, Domi certificates stop working."
}
"pki.intermediate_expired" => {
"The Domi intermediate certificate has expired. Hosts with a Domi certificate are not trusted until it is renewed."
}
"pki.renewed" => "Renewed. The Domi intermediate certificate is now valid until {date}.",
"pki.not_configured" => {
"The Domi certificate authority is not set up on this server. See docs/pki.md."
}
"pki.no_password" => {
"The password for the Domi certificate keys is missing from the server's credentials, so nothing can be issued."
}
"pki.wrong_password" => {
"The password for the Domi certificate keys does not open them. Check the pki-password credential."
}
"pki.no_intermediate" => {
"There is no Domi intermediate certificate yet, so Domi certificates cannot be issued. Set it up first in Certificates."
}
"pki.not_our_root" => {
"This certificate was not signed by the Domi root this server trusts."
}
"pki.wrong_key" => {
"This certificate was made for another request. Sign the request shown here, then try again."
}
"pki.bad_certificate" => {
"This is not a Domi intermediate certificate Ianitor can use. It must be a CA with path length 0 that is valid now."
}
"pki.request_not_found" => "There is no such request.",
"pki.request_closed" => "This request is closed. Start a new one.",
"pki.wrong_code" => "That code does not match the request.",
"pki.too_many_requests" => "Too many requests are open. Finish or cancel some first.",
"pki.device_not_found" => "There is no such device.",
"pki.device_not_valid" => {
"This device's certificate is revoked or expired, so it cannot be installed. Issue a new one."
}
"pki.revoked" => {
"Revoked. {name} can no longer reach hosts that need a device certificate."
}
// UI sign-in
"ui.no_proof" => {
"This request carries a sign-in header but did not come through Ianitor's proxy, so it was refused."
}
"ui.no_user" => "The sign-in did not say who you are. Sign in again.",
// engine switch
"engine.unmanaged" => {
"This server does not let Ianitor switch engines (no engine settings in control.toml)."
}
"engine.same" => "{engine} is already serving.",
"engine.switching" => "A switch is already running. Wait for it to finish.",
"engine.busy" => "A change is being applied. Switch when it has finished.",
"engine.switched" => "{engine} is serving now.",
"engine.switch_failed" => {
"{engine} did not start, so Ianitor went back to {previous}. Traffic is served as before."
}
"host.header.proof" => {
"Only a host behind sign-in can send the ui-proof secret. Choose Sign in first, or remove the rule."
}
"host.header.proof_host" => {
"Only the web UI's admin host can send the ui-proof secret, and {hostname} is not it ([ui] hostname in control.toml)."
}
"pki.manual.not_ca" => {
"This certificate cannot sign other certificates. Sign it again with the signing settings file (.ext)."
}
"pki.manual.eku" => {
"This certificate is limited to some uses, so it could not issue both host and device certificates. Sign it again with the signing settings file (.ext)."
}
"pki.manual.dates" => {
"This certificate is not valid yet, has already expired, or lasts longer than the Domi root. Check the offline computer's clock and use -days 365."
}
"pki.devices_unwritten" => {
"The device list could not be saved or handed to the proxy, so the change is not in force yet. Ianitor keeps trying; try again in a moment."
}
"engine.not_ready" => {
"Caddy is not ready: its settings could not be built from the current routes."
}
// The eight codes the UI hand-off gave sentences for (handoff §12.2, decision Q12).
"repo.duplicate_file" => {
"Two files in the routes repository describe {hostname}. Remove one, then Ianitor picks it up."
}
"file.syntax" => {
"{file} in the routes repository has a typing mistake. Changes are paused until it is fixed."
}
"file.too_large" => {
"{file} in the routes repository is too large to read. Changes are paused until it is fixed."
}
"site.field.unknown" => "ianitor.toml has a setting Ianitor does not know: \"{field}\".",
"site.forward_auth" => {
"The sign-in settings in ianitor.toml cannot be used. Show details to see why."
}
"site.forward_auth.header" => {
"ianitor.toml asks sign-in to pass on \"{name}\", which cannot be a header name."
}
"site.secret.name" => {
"\"{name}\" cannot be a secret name in ianitor.toml. Use letters, digits, dashes and underscores."
}
"site.acme" => {
"The Let's Encrypt settings in ianitor.toml cannot be used. Show details to see why."
}
"share.engine_caddy" => {
"Share links are paused while Caddy serves. They work again after switching back."
}
"internal" => "Something went wrong inside Ianitor control. Show details for more.",
_ => "Something went wrong.",
}
File diff suppressed because it is too large Load Diff
+270
View File
@@ -0,0 +1,270 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Control's side of the Domi CA: certificates for the hosts of every tree that is applied,
//! the device files both engines read, and what happens after an approval, a renewal or a
//! revocation.
// A refusal is built once per failed request; boxing it buys nothing.
#![allow(clippy::result_large_err)]
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use ianitor_core::TlsMode;
use crate::engine::{Control, Fail};
use crate::messages::{self, Params};
use crate::pki::PkiFail;
use crate::util::now;
/// The HTTP status for a PKI refusal.
pub fn status_of(code: &str) -> u16 {
match code {
"pki.request_not_found" | "pki.device_not_found" => 404,
"pki.bundle_used" => 410,
"pki.bad_certificate"
| "pki.not_our_root"
| "pki.wrong_key"
| "pki.device_name"
| "pki.device_kind"
| "pki.wrong_code"
| "pki.manual.not_ca"
| "pki.manual.eku"
| "pki.manual.dates" => 422,
"pki.devices_unwritten" => 503,
"pki.too_many_requests" => 429,
_ => 409,
}
}
pub fn pki_fail(e: PkiFail) -> Fail {
match e {
PkiFail::Code(c) => Fail::new(status_of(c), c, Params::new()),
PkiFail::Internal(d) => Fail::new(500, "internal", Params::new()).detail(d),
}
}
impl Control {
pub fn pki_or_fail(&self) -> Result<&crate::pki::Pki, Fail> {
self.pki
.as_ref()
.ok_or_else(|| Fail::new(409, "pki.not_configured", Params::new()))
}
/// Every certificate directory a compiler output points at.
fn cert_dirs(&self) -> Vec<&Path> {
let mut v = vec![Path::new(&self.cfg.compile.cert_dir)];
let c = Path::new(&self.cfg.caddy_compile().cert_dir);
if c != v[0] {
v.push(c);
}
v
}
/// Before a tree goes live: server certificates for its `tls = "domi"` hosts and the
/// device files when a host needs them. Without `[pki]` nothing is issued (the files are
/// expected to be there, as in phase 2). Returns whether a file changed.
pub fn pki_prepare(&self, model: &ianitor_core::Model) -> Result<bool, Fail> {
let Some(p) = &self.pki else {
return Ok(false);
};
let t = now();
let domi: Vec<String> = model
.hosts()
.iter()
.filter(|h| h.tls == TlsMode::Domi)
.map(|h| h.hostname.to_string())
.collect();
let mut changed = false;
for dir in self.cert_dirs() {
let issued = p.ensure_host_certs(&domi, dir, t).map_err(|e| {
let mut f = pki_fail(e);
// The apply's reason names a host so the UI can point at it.
if let Some(h) = domi.first() {
f.reason.hostname = Some(h.clone());
}
f
})?;
if !issued.is_empty() {
log::info!(target: "ianitor::pki", "issued server certificates for {}", issued.join(", "));
changed = true;
}
// Always: the files are tiny, and a list that failed to be written catches up here.
changed |= p.write_device_files(dir, t).map_err(pki_fail)?;
}
Ok(changed)
}
/// Every couple of seconds: act on approvals; once an hour: renew server certificates.
pub async fn pki_poller(self: Arc<Self>) {
if self.pki.is_none() {
return;
}
let mut last_renewal_check = now();
// At start: bring the device files in line (a revocation that could not be written
// before a restart is in force now).
let _ = self.devices_changed().await;
loop {
tokio::time::sleep(Duration::from_secs(2)).await;
let me = self.clone();
let polled = tokio::task::spawn_blocking(move || match &me.pki {
Some(p) => p.poll(now()),
None => Ok(Default::default()),
})
.await;
let changes = match polled {
Ok(Ok(c)) => c,
Ok(Err(e)) => {
log::error!(target: "ianitor::pki", "{e}");
continue;
}
Err(e) => {
log::error!(target: "ianitor::pki", "pki poll crashed: {e}");
continue;
}
};
let t = now();
if changes.intermediate || t.saturating_sub(last_renewal_check) >= 3600 {
last_renewal_check = t;
self.refresh_certificates(changes.intermediate).await;
}
let retry = self
.devices_problem
.lock()
.map(|p| p.is_some())
.unwrap_or(false);
if changes.devices || retry {
let _ = self.devices_changed().await;
}
}
}
/// Issue what the current tree needs (after a new intermediate: everything) and reload
/// the engine that serves, under the apply lock so no trial is running.
pub async fn refresh_certificates(&self, new_intermediate: bool) {
let _lock = self.apply_lock.lock().await;
let Ok((_, _, model)) = self.head_model() else {
return;
};
match self.pki_prepare(&model) {
Ok(changed) if changed || new_intermediate => {
if new_intermediate {
log::info!(target: "ianitor::pki", "new Domi intermediate installed; certificates reissued");
}
self.reload_serving_engine().await;
}
Ok(_) => {}
Err(f) => {
log::error!(target: "ianitor::pki", "certificates not renewed: {}", f.reason.message);
}
}
}
/// The device files changed (issue or revoke): rewrite them and tell the engine at once.
///
/// It never waits for an apply (fix round 3): the files go to disk at once and edge is told
/// at once, also during a watch (edge's trial reads the same files). Only when Caddy serves
/// *and* a trial is out is the Caddy reload left to the end of that apply: a reload now
/// would drop the trial, and the end of every Caddy trial loads caddy.json again (promote,
/// revert, caddy-guard, caddy-revert), which reads the new files. During an engine switch
/// (engine lock busy for more than a second) the engine being started reads them anyway.
pub async fn devices_changed(&self) -> Result<(), String> {
let Some(p) = &self.pki else { return Ok(()) };
let _files = self.devices_lock.lock().await;
let t = now();
let mut result = Ok(());
for dir in self.cert_dirs() {
if let Err(e) = p.write_device_files(dir, t) {
result = Err(format!(
"the device files in {} could not be written: {e}",
dir.display()
));
}
}
// The engine lock is held for long only by a switch; an apply holds it for a moment
// (loading a trial, or from the claim to the promoted reload), so then this waits.
let engine =
match tokio::time::timeout(Duration::from_secs(1), self.engine_lock.lock()).await {
Ok(g) => Some(g),
Err(_) if self.engine_state().state == "switching" => None,
Err(_) => Some(self.engine_lock.lock().await),
};
// Tell the serving engine every time, changed or not: a repeated Revoke nudges again.
// During a switch it is not told now, and never silently (QC round 4): the problem
// stays set, so the retry tells whichever engine serves once the switch is over (the
// switch itself also ends by telling it).
let mut pending = None;
if result.is_ok() {
if engine.is_none() {
pending = Some(
"an engine switch is under way; the engine that serves after it is told then"
.to_owned(),
);
} else {
result = self.nudge_devices().await;
}
}
if let Ok(mut pr) = self.devices_problem.lock() {
*pr = result.as_ref().err().cloned().or(pending.clone());
}
if let Some(p) = &pending {
log::info!(target: "ianitor::pki", "{p}");
}
if let Err(e) = &result {
log::error!(target: "ianitor::pki", "{e}; retrying");
}
result
}
/// Tell the engine that serves to read the device files again. The caller holds the engine
/// lock. Under Caddy with a trial out, the end of that apply does it (promote, revert, the
/// guard and caddy-revert all load caddy.json, which reads the files).
pub(crate) async fn nudge_devices(&self) -> Result<(), String> {
let caddy = self.engine_running() == "caddy";
if caddy && crate::caddy_guard::armed(&self.cfg.state_dir).is_some() {
log::info!(target: "ianitor::pki", "a change is being tried on Caddy; Caddy reads the new device list when it ends");
Ok(())
} else if caddy {
self.caddy_reload_checked()
.await
.map_err(|e| format!("Caddy did not reload the device list: {e}"))
} else if self.edge.attached() {
self.edge
.reload_devices()
.await
.map_err(|e| format!("edge did not re-read the device list: {e}"))
} else {
Ok(())
}
}
async fn reload_serving_engine(&self) {
let _engine = self.engine_lock.lock().await;
if self.engine_running() == "caddy" {
if let Err(e) = self.caddy_reload_checked().await {
log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {e}");
}
} else if self.edge.attached()
&& let Err(e) = self.edge.reload().await
{
log::error!(target: "ianitor::pki", "edge did not reload the new certificates: {e}");
}
}
/// The code and message for a PKI request that waits for its approval.
pub fn waiting_message(&self, kind: &str, code: &str) -> (String, String) {
let manual = self.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual");
let c = match (kind, manual) {
("intermediate", _) => "pki.renew.manual",
(_, true) => "pki.waiting.manual",
(_, false) => "pki.waiting",
};
(
c.to_owned(),
messages::message(c, &messages::params([("code", code.to_owned())])),
)
}
}
+412
View File
@@ -0,0 +1,412 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Switching the engine at runtime (ROADMAP §1.6 as corrected 2026-11-07, §3, §4).
//!
//! Exactly one of `ianitor-edge.service` and `caddy-fallback.service` runs. Control may start,
//! and stop only those two, through a polkit rule scoped to exactly them (NixOS
//! module). `/var/lib/ianitor/engine` names the one to run; the `ianitor-engine-select` unit
//! reads it at boot. A switch writes the file first (so a reboot mid-switch boots the
//! target), stops the old engine, starts the new one and waits until it serves; if the new
//! one does not come up, it goes back to the old one and says so.
//!
//! Decisions (phase 3):
//! - While Caddy serves, changes keep working (Mark, 2026-11-08): an apply is loaded into Caddy
//! through its admin socket, watched through Caddy and kept or reverted (`engine/caddy_apply`).
//! - Share links are refused while Caddy serves (`share.engine_caddy`, see docs/api.md):
//! Caddy cannot check them, and control never serves visitors itself.
//! - Device revocations while Caddy serves reload Caddy's config through its admin socket.
//!
//! The systemd calls go through [`Units`], so tests use a fake.
// A refusal is built once per request; boxing it buys nothing.
#![allow(clippy::result_large_err)]
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::config::EngineConfig;
use crate::engine::{Control, Fail, reason};
use crate::messages::{self, Params};
use crate::records::Reason;
use crate::util::{now, write_atomic};
/// Start, stop and look at systemd units.
pub trait Units: Send + Sync {
fn start(&self, unit: &str) -> Result<(), String>;
fn stop(&self, unit: &str) -> Result<(), String>;
fn is_active(&self, unit: &str) -> Result<bool, String>;
}
/// `systemctl --no-ask-password <verb> <unit>`, as the control user (polkit decides).
pub struct Systemctl {
pub bin: PathBuf,
}
impl Systemctl {
fn run(&self, args: &[&str]) -> Result<std::process::Output, String> {
std::process::Command::new(&self.bin)
.arg("--no-ask-password")
.args(args)
.stdin(std::process::Stdio::null())
.output()
.map_err(|e| format!("cannot run {}: {e}", self.bin.display()))
}
fn verb(&self, verb: &str, unit: &str) -> Result<(), String> {
let o = self.run(&[verb, unit])?;
if o.status.success() {
Ok(())
} else {
Err(format!(
"systemctl {verb} {unit} failed: {}",
String::from_utf8_lossy(&o.stderr).trim()
))
}
}
}
impl Units for Systemctl {
fn start(&self, unit: &str) -> Result<(), String> {
self.verb("start", unit)
}
fn stop(&self, unit: &str) -> Result<(), String> {
self.verb("stop", unit)
}
fn is_active(&self, unit: &str) -> Result<bool, String> {
Ok(self.run(&["is-active", "--quiet", unit])?.status.success())
}
}
/// In-memory units for tests: records every call; `fail_start` makes a start fail.
#[derive(Default)]
pub struct FakeUnits {
pub calls: Mutex<Vec<String>>,
pub active: Mutex<HashSet<String>>,
pub fail_start: Mutex<HashSet<String>>,
}
impl Units for FakeUnits {
fn start(&self, unit: &str) -> Result<(), String> {
if let Ok(mut c) = self.calls.lock() {
c.push(format!("start {unit}"));
}
if self.fail_start.lock().is_ok_and(|f| f.contains(unit)) {
return Err(format!("{unit} failed to start"));
}
if let Ok(mut a) = self.active.lock() {
a.insert(unit.to_owned());
}
Ok(())
}
fn stop(&self, unit: &str) -> Result<(), String> {
if let Ok(mut c) = self.calls.lock() {
c.push(format!("stop {unit}"));
}
if let Ok(mut a) = self.active.lock() {
a.remove(unit);
}
Ok(())
}
fn is_active(&self, unit: &str) -> Result<bool, String> {
Ok(self.active.lock().is_ok_and(|a| a.contains(unit)))
}
}
/// Which engine serves, as control knows it.
#[derive(Debug, Clone)]
pub struct EngineState {
/// `pingora` or `caddy`.
pub running: String,
/// `running`, `switching` or `stopped`.
pub state: String,
pub since: u64,
/// The target while switching.
pub target: Option<String>,
/// Why the last switch did not happen.
pub last_error: Option<Reason>,
}
pub fn read_engine_file(p: &Path) -> String {
match std::fs::read_to_string(p) {
Ok(s) if s.trim() == "caddy" => "caddy".into(),
_ => "pingora".into(),
}
}
pub fn engine_name(e: &str) -> String {
if e == "caddy" { "Caddy" } else { "Pingora" }.into()
}
impl Control {
pub fn engine_cfg(&self) -> Option<&EngineConfig> {
self.cfg.engine.as_ref()
}
/// `pingora` or `caddy`.
pub fn engine_running(&self) -> String {
self.engine
.lock()
.map(|e| e.running.clone())
.unwrap_or_else(|_| "pingora".into())
}
pub fn engine_state(&self) -> EngineState {
self.engine
.lock()
.map(|e| e.clone())
.unwrap_or(EngineState {
running: "pingora".into(),
state: "running".into(),
since: 0,
target: None,
last_error: None,
})
}
fn set_engine(&self, f: impl FnOnce(&mut EngineState)) {
if let Ok(mut e) = self.engine.lock() {
f(&mut e);
}
}
/// Check a switch request and start it. Answers at once; the switch runs in the
/// background (`overview.engine.state` is `switching` until it ends).
pub fn request_switch(self: &Arc<Self>, target: &str) -> Result<EngineState, Fail> {
if self.engine_cfg().is_none() || self.units.is_none() {
return Err(Fail::new(409, "engine.unmanaged", Params::new()));
}
if target == "caddy" && !self.fallback_buildable() {
return Err(Fail::new(409, "engine.not_ready", Params::new()));
}
if target != "pingora" && target != "caddy" {
return Err(Fail::new(
422,
"request.body",
messages::params([("problem", "target must be \"pingora\" or \"caddy\".".into())]),
));
}
{
let mut e = self
.engine
.lock()
.map_err(|_| Fail::new(500, "internal", Params::new()))?;
if e.state == "switching" {
return Err(Fail::new(409, "engine.switching", Params::new()));
}
if e.running == target {
return Err(Fail::new(
409,
"engine.same",
messages::params([("engine", engine_name(target))]),
));
}
e.state = "switching".into();
e.target = Some(target.to_owned());
e.last_error = None;
}
let me = self.clone();
let t = target.to_owned();
tokio::spawn(async move { me.switch(&t).await });
Ok(self.engine_state())
}
async fn switch(self: Arc<Self>, target: &str) {
// No apply runs during a switch, and none starts.
let _lock = self.apply_lock.lock().await;
let _engine = self.engine_lock.lock().await;
let from = self.engine_running();
let res = self.switch_inner(&from, target).await;
let t = now();
match res {
Ok(()) => {
log::info!(target: "ianitor::engine", "switched from {from} to {target}");
self.set_engine(|e| {
e.running = target.to_owned();
e.state = "running".into();
e.since = t;
e.target = None;
});
}
Err(detail) => {
log::error!(target: "ianitor::engine", "switch to {target} failed: {detail}");
// Go back to what served before.
let back = self.bring_back(&from).await;
let mut r = reason(
"engine.switch_failed",
messages::params([
("engine", engine_name(target)),
("previous", engine_name(&from)),
]),
);
r.detail = Some(match back {
Ok(()) => detail,
Err(b) => format!("{detail}; going back also failed: {b}"),
});
self.set_engine(|e| {
e.running = from.clone();
e.state = "running".into();
e.target = None;
e.last_error = Some(r);
});
}
}
// Still under the engine lock: whichever engine serves now reads the device files again
// (QC round 4). A device change during the switch only wrote them; a Caddy that was
// already running, or started before they changed, would keep the old list.
if self.pki.is_some()
&& let Err(e) = self.nudge_devices().await
{
log::error!(target: "ianitor::engine", "after the switch: {e}; retrying");
if let Ok(mut p) = self.devices_problem.lock() {
*p = Some(e);
}
}
}
fn units_and_cfg(&self) -> Result<(Arc<dyn Units>, EngineConfig), String> {
match (self.units.clone(), self.engine_cfg().cloned()) {
(Some(u), Some(c)) => Ok((u, c)),
_ => Err("no engine settings".into()),
}
}
fn unit_of(cfg: &EngineConfig, engine: &str) -> String {
if engine == "caddy" {
cfg.caddy_unit.clone()
} else {
cfg.edge_unit.clone()
}
}
async fn blocking<T: Send + 'static>(
f: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> Result<T, String> {
tokio::task::spawn_blocking(f)
.await
.map_err(|e| e.to_string())?
}
async fn switch_inner(&self, from: &str, target: &str) -> Result<(), String> {
let (units, cfg) = self.units_and_cfg()?;
if target == "caddy" {
// Caddy starts from caddy.json: make sure it is the current tree's.
self.write_current_caddy()?;
}
write_atomic(&cfg.file, target.as_bytes(), 0o644)
.map_err(|e| format!("cannot write {}: {e}", cfg.file.display()))?;
let (old, new) = (Self::unit_of(&cfg, from), Self::unit_of(&cfg, target));
let u = units.clone();
Self::blocking(move || u.stop(&old)).await?;
let u = units.clone();
let n = new.clone();
Self::blocking(move || u.start(&n)).await?;
self.wait_serving(target, &units, &new).await?;
// Edge reads edge.json when it starts; tell it again in case it kept running (changes
// kept under Caddy are in edge.json).
if target == "pingora"
&& self.edge.attached()
&& let Err(e) = self.edge.reload().await
{
log::warn!(target: "ianitor::engine", "edge did not reload edge.json after the switch: {e}");
}
Ok(())
}
async fn bring_back(&self, engine: &str) -> Result<(), String> {
let (units, cfg) = self.units_and_cfg()?;
let other = if engine == "caddy" {
"pingora"
} else {
"caddy"
};
write_atomic(&cfg.file, engine.as_bytes(), 0o644).map_err(|e| e.to_string())?;
let (stop, start) = (Self::unit_of(&cfg, other), Self::unit_of(&cfg, engine));
let u = units.clone();
let _ = Self::blocking(move || u.stop(&stop)).await;
let u = units.clone();
let s = start.clone();
Self::blocking(move || u.start(&s)).await?;
self.wait_serving(engine, &units, &start).await
}
/// Until the unit is active and serves: edge answers on its admin socket, Caddy accepts
/// connections on the HTTPS address.
async fn wait_serving(
&self,
engine: &str,
units: &Arc<dyn Units>,
unit: &str,
) -> Result<(), String> {
let deadline = tokio::time::Instant::now() + Duration::from_secs(20);
let addr = if engine == "caddy" {
self.cfg.caddy_compile().https_listen
} else {
self.cfg.compile.https_listen
};
loop {
let u = units.clone();
let n = unit.to_owned();
let active = Self::blocking(move || u.is_active(&n))
.await
.unwrap_or(false);
let serving = active
&& if engine == "pingora" && self.edge.attached() {
self.edge.status().await.is_ok()
} else {
tokio::net::TcpStream::connect(addr).await.is_ok()
};
if serving {
return Ok(());
}
if tokio::time::Instant::now() > deadline {
return Err(format!("{unit} did not come up within 20 s"));
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
/// Compile the current tree for Caddy and write caddy.json (the file only ever holds a
/// kept tree, so this only matters when it is missing or older).
fn write_current_caddy(&self) -> Result<(), String> {
let (_, _, model) = self.head_model().map_err(|f| f.reason.message)?;
self.pki_prepare(&model).map_err(|f| f.reason.message)?;
let text = ianitor_core::compile::caddy(&model, &self.cfg.caddy_compile().options())
.map_err(|e| e.to_string())?;
if std::fs::read_to_string(&self.cfg.caddy.config)
.ok()
.as_deref()
!= Some(text.as_str())
{
write_atomic(&self.cfg.caddy.config, text.as_bytes(), 0o644)
.map_err(|e| e.to_string())?;
}
Ok(())
}
/// Can Caddy's settings be built from the current tree? (Otherwise `engine.not_ready`.)
pub fn fallback_buildable(&self) -> bool {
self.head_model().ok().is_some_and(|(_, _, m)| {
ianitor_core::compile::caddy(&m, &self.cfg.caddy_compile().options()).is_ok()
})
}
/// Any reason changes wait now: Caddy serving, or a pause.
pub fn effective_pause(&self) -> Option<Reason> {
self.paused()
}
}
/// What control.toml's `[engine]` asks for.
pub fn units_for(cfg: Option<&EngineConfig>) -> Option<Arc<dyn Units>> {
let c = cfg?;
match c.units.as_str() {
"systemctl" => Some(Arc::new(Systemctl {
bin: c.systemctl.clone(),
})),
_ => None,
}
}
+9 -3
View File
@@ -34,6 +34,11 @@ mod unix {
fn routes(doc: &Value) -> Vec<(String, String)> {
let mut out = Vec::new();
for (path, item) in doc["paths"].as_object().unwrap() {
// The one-time device download is the one call without a token: the link is
// the secret (G15). Every other call needs one.
if path.starts_with("/api/v1/device-bundles/") {
continue;
}
for method in ["get", "post", "put", "patch", "delete"] {
if item.get(method).is_some() {
let p = path
@@ -118,14 +123,14 @@ mod unix {
vec![("Authorization".into(), "Bearer ".into())],
"token.unknown",
),
// Identity headers do not authenticate (docs/ui-api.md G14).
// Identity headers without edge's proof are refused (docs/ui-api.md G14).
(
"remote-user".into(),
vec![
("Remote-User".into(), "mark".into()),
("Remote-Groups".into(), "admins".into()),
],
"token.missing",
"ui.no_proof",
),
];
for (what, headers, code) in &cases {
@@ -147,7 +152,8 @@ mod unix {
env.call_with("GET", "/api/v1/nope", &[], None).await.status,
401
);
assert_eq!(env.call_with("GET", "/", &[], None).await.status, 401);
// Outside /api/ only the built UI is served (no data, no token); none is set up here.
assert_eq!(env.call_with("GET", "/", &[], None).await.status, 404);
// A wrong Host header (DNS rebinding) is refused even with a good token.
let auth = format!("Bearer {}", env.token);
+7 -2
View File
@@ -66,6 +66,8 @@ pub struct EnvSpec {
pub watch_secs: u64,
pub site: String,
pub remote: Option<String>,
/// Appended to control.toml (extra sections such as [pki]).
pub extra_config: String,
}
impl Default for EnvSpec {
@@ -74,6 +76,7 @@ impl Default for EnvSpec {
watch_secs: 2,
site: String::new(),
remote: None,
extra_config: String::new(),
}
}
}
@@ -111,6 +114,8 @@ impl Env {
access_log: dir.str("logs/access.log"),
caddy_credentials_dir: dir.str("creds"),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
};
// Edge starts from an empty config; control brings it in line on its first start.
let empty = load(
@@ -202,7 +207,7 @@ caddy_credentials_dir = "{creds}"
certs = d("certs"),
edge_state = d("edge-state"),
log = d("logs/access.log"),
);
) + &spec.extra_config;
std::fs::write(self.dir.join("control.toml"), text).unwrap();
}
@@ -254,7 +259,7 @@ caddy_credentials_dir = "{creds}"
std::thread::sleep(Duration::from_millis(200));
}
fn command(&self) -> Command {
pub fn command(&self) -> Command {
let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control"));
c.env_remove("IANITOR_TEST_CRASH_AT");
c.env_remove("IANITOR_TEST_FAIL_WRITE");
File diff suppressed because it is too large Load Diff
+769
View File
@@ -0,0 +1,769 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The Domi CA through control (ROADMAP §6 phase 3, tests first): the first intermediate is
//! signed offline from control's CSR and installed; `tls = "domi"` hosts then get server
//! certificates that chain to the root; device certificates need the match code; the install
//! file works once; revocation takes the device off the allow list; no root key file is ever
//! in the state directory, and control refuses to start with one there.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common;
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux; run it in WSL2",
file!()
);
}
#[cfg(unix)]
mod unix {
use std::path::Path;
use std::time::{Duration, Instant};
use crate::common::{Env, EnvSpec};
use ianitor_core::pki;
use ianitor_testkit::client::{self, Req};
use ianitor_testkit::upstream::Echo;
use serde_json::{Value, json};
const PASSWORD: &str = "intermediate-test-password-123";
/// Whether an allow list names any device (the placeholder that keeps it from being
/// empty is not one).
fn lists_a_device(allow: &str) -> bool {
pki::chain_der(allow)
.unwrap_or_default()
.iter()
.any(|d| pki::inspect_der(d).is_ok_and(|i| i.subject_cn != pki::NO_DEVICE_CN))
}
fn now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64
}
/// The offline side: a root that lives only in this test's memory (and its cert file).
struct Offline {
root_pem: String,
root_key: pki::KeyPair,
}
async fn env_with_pki() -> (Env, Offline) {
let (root_pem, root_key) = pki::create_root(now()).unwrap();
let env = env_with_root(&root_pem).await;
(env, Offline { root_pem, root_key })
}
async fn env_with_root(root_pem: &str) -> Env {
// Only the root certificate goes next to control; the key stays in this test.
let extra = |dir: &Path| {
format!(
"\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n",
dir.join("offline-root.crt").display()
)
};
let mut env = Env::new(EnvSpec::default()).await;
std::fs::write(env.dir.join("offline-root.crt"), root_pem).unwrap();
std::fs::write(env.dir.join("creds/pki-password"), PASSWORD).unwrap();
let text = std::fs::read_to_string(env.config_path()).unwrap() + &extra(&env.dir.join("."));
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
env
}
async fn wait_request(env: &Env, id: &str, want: &str) -> Value {
let deadline = Instant::now() + Duration::from_secs(20);
loop {
let r = env
.call("GET", &format!("/api/v1/pki-requests/{id}"), None)
.await;
assert_eq!(r.status, 200, "{}", r.text);
if r.json["state"] == want {
return r.json;
}
if Instant::now() > deadline {
panic!(
"request {id} is {} not {want}\n{}",
r.json["state"],
env.control_log()
);
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
fn cli(env: &Env, args: &[&str]) -> std::process::Output {
env.command()
.args(args)
.arg("--config")
.arg(env.config_path())
.output()
.unwrap()
}
/// Renew (first intermediate), sign offline, install with the CLI.
async fn install_intermediate(env: &Env, off: &Offline) -> Value {
let r = env
.call(
"POST",
"/api/v1/certs/intermediate/renewal",
Some(json!({})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let rid = r.json["request_id"].as_str().unwrap().to_owned();
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
// The code the UI shows is the one the offline signer computes from the CSR.
assert_eq!(
r.json["match_code"].as_str().unwrap(),
pki::match_code(&pki::csr_der(&csr).unwrap())
);
let r2 = env
.call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None)
.await;
assert_eq!(
r2.status,
200,
"{}
{}
{}",
r.text,
r2.text,
env.control_log()
);
assert_eq!(r2.text, csr);
let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
let f = env.dir.join("signed.crt");
std::fs::write(&f, &signed).unwrap();
let out = cli(env, &["pki", "install", f.to_str().unwrap()]);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
wait_request(env, &rid, "approved").await
}
#[tokio::test(flavor = "multi_thread")]
async fn first_intermediate_from_an_offline_signature_then_domi_hosts_chain_to_the_root() {
let (env, off) = env_with_pki().await;
let ov = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(ov.json["intermediate"]["state"], "missing", "{}", ov.text);
// Before an intermediate exists a domi host cannot get a certificate.
let echo = Echo::start("domi").await;
let host = json!({"host": {"hostname": "fresh.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}});
let rec = env.apply("POST", "/api/v1/hosts", Some(host.clone())).await;
assert_eq!(rec["state"], "failed", "{rec}");
assert_eq!(rec["reason"]["code"], "pki.no_intermediate", "{rec}");
install_intermediate(&env, &off).await;
let ov = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(ov.json["intermediate"]["state"], "ok", "{}", ov.text);
assert!(ov.json["intermediate"]["days_left"].as_i64().unwrap() >= 364);
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log());
// The served certificate chains to the Domi root (only the root is trusted here).
let roots = ianitor_testkit::tls::roots_from_pem(&off.root_pem);
let edge = env.edge.as_ref().unwrap();
let r = client::https(
edge.https,
"fresh.test",
roots,
&Req::get("fresh.test", "/"),
)
.await
.unwrap();
assert_eq!(r.status, 200);
let crt = std::fs::read_to_string(env.dir.join("certs/fresh.test.crt")).unwrap();
let info = pki::inspect(&crt).unwrap();
assert_eq!(info.dns_names, vec!["fresh.test".to_owned()]);
assert_eq!(
(info.not_after - now()) / 86_400,
i64::from(pki::SERVER_DAYS) - 1
);
// No root key anywhere control writes. (The start of a P-256 PKCS#8 body is the same
// for every key, so the unique end is compared.)
let key_pem = off.root_key.serialize_pem();
let body: String = key_pem
.lines()
.filter(|l| !l.starts_with("-----"))
.collect();
for d in ["state", "certs", "edge", "caddy", "edge-state"] {
for f in walk(&env.dir.join(d)) {
let bytes = std::fs::read(&f).unwrap();
let text = String::from_utf8_lossy(&bytes);
assert!(
!text.contains(&body[body.len() - 40..]),
"root key material in {}",
f.display()
);
assert!(
!contains(&bytes, &off.root_key.serialize_der()),
"root key DER in {}",
f.display()
);
}
}
// The intermediate key is only stored encrypted.
let k = std::fs::read_to_string(env.dir.join("state/pki/intermediate.key")).unwrap();
assert!(k.contains(concat!("IANITOR ENCRYPTED ", "PRIVATE KEY")));
assert!(!k.contains(concat!("BEGIN ", "PRIVATE KEY")));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_wrong_certificate_is_not_installed() {
let (env, off) = env_with_pki().await;
let r = env
.call(
"POST",
"/api/v1/certs/intermediate/renewal",
Some(json!({})),
)
.await;
let rid = r.json["request_id"].as_str().unwrap().to_owned();
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
// Signed by another root.
let (other, other_key) = pki::create_root(now()).unwrap();
let wrong = pki::sign_intermediate(&other, &other_key, &csr, now()).unwrap();
let r = env
.call(
"PUT",
&format!("/api/v1/pki-requests/{rid}/certificate"),
Some(json!({"certificate_pem": wrong})),
)
.await;
assert_eq!(r.status, 422, "{}", r.text);
assert_eq!(r.json["error"]["code"], "pki.not_our_root");
// For another key.
let k = pki::generate_key().unwrap();
let other_csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
let wrong =
pki::sign_intermediate(&off.root_pem, &off.root_key, &other_csr, now()).unwrap();
let r = env
.call(
"PUT",
&format!("/api/v1/pki-requests/{rid}/certificate"),
Some(json!({"certificate_pem": wrong})),
)
.await;
assert_eq!(r.status, 422, "{}", r.text);
assert_eq!(r.json["error"]["code"], "pki.wrong_key");
// A leaf is not an intermediate.
let r = env
.call(
"PUT",
&format!("/api/v1/pki-requests/{rid}/certificate"),
Some(json!({"certificate_pem": "garbage"})),
)
.await;
assert_eq!(r.status, 422, "{}", r.text);
let st = env
.call("GET", &format!("/api/v1/pki-requests/{rid}"), None)
.await;
assert_eq!(st.json["state"], "waiting");
// The right one through the API works too.
let good = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
let r = env
.call(
"PUT",
&format!("/api/v1/pki-requests/{rid}/certificate"),
Some(json!({"certificate_pem": good})),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
assert_eq!(r.json["state"], "approved");
}
#[tokio::test(flavor = "multi_thread")]
async fn device_certificate_needs_the_match_code_and_installs_once() {
let (env, off) = env_with_pki().await;
install_intermediate(&env, &off).await;
let r = env
.call(
"POST",
"/api/v1/certs/devices",
Some(json!({"name": "Mark's phone", "kind": "phone"})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let rid = r.json["request_id"].as_str().unwrap().to_owned();
let code = r.json["match_code"].as_str().unwrap().to_owned();
assert_eq!(code.len(), 8, "{code}");
// The same name again while it waits: refused.
let again = env
.call(
"POST",
"/api/v1/certs/devices",
Some(json!({"name": "mark's PHONE", "kind": "phone"})),
)
.await;
assert_eq!(again.status, 409, "{}", again.text);
assert_eq!(again.json["error"]["code"], "pki.device_name_taken");
// A wrong code does nothing.
let wrong = if code.starts_with('0') {
"11 11 11"
} else {
"00 00 00"
};
let out = cli(&env, &["pki", "approve", wrong]);
assert!(!out.status.success());
tokio::time::sleep(Duration::from_millis(2500)).await;
let st = env
.call("GET", &format!("/api/v1/pki-requests/{rid}"), None)
.await;
assert_eq!(st.json["state"], "waiting");
let out = cli(&env, &["pki", "approve", &code]);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let done = wait_request(&env, &rid, "approved").await;
let did = done["device_id"].as_str().unwrap().to_owned();
let certs = env.call("GET", "/api/v1/certs", None).await;
assert_eq!(certs.status, 200, "{}", certs.text);
assert_eq!(certs.json["root"]["offline"], true);
let dev = certs.json["devices"]
.as_array()
.unwrap()
.iter()
.find(|d| d["id"] == did.as_str())
.unwrap()
.clone();
assert_eq!(dev["state"], "valid");
assert_eq!(dev["name"], "Mark's phone");
// The allow list both engines read has it.
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
assert!(lists_a_device(&allow));
// One-time install file.
let b = env
.call(
"POST",
&format!("/api/v1/certs/devices/{did}/bundle"),
Some(json!({"format": "qr"})),
)
.await;
assert_eq!(b.status, 200, "{}", b.text);
let url = b.json["download_url"].as_str().unwrap().to_owned();
let password = b.json["one_time_password"].as_str().unwrap().to_owned();
assert!(b.json["qr_svg"].as_str().unwrap().starts_with("<?xml"));
let path = url
.split_once("/api/v1/")
.map(|(_, p)| format!("/api/v1/{p}"))
.unwrap();
// Opening the link (GET, as a link preview or prefetcher would) shows a page and
// uses nothing up; its button posts.
for _ in 0..2 {
let g = env.call_with("GET", &path, &[], None).await;
assert_eq!(g.status, 200, "{}", g.text);
assert!(g.text.contains("<form method=\"post\">"), "{}", g.text);
assert!(g.text.contains("Mark&#39;s phone"), "{}", g.text);
}
// No token needed for the download itself (the link is the secret) ...
let d = env.call_with("POST", &path, &[], None).await;
assert_eq!(d.status, 200, "{}", d.text);
assert_eq!(d.header("content-type"), Some("application/x-pkcs12"));
let ks = p12_keystore::KeyStore::from_pkcs12(
&d.body,
&password,
p12_keystore::Pkcs12ImportPolicy::Strict,
)
.unwrap();
let (_, chain) = ks.private_key_chain().unwrap();
assert_eq!(chain.certs().len(), 3, "leaf, intermediate, root");
// ... and it works only once.
let d = env.call_with("POST", &path, &[], None).await;
assert_eq!(d.status, 410, "{}", d.text);
assert_eq!(d.json["error"]["code"], "pki.bundle_used");
let g = env.call_with("GET", &path, &[], None).await;
assert_eq!(g.status, 410, "{}", g.text);
// Revoke: off the allow list, no new install file.
let r = env
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
.await;
assert_eq!(r.status, 204, "{}", r.text);
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
assert!(!lists_a_device(&allow), "{allow}");
assert!(
allow.contains("BEGIN CERTIFICATE"),
"never empty (Caddy refuses that)"
);
let b = env
.call(
"POST",
&format!("/api/v1/certs/devices/{did}/bundle"),
Some(json!({"format": "p12"})),
)
.await;
assert_eq!(b.status, 409, "{}", b.text);
}
#[tokio::test(flavor = "multi_thread")]
async fn control_refuses_to_start_with_a_root_key_in_its_state_dir() {
let (mut env, off) = env_with_pki().await;
env.kill_control();
std::fs::write(env.dir.join("state/root.key"), off.root_key.serialize_pem()).unwrap();
// A control that does not refuse would serve forever: give it 20 s, then kill it.
let mut child = env
.command()
.arg("--config")
.arg(env.config_path())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(20);
let status = loop {
if let Some(s) = child.try_wait().unwrap() {
break Some(s);
}
if Instant::now() > deadline {
let _ = child.kill();
let _ = child.wait();
break None;
}
std::thread::sleep(Duration::from_millis(50));
};
assert!(
status.is_some_and(|s| !s.success()),
"control started with a root key in its state dir"
);
let mut err = String::new();
std::io::Read::read_to_string(&mut child.stderr.take().unwrap(), &mut err).unwrap();
assert!(err.contains("root"), "{err}");
// And the message never prints the key.
assert!(!err.contains("PRIVATE KEY"), "{err}");
}
/// The accepted manual step (Mark, 2026-11-07, Q6): the offline machine runs openssl.
/// A root made with openssl signs control's CSR with the extensions file control serves,
/// and control installs the result.
#[tokio::test(flavor = "multi_thread")]
async fn an_intermediate_signed_with_openssl_is_installed() {
let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else {
return;
};
let off = ianitor_testkit::proc::TempDir::new("openssl-root");
let run = |args: &[&str]| {
let o = std::process::Command::new(&openssl)
.args(args)
.current_dir(off.join("."))
.output()
.unwrap();
assert!(
o.status.success(),
"openssl {args:?}: {}",
String::from_utf8_lossy(&o.stderr)
);
};
run(&[
"req",
"-x509",
"-new",
"-newkey",
"ec",
"-pkeyopt",
"ec_paramgen_curve:P-256",
"-nodes",
"-keyout",
"domi-root.key",
"-out",
"domi-root.crt",
"-days",
"3653",
"-subj",
"/CN=Domi PKI Root/O=Fabrica Domi",
"-addext",
"basicConstraints=critical,CA:TRUE,pathlen:1",
"-addext",
"keyUsage=critical,keyCertSign,cRLSign",
]);
let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap();
let env = env_with_root(&root_pem).await;
let r = env
.call(
"POST",
"/api/v1/certs/intermediate/renewal",
Some(json!({})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let rid = r.json["request_id"].as_str().unwrap().to_owned();
let base = r.json["file_base"].as_str().unwrap().to_owned();
let cmd = r.json["approve_command"].as_str().unwrap().to_owned();
assert!(cmd.starts_with("openssl x509 -req"), "{cmd}");
std::fs::write(
off.join(&format!("{base}.csr")),
r.json["csr_pem"].as_str().unwrap(),
)
.unwrap();
let ext = env
.call("GET", &format!("/api/v1/pki-requests/{rid}/ext"), None)
.await;
assert_eq!(ext.status, 200, "{}", ext.text);
std::fs::write(off.join(&format!("{base}.ext")), &ext.text).unwrap();
// Exactly the command control shows.
let args: Vec<&str> = cmd.split_whitespace().skip(1).collect();
run(&args);
let signed = std::fs::read_to_string(off.join(&format!("{base}.crt"))).unwrap();
let info = pki::inspect(&signed).unwrap();
assert_eq!(info.path_len, Some(0));
let r = env
.call(
"PUT",
&format!("/api/v1/pki-requests/{rid}/certificate"),
Some(json!({"certificate_pem": signed})),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
assert_eq!(r.json["state"], "approved");
}
fn walk(dir: &Path) -> Vec<std::path::PathBuf> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
let Ok(rd) = std::fs::read_dir(&d) else {
continue;
};
for e in rd.flatten() {
let p = e.path();
if p.is_dir() {
stack.push(p);
} else if p.is_file() {
out.push(p);
}
}
}
out
}
fn contains(hay: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
/// QC: the openssl step can produce intermediates that are CA + pathlen 0 but cannot
/// issue what control issues. Control installs them and reissues every Domi host.
#[tokio::test(flavor = "multi_thread")]
async fn qc_install_refuses_intermediates_that_cannot_issue() {
let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else {
return;
};
let off = ianitor_testkit::proc::TempDir::new("qc-openssl-root");
let run = |args: &[&str]| {
let o = std::process::Command::new(&openssl)
.args(args)
.current_dir(off.join("."))
.output()
.unwrap();
assert!(
o.status.success(),
"openssl {args:?}: {}",
String::from_utf8_lossy(&o.stderr)
);
};
run(&[
"req",
"-x509",
"-new",
"-newkey",
"ec",
"-pkeyopt",
"ec_paramgen_curve:P-256",
"-nodes",
"-keyout",
"domi-root.key",
"-out",
"domi-root.crt",
"-days",
"3653",
"-subj",
"/CN=Domi PKI Root/O=Fabrica Domi",
"-addext",
"basicConstraints=critical,CA:TRUE,pathlen:1",
"-addext",
"keyUsage=critical,keyCertSign,cRLSign",
]);
let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap();
let env = env_with_root(&root_pem).await;
let good = "basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\n";
let cases = [
(
"keyUsage without keyCertSign",
"basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, digitalSignature\n",
"365",
),
(
"EKU serverAuth only (devices cannot chain)",
"basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\nextendedKeyUsage = serverAuth\n",
"365",
),
("valid past the root (-days 4000)", good, "4000"),
];
let mut accepted = Vec::new();
for (label, ext, days) in cases {
let r = env
.call(
"POST",
"/api/v1/certs/intermediate/renewal",
Some(json!({})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let rid = r.json["request_id"].as_str().unwrap().to_owned();
std::fs::write(off.join("q.csr"), r.json["csr_pem"].as_str().unwrap()).unwrap();
std::fs::write(off.join("q.ext"), ext).unwrap();
run(&[
"x509",
"-req",
"-in",
"q.csr",
"-CA",
"domi-root.crt",
"-CAkey",
"domi-root.key",
"-days",
days,
"-sha256",
"-extfile",
"q.ext",
"-out",
"q.crt",
]);
let signed = std::fs::read_to_string(off.join("q.crt")).unwrap();
let r = env
.call(
"PUT",
&format!("/api/v1/pki-requests/{rid}/certificate"),
Some(json!({"certificate_pem": signed})),
)
.await;
eprintln!("QC {label}: {} {}", r.status, r.json["state"]);
if r.status == 200 {
accepted.push(label);
}
}
assert!(
accepted.is_empty(),
"control installed unusable intermediates: {accepted:?}"
);
}
/// QC: the root key name that `ianitor-control ca init` and docs/pki.md's openssl
/// command write is `domi-root.key`.
#[test]
fn qc_root_key_check_finds_the_names_ianitor_itself_uses() {
let d = ianitor_testkit::proc::TempDir::new("qc-rootkey");
let mut missed = Vec::new();
for name in [
"domi-root.key",
"offline/domi-root.key",
"Domi_Root_CA.pem",
"ca.key",
] {
let p = d.join(name);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(
&p,
// (Split so that this file does not match the pre-commit hook itself.)
concat!(
"-----BEGIN ",
"PRIVATE KEY-----\nx\n-----END ",
"PRIVATE KEY-----\n"
),
)
.unwrap();
if ianitor_control::pki::root_key_files(&d.join(".")).is_empty() {
missed.push(name);
}
std::fs::remove_file(&p).unwrap();
}
assert!(missed.is_empty(), "root_key_files missed: {missed:?}");
}
/// QC M2: a revocation that cannot be written (or not told to edge) must not answer 204 and
/// be forgotten. It answers an error, the certificates screen says so, and once the disk
/// works again (here: a restart without the fault) the allow list catches up; a repeated
/// DELETE nudges again.
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_that_cannot_be_written_is_an_error_and_catches_up() {
let (mut env, off) = env_with_pki().await;
install_intermediate(&env, &off).await;
let r = env
.call(
"POST",
"/api/v1/certs/devices",
Some(json!({"name": "tablet", "kind": "phone"})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let rid = r.json["request_id"].as_str().unwrap().to_owned();
let code = r.json["match_code"].as_str().unwrap().to_owned();
assert!(cli(&env, &["pki", "approve", &code]).status.success());
let done = wait_request(&env, &rid, "approved").await;
let did = done["device_id"].as_str().unwrap().to_owned();
let allow_file = env.dir.join("certs/domi-devices.pem");
let on_list = || lists_a_device(&std::fs::read_to_string(&allow_file).unwrap_or_default());
let deadline = Instant::now() + Duration::from_secs(10);
while !on_list() {
assert!(
Instant::now() < deadline,
"the device never reached the allow list"
);
tokio::time::sleep(Duration::from_millis(200)).await;
}
// From now on the allow list cannot be written.
env.kill_control();
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "domi-devices.pem")]);
let d = env
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
.await;
assert_eq!(d.status, 503, "{}", d.text);
assert_eq!(
d.json["error"]["code"], "pki.devices_unwritten",
"{}",
d.text
);
// The certificates screen keeps saying so; the device is still on the list.
let c = env.call("GET", "/api/v1/certs", None).await;
assert_eq!(
c.json["devices_problem"]["code"], "pki.devices_unwritten",
"{}",
c.text
);
assert!(on_list());
// The disk works again: the list catches up by itself, without another Revoke.
env.kill_control();
env.start_control(None);
let deadline = Instant::now() + Duration::from_secs(10);
while on_list() {
assert!(Instant::now() < deadline, "the revocation never caught up");
tokio::time::sleep(Duration::from_millis(200)).await;
}
// A repeated Revoke is fine and nudges the engine again.
let d = env
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
.await;
assert_eq!(d.status, 204, "{}", d.text);
let c = env.call("GET", "/api/v1/certs", None).await;
assert!(c.json["devices_problem"].is_null(), "{}", c.text);
}
}
+283
View File
@@ -0,0 +1,283 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Sign-in for the web UI (G14, tests first). The UI reaches control through edge on the
//! admin host, behind Authelia; edge adds a per-boot secret header (`X-Ianitor-Proof`, from a
//! systemd credential only edge and control can read). Control trusts `Remote-User` only on a
//! request that carries that proof: any local process can send `Remote-User` to loopback, but
//! none can send the proof. API tokens keep working for scripts.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common;
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux; run it in WSL2",
file!()
);
}
#[cfg(unix)]
mod unix {
use crate::common::{Env, EnvSpec};
use ianitor_testkit::authelia::MockAuthelia;
use ianitor_testkit::client::{self, Req};
use serde_json::json;
const PROOF: &str = "per-boot-proof-0123456789abcdef0123456789abcdef";
async fn env(site: String) -> Env {
env_for(site, "ui.test").await
}
async fn env_for(site: String, ui_host: &str) -> Env {
let mut env = Env::new(EnvSpec {
site,
..Default::default()
})
.await;
std::fs::write(env.dir.join("creds/ui-proof"), format!("{PROOF}\n")).unwrap();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!("\n[ui]\nhostname = \"{ui_host}\"\nproof_credential = \"ui-proof\"\n");
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
env
}
#[tokio::test(flavor = "multi_thread")]
async fn a_forged_remote_user_without_the_proof_gets_401() {
let env = env(String::new()).await;
for headers in [
vec![("Remote-User", "mark")],
vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "guess")],
vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "")],
vec![("remote-user", "mark"), ("Remote-Groups", "admins")],
] {
let r = env
.call_with("GET", "/api/v1/overview", &headers, None)
.await;
assert_eq!(r.status, 401, "{headers:?}: {}", r.text);
assert_eq!(r.json["error"]["code"], "ui.no_proof", "{}", r.text);
}
// A valid API token does not make a forged identity acceptable either.
let auth = format!("Bearer {}", env.token);
let r = env
.call_with(
"GET",
"/api/v1/overview",
&[("Authorization", &auth), ("Remote-User", "mark")],
None,
)
.await;
assert_eq!(r.status, 401, "{}", r.text);
// Nothing was trusted: the log does not show the forged user as an actor.
assert!(!env.control_log().contains("by mark"));
}
#[tokio::test(flavor = "multi_thread")]
async fn the_proof_with_a_remote_user_signs_the_ui_in() {
let env = env(String::new()).await;
let ok = [("Remote-User", "mark"), ("X-Ianitor-Proof", PROOF)];
let r = env.call_with("GET", "/api/v1/overview", &ok, None).await;
assert_eq!(r.status, 200, "{}", r.text);
// Through edge the Host is the admin host's.
let r = env
.call_with(
"GET",
"/api/v1/overview",
&[
("Remote-User", "mark"),
("X-Ianitor-Proof", PROOF),
("Host", "ui.test"),
],
None,
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
// Writes need the UI header (CSRF), browser or not.
let r = env
.call_with(
"POST",
"/api/v1/tokens",
&ok,
Some(json!({"name": "from ui"})),
)
.await;
assert_eq!(r.status, 403, "{}", r.text);
assert_eq!(r.json["error"]["code"], "request.csrf");
let mut w = ok.to_vec();
w.push(("X-Ianitor-UI", "1"));
let r = env
.call_with(
"POST",
"/api/v1/tokens",
&w,
Some(json!({"name": "from ui"})),
)
.await;
assert_eq!(r.status, 201, "{}", r.text);
// The proof without a user is not a sign-in.
let r = env
.call_with(
"GET",
"/api/v1/overview",
&[("X-Ianitor-Proof", PROOF)],
None,
)
.await;
assert_eq!(r.status, 401, "{}", r.text);
assert_eq!(r.json["error"]["code"], "ui.no_user");
// API tokens still work for scripts.
let r = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(r.status, 200, "{}", r.text);
}
#[tokio::test(flavor = "multi_thread")]
async fn through_edge_authelia_decides_and_a_client_cannot_bring_its_own_proof() {
let auth = MockAuthelia::start().await;
let site = format!(
"secrets = [\"ui-proof\"]\n[forward_auth]\nurl = \"{}\"\n",
auth.url()
);
let env = env_for(site, "a.test").await;
// The admin host: forward-auth, upstream control, the proof header from the secret.
let host = json!({"host": {
"hostname": "a.test", "upstreams": [format!("http://{}", env.api)],
"tls": "domi", "auth": "forward-auth",
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
}});
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log());
let edge = env.edge.as_ref().unwrap();
let roots = env.ca.roots();
// Signed in at Authelia (mock: alice): the UI gets in.
let r = client::https(
edge.https,
"a.test",
roots.clone(),
&Req::get("a.test", "/api/v1/overview").header("cookie", "authelia_session=good"),
)
.await
.unwrap();
assert_eq!(r.status, 200, "{}", r.text());
assert!(r.text().contains("\"hosts\""), "{}", r.text());
// Not signed in: Authelia's answer, control never sees it.
let r = client::https(
edge.https,
"a.test",
roots.clone(),
&Req::get("a.test", "/api/v1/overview"),
)
.await
.unwrap();
assert_ne!(r.status, 200);
// A client that sends its own proof and user gets neither through: edge replaces
// the proof with the real one only after Authelia allowed the request, and strips
// Remote-* from clients.
let r = client::https(
edge.https,
"a.test",
roots,
&Req::get("a.test", "/api/v1/overview")
.header("x-ianitor-proof", "guess")
.header("remote-user", "mallory"),
)
.await
.unwrap();
assert_ne!(r.status, 200);
}
/// QC: an admin host (the proof header rule) without forward-auth. Edge strips Remote-*
/// only on forward-auth hosts and sets the proof on every request, so any client that
/// can reach the host names any user. Control accepts such a host file.
#[tokio::test(flavor = "multi_thread")]
async fn qc_proof_on_a_host_without_forward_auth_is_refused() {
let env = env_for("secrets = [\"ui-proof\"]\n".into(), "a.test").await;
let host = json!({"host": {
"hostname": "a.test", "upstreams": [format!("http://{}", env.api)],
"tls": "domi", "auth": "none",
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
}});
let r = env.call("POST", "/api/v1/hosts", Some(host)).await;
// Refused at the door: the proof belongs to the [ui] host behind forward-auth.
assert_eq!(r.status, 422, "{}", r.text);
assert_eq!(
r.json["errors"][0]["code"], "host.header.proof",
"{}",
r.text
);
assert!(
env.call("GET", "/api/v1/hosts/a.test", None).await.status == 404,
"the host went live"
);
if r.status != 202 {
return;
}
let edge = env.edge.as_ref().unwrap();
let r = client::https(
edge.https,
"a.test",
env.ca.roots(),
&Req::new("POST", "a.test", "/api/v1/tokens")
.body(br#"{"name":"pwned"}"#)
.header("content-type", "application/json")
.header("x-ianitor-ui", "1")
.header("remote-user", "mallory"),
)
.await
.unwrap();
eprintln!("QC POST /tokens as mallory: {} {}", r.status, r.text());
assert_ne!(
r.status,
201,
"a client minted an API token as mallory: {}",
r.text()
);
}
/// QC: signed in at Authelia (alice) but the client also sends a proof guess: edge must
/// replace, not append, the proof; and Remote-User must be Authelia's.
#[tokio::test(flavor = "multi_thread")]
async fn qc_signed_in_client_with_own_proof_and_user_is_alice() {
let auth = MockAuthelia::start().await;
let site = format!(
"secrets = [\"ui-proof\"]\n[forward_auth]\nurl = \"{}\"\n",
auth.url()
);
let env = env_for(site, "a.test").await;
let host = json!({"host": {
"hostname": "a.test", "upstreams": [format!("http://{}", env.api)],
"tls": "domi", "auth": "forward-auth",
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
}});
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
assert_eq!(rec["state"], "kept", "{rec}");
let edge = env.edge.as_ref().unwrap();
let r = client::https(
edge.https,
"a.test",
env.ca.roots(),
&Req::get("a.test", "/api/v1/overview")
.header("cookie", "authelia_session=good")
.header("x-ianitor-proof", "guess")
.header("remote-user", "mallory")
.header("remote-name", "Mallory"),
)
.await
.unwrap();
assert_eq!(r.status, 200, "{}", r.text());
eprintln!(
"QC viewer: {}",
r.text()[r.text().find("\"viewer\"").unwrap_or(0)..]
.chars()
.take(80)
.collect::<String>()
);
assert!(!r.text().contains("allory"), "{}", r.text());
}
}
+5
View File
@@ -16,6 +16,11 @@ url.workspace = true
ring.workspace = true
base64.workspace = true
unicode-normalization = "0.1.24"
domi-pki.workspace = true
[dev-dependencies]
rustls-pki-types.workspace = true
webpki = { package = "rustls-webpki", version = "0.103", default-features = false, features = ["ring", "std"] }
[lints]
workspace = true
+56 -9
View File
@@ -10,7 +10,7 @@
use serde_json::{Map, Value, json};
use super::{CompileOptions, join, strip_headers};
use super::{CompileOptions, DEVICE_ALLOW_FILE, DEVICE_CA_FILE, join, strip_headers};
use crate::{
AccessLog, AuthMode, ForwardAuth, HeaderRule, HeaderValue, Host, Model, Scheme, TlsMode,
Upstream,
@@ -26,9 +26,13 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
root.insert(
"admin".into(),
match o.caddy_admin {
Some(addr) => json!({ "listen": addr.to_string() }),
None => json!({ "disabled": true }),
match (&o.caddy_admin_socket, o.caddy_admin) {
// Only the ianitor group (control) can reach it; no TCP port for local processes.
(Some(s), _) => {
json!({ "listen": format!("unix//{}|0660", s.trim_start_matches('/')) })
}
(None, Some(addr)) => json!({ "listen": addr.to_string() }),
(None, None) => json!({ "disabled": true }),
},
);
root.insert(
@@ -52,13 +56,23 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
routes.push(not_found());
let domi: Vec<&Host> = hosts.iter().filter(|h| h.tls == TlsMode::Domi).collect();
let mut policies: Vec<Value> = domi
// One policy per host that needs one: a Domi certificate, device certificates, or both.
let mut policies: Vec<Value> = hosts
.iter()
.filter(|h| h.tls == TlsMode::Domi || h.device_certs)
.map(|h| {
json!({
"match": { "sni": [h.hostname.as_str()] },
"certificate_selection": { "any_tag": [cert_tag(h)] }
})
let mut p = Map::new();
p.insert("match".into(), json!({ "sni": [h.hostname.as_str()] }));
if h.tls == TlsMode::Domi {
p.insert(
"certificate_selection".into(),
json!({ "any_tag": [cert_tag(h)] }),
);
}
if h.device_certs {
p.insert("client_authentication".into(), client_auth(o));
}
Value::Object(p)
})
.collect();
policies.push(json!({}));
@@ -75,6 +89,18 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
}),
);
https.insert("protocols".into(), json!(["h1", "h2"]));
if !o.trusted_proxies.is_empty() {
// Like edge: X-Forwarded-For from these peers names the client (logs, `client_ip`).
https.insert(
"trusted_proxies".into(),
json!({
"source": "static",
"ranges": o.trusted_proxies.iter().map(ToString::to_string).collect::<Vec<_>>()
}),
);
https.insert("client_ip_headers".into(), json!(["X-Forwarded-For"]));
https.insert("trusted_proxies_strict".into(), json!(1));
}
if !logged.is_empty() {
let names: Map<String, Value> = logged
.iter()
@@ -203,6 +229,14 @@ fn logging(file: &str) -> Value {
fn host_route(h: &Host, fa: Option<&ForwardAuth>, o: &CompileOptions) -> Value {
let mut steps = Vec::new();
if h.device_certs {
// No client certificate on this connection: 403, like edge. A certificate that is not
// trusted or not on the allow list never gets this far (the handshake fails).
steps.push(json!({
"match": [{ "vars": { "{http.request.tls.client.fingerprint}": [""] } }],
"handle": [{ "handler": "static_response", "status_code": 403 }]
}));
}
if let (AuthMode::ForwardAuth, Some(fa)) = (h.auth, fa) {
// Client-sent identity headers never reach the auth server or the upstream.
steps.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": strip_headers(fa) } }] }));
@@ -339,3 +373,16 @@ fn forward_auth(fa: &ForwardAuth) -> Value {
);
Value::Object(rp)
}
/// Device certificates: optional in the handshake (a missing one is a 403 in the route, as in
/// edge), but one that is presented must chain to the Domi CA bundle and be on the allow list.
fn client_auth(o: &CompileOptions) -> Value {
json!({
"ca": { "provider": "file", "pem_files": [join(&o.cert_dir, DEVICE_CA_FILE)] },
"verifiers": [{
"verifier": "leaf",
"leaf_certs_loaders": [{ "loader": "file", "files": [join(&o.cert_dir, DEVICE_ALLOW_FILE)] }]
}],
"mode": "verify_if_given"
})
}
+13 -3
View File
@@ -4,10 +4,10 @@
//! Model → [`EdgeConfig`] for the Pingora data plane.
use super::{CompileOptions, join, strip_headers};
use super::{CompileOptions, DEVICE_ALLOW_FILE, DEVICE_CA_FILE, join, strip_headers};
use crate::edge_config::{
EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeForwardAuth, EdgeHeaderOp, EdgeHealthCheck,
EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeDeviceCerts, EdgeForwardAuth, EdgeHeaderOp,
EdgeHealthCheck, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
};
use crate::{AccessLog, AuthMode, HeaderRule, HeaderValue, Model, Scheme, TlsMode, Upstream};
@@ -26,6 +26,15 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
directory: site.acme.directory.clone(),
email: site.acme.email.clone(),
}),
device_certs: model
.hosts()
.iter()
.any(|h| h.device_certs)
.then(|| EdgeDeviceCerts {
ca: join(&o.cert_dir, DEVICE_CA_FILE),
allow: join(&o.cert_dir, DEVICE_ALLOW_FILE),
}),
trusted_proxies: o.trusted_proxies.iter().map(ToString::to_string).collect(),
forward_auth: site.forward_auth.as_ref().map(|fa| EdgeForwardAuth {
upstream: upstream(&fa.upstream),
path_and_query: fa.path_and_query.clone(),
@@ -55,6 +64,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
}),
access_log: h.access_log == AccessLog::Truncated,
share_links: h.share_links,
device_certs: h.device_certs,
})
.collect(),
}
+18
View File
@@ -17,6 +17,11 @@
mod caddy;
mod edge;
/// In the certificate directory: the CA bundle for device certificates (written by control).
pub const DEVICE_CA_FILE: &str = "domi-devices-ca.pem";
/// In the certificate directory: every allowed (issued, not revoked) device certificate.
pub const DEVICE_ALLOW_FILE: &str = "domi-devices.pem";
use std::net::SocketAddr;
use crate::Model;
@@ -36,6 +41,13 @@ pub struct CompileOptions {
pub caddy_credentials_dir: String,
/// Caddy admin endpoint; `None` disables the admin API.
pub caddy_admin: Option<SocketAddr>,
/// Caddy admin endpoint on a Unix socket (mode 0660), which control uses to load a changed
/// config while Caddy serves. Takes precedence over `caddy_admin`.
pub caddy_admin_socket: Option<String>,
/// Peers whose `X-Forwarded-For` is believed (a proxy in front, such as Caddy beside
/// Ianitor on loopback): the share-link throttle and the access log then see the real
/// client. Empty (the default): only the connection's own address counts.
pub trusted_proxies: Vec<std::net::IpAddr>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
@@ -68,6 +80,12 @@ pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileE
}
fn check_options(o: &CompileOptions) -> Result<(), CompileError> {
if let Some(s) = &o.caddy_admin_socket {
check_path(s).map_err(|reason| CompileError::BadOption {
option: "caddy_admin_socket",
reason,
})?;
}
for (option, value) in [
("cert_dir", &o.cert_dir),
("state_dir", &o.state_dir),
+19 -1
View File
@@ -9,7 +9,7 @@
use serde::{Deserialize, Serialize};
/// Bumped on any incompatible change; edge refuses other versions.
pub const EDGE_CONFIG_VERSION: u32 = 2;
pub const EDGE_CONFIG_VERSION: u32 = 3;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -29,6 +29,11 @@ pub struct EdgeConfig {
pub access_log: String,
pub acme: Option<EdgeAcme>,
pub forward_auth: Option<EdgeForwardAuth>,
/// Device certificates (mTLS); present when any host has `device_certs`.
pub device_certs: Option<EdgeDeviceCerts>,
/// Peers whose `X-Forwarded-For` is believed (IP addresses); empty: none.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub trusted_proxies: Vec<String>,
/// Sorted by hostname.
pub hosts: Vec<EdgeHost>,
}
@@ -106,4 +111,17 @@ pub struct EdgeHost {
/// Share-link tokens (see `ianitor_core::share`) let visitors in on this host without
/// forward-auth. Checked against the key credential and the revocation file.
pub share_links: bool,
/// Only visitors with an allowed Domi device certificate get in (403 otherwise).
pub device_certs: bool,
}
/// Where edge finds what it needs to check device certificates. Both files are written by
/// control: the CA bundle (the Domi intermediates that issue device certificates) and the
/// allow list (every device certificate that is issued and not revoked, PEM). A certificate
/// that chains to the bundle but is not on the list is refused in the handshake.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeDeviceCerts {
pub ca: String,
pub allow: String,
}
+7
View File
@@ -170,6 +170,10 @@ pub enum ValidationError {
BadHealthCheck { file: String, reason: &'static str },
#[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")]
ForwardAuthNotConfigured { file: String },
#[error(
"{file}: only a host behind sign-in (auth = \"forward-auth\") may send the `ui-proof` secret; it is the web UI's admin host"
)]
ProofWithoutSignIn { file: String },
#[error("{file}: forward_auth is not usable: {reason}")]
BadForwardAuth { file: String, reason: &'static str },
#[error("{file}: acme is not usable: {reason}")]
@@ -211,6 +215,7 @@ impl ValidationError {
| E::BadHeaderRule { file, .. }
| E::BadHealthCheck { file, .. }
| E::ForwardAuthNotConfigured { file }
| E::ProofWithoutSignIn { file }
| E::BadForwardAuth { file, .. }
| E::BadAcme { file, .. } => file,
E::DuplicateHostname { second, .. } => second,
@@ -296,6 +301,7 @@ impl ValidationError {
}
E::BadHealthCheck { .. } => "host.health.path",
E::ForwardAuthNotConfigured { .. } => "host.auth.not_configured",
E::ProofWithoutSignIn { .. } => "host.header.proof",
E::BadForwardAuth { .. } => "site.forward_auth",
E::BadAcme { .. } => "site.acme",
}
@@ -331,6 +337,7 @@ impl ValidationError {
}
E::BadHealthCheck { .. } => Some("health_check.path".into()),
E::ForwardAuthNotConfigured { .. } => Some("auth".into()),
E::ProofWithoutSignIn { .. } => Some("auth".into()),
_ => None,
}
}
+3 -1
View File
@@ -12,6 +12,7 @@ pub mod compile;
pub mod edge_config;
mod error;
mod model;
pub mod pki;
pub mod routes;
pub mod share;
pub mod time;
@@ -21,6 +22,7 @@ pub use error::{ValidationError, ValidationErrors};
pub use model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES,
MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream,
UpstreamHost,
};
pub use validate::{SourceFile, load};
+6
View File
@@ -171,6 +171,8 @@ pub struct Host {
pub health_check: Option<HealthCheck>,
pub share_links: bool,
pub access_log: AccessLog,
/// Visitors must present a Domi device certificate (mTLS) that is on the allow list.
pub device_certs: bool,
}
/// The forward-auth endpoint (Authelia's `/api/authz/forward-auth`).
@@ -217,6 +219,10 @@ impl Model {
}
}
/// The secret that carries the web UI's per-boot proof (docs/api.md, "Sign-in"). Only the admin
/// host, behind forward-auth, may send it.
pub const UI_PROOF_SECRET: &str = "ui-proof";
/// Let's Encrypt production directory, the default when `[acme] directory` is not set.
pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/directory";
/// Let's Encrypt staging directory.
+366
View File
@@ -0,0 +1,366 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The Domi CA (ROADMAP §1.1, §1.2, §1.8, §3), as Ianitor uses it. The CA itself lives in the
//! 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
//! Domi PKI Root 10 years, pathLen 1 created offline, never on the server
//! └ Ianitor Domi Intermediate 1 year, pathLen 0 key encrypted at rest on the server
//! ├ <hostname> 90 days, serverAuth tls = "domi" hosts
//! └ <device name> 1 year, clientAuth mTLS for hosts with device_certs
//! ```
//!
//! Lifetimes (decided in phase 3):
//! - Server certificates: 90 days, renewed by control when 30 days are left. Control renews
//! them by itself, so a short life costs nothing and bounds the damage of a key read from the
//! certificate directory; 30 days of slack survive a long control outage.
//! - Device certificates: 1 year. Installing one is a deliberate, manual step on a phone or a
//! laptop (ROADMAP §4 accepts a 4th click for it), so it should not come round more than
//! once a year; revocation (the allow list edge and Caddy check) covers a lost device.
//! - No certificate is ever issued past its issuer's `notAfter`.
//!
//! The intermediate is never made from what a CSR asks for: only its public key and its
//! subject CN are taken; every extension comes from the profile in `domi-pki`.
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use ring::rand::{SecureRandom, SystemRandom};
pub use domi_pki::{
CertInfo, DEVICE_DAYS, EkuInfo, INTERMEDIATE_DAYS, INTERMEDIATE_OPENSSL_EXT, KeyPair,
KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem,
match_code, openssl_sign_command, sha256_hex,
};
/// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this.
pub const INTERMEDIATE_CN: &str = domi_pki::IANITOR_INTERMEDIATE_CN;
/// PBKDF2-HMAC-SHA256 iterations for encrypted keys (OWASP 2023 figure).
pub const KEY_KDF_ITERATIONS: u32 = 600_000;
// Split so that this file does not match the pre-commit hook itself.
const ARMOR_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----");
const ARMOR_END: &str = concat!("-----END IANITOR ENCRYPTED ", "PRIVATE KEY-----");
const KEY_MAGIC: &[u8; 4] = b"IEK1";
const KEY_AAD: &[u8] = b"ianitor encrypted key v1";
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum PkiError {
#[error("the certificate cannot be read: {0}")]
BadCertificate(String),
#[error("the certificate signing request cannot be read or its signature is wrong")]
BadCsr,
#[error("the request's subject must start with \"{INTERMEDIATE_CN}\"")]
CsrSubject,
#[error("the private key cannot be read")]
BadKey,
#[error("the certificate is not a CA certificate")]
NotCa,
#[error("the private key does not belong to the certificate")]
KeyMismatch,
#[error("the issuing certificate has expired or is not valid yet")]
IssuerExpired,
#[error("the name cannot be used in a certificate: {0}")]
BadName(String),
#[error("the encrypted key cannot be read")]
BadSealedKey,
#[error("the password does not open the encrypted key")]
WrongPassword,
#[error("no randomness available")]
Random,
#[error("the certificate could not be made: {0}")]
Build(String),
}
impl From<domi_pki::PkiError> for PkiError {
fn from(e: domi_pki::PkiError) -> PkiError {
use domi_pki::PkiError as D;
match e {
D::BadCertificate(s) => PkiError::BadCertificate(s),
D::BadCsr => PkiError::BadCsr,
D::CsrSubject => PkiError::CsrSubject,
D::BadKey | D::UnsupportedKey => PkiError::BadKey,
D::NotCa => PkiError::NotCa,
D::KeyMismatch => PkiError::KeyMismatch,
D::IssuerExpired => PkiError::IssuerExpired,
D::BadName(s) => PkiError::BadName(s),
D::Random => PkiError::Random,
D::Build(s) | D::Signer(s) => PkiError::Build(s),
other => PkiError::Build(other.to_string()),
}
}
}
pub fn generate_key() -> Result<KeyPair, PkiError> {
Ok(domi_pki::generate_key()?)
}
fn random<const N: usize>() -> Result<[u8; N], PkiError> {
let mut b = [0u8; N];
SystemRandom::new()
.fill(&mut b)
.map_err(|_| PkiError::Random)?;
Ok(b)
}
// ------------------------------------------------------------------ root (offline)
/// Create the root: a self-signed CA, `pathLenConstraint 1`, about 10 years. For the offline
/// machine only (`ianitor-control ca init`); control never calls this on the server.
pub fn create_root(now: i64) -> Result<(String, KeyPair), PkiError> {
Ok(domi_pki::create_root_local(now)?)
}
/// Common name of [`no_device_placeholder`].
pub const NO_DEVICE_CN: &str = "Ianitor placeholder: no device is allowed";
/// The allow list's only entry while no device is enrolled. Caddy refuses to load an empty
/// leaf list (and with it the whole config), so the list is never empty: this self-signed
/// certificate's key is dropped right away, so no client can ever present it, and it is not
/// issued by the Domi intermediate, so edge refuses it too.
pub fn no_device_placeholder(now: i64) -> Result<String, PkiError> {
Ok(domi_pki::placeholder_leaf(NO_DEVICE_CN, now)?)
}
/// A CSR for a new intermediate key (made by control on the server).
pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> {
Ok(domi_pki::intermediate_csr(key, cn)?)
}
/// Sign an intermediate CSR with the root (offline, or in Custos once it can). Only the CSR's
/// public key and CN are used; the CN must start with [`INTERMEDIATE_CN`].
pub fn sign_intermediate(
root_cert_pem: &str,
root_key: &KeyPair,
csr_pem: &str,
now: i64,
) -> Result<String, PkiError> {
Ok(domi_pki::sign_intermediate(
root_cert_pem,
root_key,
csr_pem,
INTERMEDIATE_CN,
now,
)?)
}
// ------------------------------------------------------------------ the intermediate
/// The intermediate as control holds it: its certificate and its key, checked to belong
/// together and to be a CA.
#[derive(Debug)]
pub struct Intermediate(domi_pki::Intermediate);
impl Intermediate {
pub fn new(cert_pem: &str, key: KeyPair) -> Result<Intermediate, PkiError> {
Ok(Intermediate(domi_pki::Intermediate::new(cert_pem, key)?))
}
pub fn cert_pem(&self) -> &str {
self.0.cert_pem()
}
pub fn not_after(&self) -> i64 {
self.0.not_after()
}
pub fn info(&self) -> &CertInfo {
self.0.info()
}
pub fn key(&self) -> &KeyPair {
self.0.key()
}
/// The shared crate's intermediate.
pub fn inner(&self) -> &domi_pki::Intermediate {
&self.0
}
}
pub use domi_pki::Issued;
/// A server certificate for one hostname (`tls = "domi"`). The hostname must already be
/// validated by the schema; it is checked again here.
pub fn issue_server(int: &Intermediate, hostname: &str, now: i64) -> Result<Issued, PkiError> {
Ok(domi_pki::issue_server(&int.0, hostname, now)?)
}
/// A device certificate (mTLS client) for a named device.
pub fn issue_device(int: &Intermediate, name: &str, now: i64) -> Result<Issued, PkiError> {
Ok(domi_pki::issue_device(&int.0, name, now)?)
}
// ------------------------------------------------------------------ reading certificates
/// The DER of every certificate in a PEM chain, in order.
pub fn chain_der(pem: &str) -> Result<Vec<Vec<u8>>, PkiError> {
Ok(domi_pki::chain_der(pem)?)
}
/// The first certificate of a PEM chain, as PEM.
pub fn first_pem(pem: &str) -> Result<String, PkiError> {
Ok(domi_pki::first_pem(pem)?)
}
/// Read the first certificate of a PEM chain.
pub fn inspect(pem: &str) -> Result<CertInfo, PkiError> {
Ok(domi_pki::inspect(pem)?)
}
pub fn inspect_der(der: &[u8]) -> Result<CertInfo, PkiError> {
Ok(domi_pki::inspect_der(der)?)
}
/// Why a signed certificate cannot be the Domi intermediate, or `None` when it can. It must
/// be signed by the root, a CA with path length 0 that may sign certificates (keyCertSign),
/// allowed to issue both server and device certificates (no extendedKeyUsage, or one that
/// allows both), valid now, and no longer than the root.
pub fn intermediate_problem(cert_pem: &str, root_pem: &str, now: i64) -> Option<&'static str> {
domi_pki::intermediate_problem(cert_pem, root_pem, INTERMEDIATE_CN, now)
}
/// SubjectPublicKeyInfo DER of the first certificate.
pub fn public_key_der(pem: &str) -> Result<Vec<u8>, PkiError> {
Ok(domi_pki::public_key_der(pem)?)
}
/// Is `child` (first certificate) signed by the key of `issuer` (first certificate), and
/// does its issuer name match? A CA flag on the issuer is required.
pub fn issued_by(child_pem: &str, issuer_pem: &str) -> Result<bool, PkiError> {
Ok(domi_pki::issued_by(child_pem, issuer_pem)?)
}
/// 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> {
Ok(domi_pki::csr_public_key_der(csr_pem)?)
}
/// DER of the first PEM block of a CSR (for the match code).
pub fn csr_der(csr_pem: &str) -> Result<Vec<u8>, PkiError> {
Ok(domi_pki::csr_der(csr_pem)?)
}
// ------------------------------------------------------------------ encrypted keys
fn derive(
password: &[u8],
salt: &[u8],
iterations: u32,
) -> Result<ring::aead::LessSafeKey, PkiError> {
let n = std::num::NonZeroU32::new(iterations).ok_or(PkiError::BadSealedKey)?;
let mut k = [0u8; 32];
ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, n, salt, password, &mut k);
let unbound = ring::aead::UnboundKey::new(&ring::aead::AES_256_GCM, &k)
.map_err(|_| PkiError::BadSealedKey)?;
Ok(ring::aead::LessSafeKey::new(unbound))
}
/// Encrypt a key with a password: PBKDF2-HMAC-SHA256 ([`KEY_KDF_ITERATIONS`]) and
/// AES-256-GCM, armoured as `IANITOR ENCRYPTED PRIVATE KEY` (so the pre-commit hook blocks it).
pub fn encrypt_key(key: &KeyPair, password: &[u8]) -> Result<String, PkiError> {
encrypt_key_with(key, password, KEY_KDF_ITERATIONS)
}
/// [`encrypt_key`] with another iteration count (tests).
pub fn encrypt_key_with(
key: &KeyPair,
password: &[u8],
iterations: u32,
) -> Result<String, PkiError> {
if password.is_empty() {
return Err(PkiError::WrongPassword);
}
let salt = random::<16>()?;
let nonce = random::<12>()?;
let k = derive(password, &salt, iterations)?;
let mut data = key.serialize_der();
k.seal_in_place_append_tag(
ring::aead::Nonce::assume_unique_for_key(nonce),
ring::aead::Aad::from(KEY_AAD),
&mut data,
)
.map_err(|_| PkiError::BadSealedKey)?;
let mut blob = Vec::with_capacity(36 + data.len());
blob.extend_from_slice(KEY_MAGIC);
blob.extend_from_slice(&iterations.to_be_bytes());
blob.extend_from_slice(&salt);
blob.extend_from_slice(&nonce);
blob.extend_from_slice(&data);
let b = STANDARD.encode(blob);
let mut s = format!("{ARMOR_BEGIN}\n");
for chunk in b.as_bytes().chunks(64) {
s.push_str(&String::from_utf8_lossy(chunk));
s.push('\n');
}
s.push_str(ARMOR_END);
s.push('\n');
Ok(s)
}
/// Open a key made by [`encrypt_key`].
pub fn decrypt_key(sealed: &str, password: &[u8]) -> Result<KeyPair, PkiError> {
let body = sealed
.trim()
.strip_prefix(ARMOR_BEGIN)
.and_then(|r| r.strip_suffix(ARMOR_END))
.ok_or(PkiError::BadSealedKey)?;
let b64: String = body.chars().filter(|c| !c.is_ascii_whitespace()).collect();
let blob = STANDARD.decode(b64).map_err(|_| PkiError::BadSealedKey)?;
if blob.len() < 4 + 4 + 16 + 12 + 16 || &blob[..4] != KEY_MAGIC {
return Err(PkiError::BadSealedKey);
}
let iterations = u32::from_be_bytes([blob[4], blob[5], blob[6], blob[7]]);
if !(1..=10_000_000).contains(&iterations) {
return Err(PkiError::BadSealedKey);
}
let salt = &blob[8..24];
let mut nonce = [0u8; 12];
nonce.copy_from_slice(&blob[24..36]);
let mut data = blob[36..].to_vec();
let k = derive(password, salt, iterations)?;
let plain = k
.open_in_place(
ring::aead::Nonce::assume_unique_for_key(nonce),
ring::aead::Aad::from(KEY_AAD),
&mut data,
)
.map_err(|_| PkiError::WrongPassword)?;
Ok(KeyPair::from_der(plain)?)
}
// ------------------------------------------------------------------ for tests
/// Helpers for tests that need certificates Ianitor itself would never make.
#[doc(hidden)]
pub mod testing {
use super::*;
/// A server certificate for `name`, signed with `key` as if the first certificate of
/// `issuer_pem` were a CA (for "a leaf cannot sign").
pub fn sign_as(
issuer_pem: &str,
key: KeyPair,
name: &str,
now: i64,
) -> Result<String, PkiError> {
Ok(domi_pki::testing::sign_as(issuer_pem, key, name, now)?)
}
/// A CA below the intermediate (which pathLen 0 forbids).
pub fn sub_ca(int: &Intermediate, key: &KeyPair, now: i64) -> Result<String, PkiError> {
Ok(domi_pki::testing::sub_ca(int.inner(), key, now)?)
}
/// A CSR that asks for far too much.
pub fn greedy_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> {
Ok(domi_pki::testing::greedy_csr(key, cn)?)
}
/// Flip one byte inside the CSR's signed part.
pub fn tamper_csr(csr_pem: &str) -> String {
domi_pki::testing::tamper_csr(csr_pem)
}
}
+13 -1
View File
@@ -15,7 +15,7 @@ use crate::error::{ValidationError as E, ValidationErrors, reason as r};
use crate::model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model,
Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost,
};
/// One route file handed in by the caller (core does no I/O).
@@ -121,6 +121,8 @@ struct RawHost {
#[serde(default)]
share_links: bool,
#[serde(default)]
device_certs: bool,
#[serde(default)]
access_log: RawAccessLog,
health_check: Option<RawHealthCheck>,
#[serde(default)]
@@ -500,6 +502,15 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
}
});
// The web UI's per-boot proof (docs/api.md, "Sign-in") may only ride on a host whose
// visitors were checked by forward-auth: edge strips client `Remote-*` headers only there.
let sends_proof = request_headers.iter().any(|r| {
matches!(r, HeaderRule::Set { value: HeaderValue::Secret(s), .. } if s.as_str() == UI_PROOF_SECRET)
});
if sends_proof && auth != AuthMode::ForwardAuth {
errors.push(E::ProofWithoutSignIn { file: f() });
}
if errors.len() != before {
return None;
}
@@ -517,6 +528,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
websockets: raw.websockets,
health_check,
share_links: raw.share_links,
device_certs: raw.device_certs,
access_log: match raw.access_log {
RawAccessLog::Off => AccessLog::Off,
RawAccessLog::Truncated => AccessLog::Truncated,
+90
View File
@@ -72,6 +72,8 @@ fn options() -> CompileOptions {
access_log: "/var/log/ianitor/access.log".into(),
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
}
}
@@ -149,6 +151,29 @@ fn caddy_output_is_valid_json_with_servers() {
assert_eq!(v["admin"]["disabled"], serde_json::json!(true));
}
#[test]
fn trusted_proxies_reach_both_engines_only_when_set() {
let edge = compile::edge(&model(false), &options()).unwrap();
let caddy = compile::caddy(&model(false), &options()).unwrap();
assert!(!edge.contains("trusted_proxies") && !caddy.contains("trusted_proxies"));
let mut o = options();
o.trusted_proxies = vec!["127.0.0.1".parse().unwrap()];
let cfg: EdgeConfig = serde_json::from_str(&compile::edge(&model(false), &o).unwrap()).unwrap();
assert_eq!(cfg.trusted_proxies, vec!["127.0.0.1".to_owned()]);
let v: serde_json::Value =
serde_json::from_str(&compile::caddy(&model(false), &o).unwrap()).unwrap();
let servers = v["apps"]["http"]["servers"].as_object().unwrap();
let https = servers
.values()
.find(|s| s["listen"][0] == "0.0.0.0:443")
.unwrap();
assert_eq!(
https["trusted_proxies"],
serde_json::json!({"source": "static", "ranges": ["127.0.0.1"]})
);
assert_eq!(https["trusted_proxies_strict"], serde_json::json!(1));
}
#[test]
fn outputs_reference_secrets_by_name_only() {
let edge = compile::edge(&model(false), &options()).unwrap();
@@ -277,3 +302,68 @@ fn websocket_refusal_in_caddy_matches_any_upgrade_token() {
"token-aware Upgrade matcher"
);
}
#[test]
fn device_cert_hosts_check_client_certificates_in_both_engines() {
let m = model(false);
let edge: EdgeConfig = serde_json::from_str(&compile::edge(&m, &options()).unwrap()).unwrap();
let dc = edge.device_certs.expect("a host needs device certificates");
assert_eq!(dc.ca, "/var/lib/ianitor/certs/domi-devices-ca.pem");
assert_eq!(dc.allow, "/var/lib/ianitor/certs/domi-devices.pem");
let on: Vec<&str> = edge
.hosts
.iter()
.filter(|h| h.device_certs)
.map(|h| h.hostname.as_str())
.collect();
assert_eq!(on, ["status.example.org"]);
let v: serde_json::Value =
serde_json::from_str(&compile::caddy(&m, &options()).unwrap()).unwrap();
let https = &v["apps"]["http"]["servers"]["ianitor_https"];
let policies = https["tls_connection_policies"].as_array().unwrap();
let with_auth: Vec<&serde_json::Value> = policies
.iter()
.filter(|p| p.get("client_authentication").is_some())
.collect();
assert_eq!(
with_auth.len(),
1,
"only the device host asks for a certificate"
);
assert_eq!(with_auth[0]["match"]["sni"][0], "status.example.org");
assert_eq!(
with_auth[0]["client_authentication"]["mode"],
"verify_if_given"
);
let routes = https["routes"].as_array().unwrap();
let status = routes
.iter()
.find(|r| r["match"][0]["host"][0] == "status.example.org")
.unwrap();
let first = &status["handle"][0]["routes"][0];
assert_eq!(
first["handle"][0]["status_code"], 403,
"no certificate: 403 first"
);
// Without a device host, neither engine asks for client certificates.
let plain = ianitor_core::load(
&SourceFile {
name: "ianitor.toml",
contents: "",
},
&[SourceFile {
name: "hosts/a.test.toml",
contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
}],
)
.unwrap();
let e: EdgeConfig = serde_json::from_str(&compile::edge(&plain, &options()).unwrap()).unwrap();
assert!(e.device_certs.is_none());
assert!(
!compile::caddy(&plain, &options())
.unwrap()
.contains("client_authentication")
);
}
@@ -1,2 +1,3 @@
hostname = "status.example.org"
upstreams = ["http://[::1]:3001"]
device_certs = true
+46
View File
@@ -145,6 +145,23 @@
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"handler": "static_response",
"status_code": 403
}
],
"match": [
{
"vars": {
"{http.request.tls.client.fingerprint}": [
""
]
}
}
]
},
{
"handle": [
{
@@ -465,6 +482,35 @@
}
],
"tls_connection_policies": [
{
"client_authentication": {
"ca": {
"pem_files": [
"/var/lib/ianitor/certs/domi-devices-ca.pem"
],
"provider": "file"
},
"mode": "verify_if_given",
"verifiers": [
{
"leaf_certs_loaders": [
{
"files": [
"/var/lib/ianitor/certs/domi-devices.pem"
],
"loader": "file"
}
],
"verifier": "leaf"
}
]
},
"match": {
"sni": [
"status.example.org"
]
}
},
{
"certificate_selection": {
"any_tag": [
+11 -4
View File
@@ -1,5 +1,5 @@
{
"version": 2,
"version": 3,
"http_listen": "0.0.0.0:80",
"https_listen": "0.0.0.0:443",
"https_port": 443,
@@ -30,6 +30,10 @@
"Remote-Name"
]
},
"device_certs": {
"ca": "/var/lib/ianitor/certs/domi-devices-ca.pem",
"allow": "/var/lib/ianitor/certs/domi-devices.pem"
},
"hosts": [
{
"hostname": "photos.example.org",
@@ -83,7 +87,8 @@
"interval_secs": 15
},
"access_log": true,
"share_links": false
"share_links": false,
"device_certs": false
},
{
"hostname": "status.example.org",
@@ -103,7 +108,8 @@
"response_headers": [],
"health_check": null,
"access_log": false,
"share_links": false
"share_links": false,
"device_certs": true
},
{
"hostname": "wiki.home.test",
@@ -134,7 +140,8 @@
"response_headers": [],
"health_check": null,
"access_log": false,
"share_links": false
"share_links": false,
"device_certs": false
}
]
}
+359
View File
@@ -0,0 +1,359 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The Domi CA (ROADMAP §6 phase 3, tests first): issued chains validate to the root, a leaf
//! cannot sign, expired and wrong-name certificates are rejected, an intermediate is never
//! made from a CSR's own wishes, and encrypted keys need their password.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use ianitor_core::pki::{
self, DEVICE_DAYS, INTERMEDIATE_DAYS, Intermediate, PkiError, ROOT_DAYS, SERVER_DAYS,
};
use rustls_pki_types::{CertificateDer, ServerName, UnixTime};
use webpki::{EndEntityCert, KeyUsage, anchor_from_trusted_cert};
const NOW: i64 = 1_800_000_000;
const DAY: i64 = 86_400;
fn der(pem: &str) -> CertificateDer<'static> {
use rustls_pki_types::pem::PemObject;
CertificateDer::pem_slice_iter(pem.as_bytes())
.next()
.unwrap()
.unwrap()
}
fn all_der(pem: &str) -> Vec<CertificateDer<'static>> {
use rustls_pki_types::pem::PemObject;
CertificateDer::pem_slice_iter(pem.as_bytes())
.collect::<Result<_, _>>()
.unwrap()
}
fn at(t: i64) -> UnixTime {
UnixTime::since_unix_epoch(std::time::Duration::from_secs(t as u64))
}
struct Ca {
root_pem: String,
root_key: pki::KeyPair,
int: Intermediate,
}
fn ca() -> Ca {
let (root_pem, root_key) = pki::create_root(NOW).unwrap();
let int_key = pki::generate_key().unwrap();
let csr = pki::intermediate_csr(&int_key, pki::INTERMEDIATE_CN).unwrap();
let int_pem = pki::sign_intermediate(&root_pem, &root_key, &csr, NOW).unwrap();
let int = Intermediate::new(&int_pem, int_key).unwrap();
Ca {
root_pem,
root_key,
int,
}
}
/// Verify `leaf_chain` (leaf first, then intermediates) against `root` at time `t`.
fn verify(root_pem: &str, leaf_chain: &str, t: i64, usage: KeyUsage) -> Result<(), webpki::Error> {
let root = der(root_pem);
let anchor = anchor_from_trusted_cert(&root).unwrap().to_owned();
let chain = all_der(leaf_chain);
let ee = EndEntityCert::try_from(&chain[0]).unwrap();
ee.verify_for_usage(
webpki::ALL_VERIFICATION_ALGS,
&[anchor],
&chain[1..],
at(t),
usage,
None,
None,
)
.map(|_| ())
}
#[test]
fn root_is_a_ten_year_ca_with_path_length_one() {
let (root_pem, _) = pki::create_root(NOW).unwrap();
let info = pki::inspect(&root_pem).unwrap();
assert!(info.is_ca);
assert_eq!(info.path_len, Some(1));
assert!(
info.path_len.unwrap() >= 1,
"ROADMAP §3: pathLenConstraint >= 1"
);
assert_eq!(info.subject_cn, pki::ROOT_CN);
let days = (info.not_after - NOW) / DAY;
assert!(
(ROOT_DAYS as i64 - 1..=ROOT_DAYS as i64).contains(&days),
"{days}"
);
assert!(days >= 3650);
}
#[test]
fn intermediate_is_one_year_path_length_zero_and_signed_by_the_root() {
let c = ca();
let info = pki::inspect(c.int.cert_pem()).unwrap();
assert!(info.is_ca);
assert_eq!(info.path_len, Some(0));
assert_eq!((info.not_after - NOW) / DAY, INTERMEDIATE_DAYS as i64);
assert!(pki::issued_by(c.int.cert_pem(), &c.root_pem).unwrap());
assert!(!pki::issued_by(&c.root_pem, c.int.cert_pem()).unwrap());
}
#[test]
fn server_chain_validates_to_the_root() {
let c = ca();
let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap();
verify(
&c.root_pem,
&leaf.chain_pem,
NOW + DAY,
KeyUsage::server_auth(),
)
.unwrap();
let info = pki::inspect(&leaf.cert_pem).unwrap();
assert!(!info.is_ca);
assert_eq!(info.dns_names, vec!["wiki.home.test".to_owned()]);
assert_eq!((info.not_after - NOW) / DAY, SERVER_DAYS as i64);
// The key belongs to the certificate.
let k = pki::KeyPair::from_pem(&leaf.key_pem).unwrap();
assert_eq!(
pki::public_key_der(&leaf.cert_pem).unwrap(),
k.public_key_der()
);
}
#[test]
fn device_chain_validates_for_client_auth_only() {
let c = ca();
let dev = pki::issue_device(&c.int, "Mark's phone", NOW).unwrap();
verify(
&c.root_pem,
&dev.chain_pem,
NOW + DAY,
KeyUsage::client_auth(),
)
.unwrap();
assert!(
verify(
&c.root_pem,
&dev.chain_pem,
NOW + DAY,
KeyUsage::server_auth()
)
.is_err(),
"a device certificate cannot serve a site"
);
let info = pki::inspect(&dev.cert_pem).unwrap();
assert_eq!(info.subject_cn, "Mark's phone");
assert_eq!((info.not_after - NOW) / DAY, DEVICE_DAYS as i64);
}
#[test]
fn a_leaf_cannot_sign() {
let c = ca();
let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap();
let leaf_key = pki::KeyPair::from_pem(&leaf.key_pem).unwrap();
// Ianitor refuses to use a leaf as an issuer.
assert!(matches!(
Intermediate::new(&leaf.cert_pem, leaf_key),
Err(PkiError::NotCa)
));
// And a certificate forged with the leaf key as issuer does not validate.
let leaf_key = pki::KeyPair::from_pem(&leaf.key_pem).unwrap();
let forged = pki::testing::sign_as(&leaf.cert_pem, leaf_key, "evil.home.test", NOW).unwrap();
let chain = format!("{forged}{}", leaf.chain_pem);
let e = verify(&c.root_pem, &chain, NOW + DAY, KeyUsage::server_auth()).unwrap_err();
assert!(
matches!(
e,
webpki::Error::EndEntityUsedAsCa
| webpki::Error::CaUsedAsEndEntity
| webpki::Error::UnknownIssuer
),
"{e:?}"
);
}
#[test]
fn intermediate_cannot_make_another_ca() {
// pathLen 0: a CA below the intermediate is not trusted.
let c = ca();
let sub_key = pki::generate_key().unwrap();
let sub = pki::testing::sub_ca(&c.int, &sub_key, NOW).unwrap();
let leaf = pki::testing::sign_as(&sub, sub_key, "deep.home.test", NOW).unwrap();
let chain = format!("{leaf}{sub}{}", c.int.cert_pem());
assert!(verify(&c.root_pem, &chain, NOW + DAY, KeyUsage::server_auth()).is_err());
}
#[test]
fn expired_certificates_are_rejected() {
let c = ca();
let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap();
let after = NOW + (SERVER_DAYS as i64 + 1) * DAY;
assert!(matches!(
verify(&c.root_pem, &leaf.chain_pem, after, KeyUsage::server_auth()),
Err(webpki::Error::CertExpired { .. })
));
let before = NOW - DAY;
assert!(
verify(
&c.root_pem,
&leaf.chain_pem,
before,
KeyUsage::server_auth()
)
.is_err()
);
}
#[test]
fn wrong_name_is_rejected() {
let c = ca();
let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap();
let ee_der = der(&leaf.cert_pem);
let ee = EndEntityCert::try_from(&ee_der).unwrap();
ee.verify_is_valid_for_subject_name(&ServerName::try_from("wiki.home.test").unwrap())
.unwrap();
assert!(
ee.verify_is_valid_for_subject_name(&ServerName::try_from("photos.home.test").unwrap())
.is_err()
);
assert!(
ee.verify_is_valid_for_subject_name(&ServerName::try_from("home.test").unwrap())
.is_err()
);
}
#[test]
fn a_certificate_from_another_root_is_rejected() {
let c = ca();
let other = ca();
let leaf = pki::issue_server(&other.int, "wiki.home.test", NOW).unwrap();
// Both CAs have the same names, so webpki finds the issuer by name and then the
// signature check fails.
let e = verify(
&c.root_pem,
&leaf.chain_pem,
NOW + DAY,
KeyUsage::server_auth(),
)
.unwrap_err();
assert!(
matches!(
e,
webpki::Error::UnknownIssuer | webpki::Error::InvalidSignatureForPublicKey
),
"{e:?}"
);
}
#[test]
fn leaves_never_outlive_the_intermediate() {
let c = ca();
let late = NOW + (INTERMEDIATE_DAYS as i64 - 10) * DAY;
let leaf = pki::issue_device(&c.int, "tablet", late).unwrap();
let info = pki::inspect(&leaf.cert_pem).unwrap();
assert!(info.not_after <= c.int.not_after());
// An expired intermediate issues nothing.
let gone = NOW + (INTERMEDIATE_DAYS as i64 + 1) * DAY;
assert!(matches!(
pki::issue_server(&c.int, "wiki.home.test", gone),
Err(PkiError::IssuerExpired)
));
}
#[test]
fn the_intermediate_ignores_what_the_csr_asks_for() {
let (root_pem, root_key) = pki::create_root(NOW).unwrap();
let key = pki::generate_key().unwrap();
// A CSR asking to be a CA with no path limit, for 50 years, for a web name.
let greedy = pki::testing::greedy_csr(&key, pki::INTERMEDIATE_CN).unwrap();
let pem = pki::sign_intermediate(&root_pem, &root_key, &greedy, NOW).unwrap();
let info = pki::inspect(&pem).unwrap();
assert_eq!(info.path_len, Some(0));
assert!(info.dns_names.is_empty());
assert_eq!((info.not_after - NOW) / DAY, INTERMEDIATE_DAYS as i64);
// The wrong subject is refused.
let wrong = pki::intermediate_csr(&key, "Some Other CA").unwrap();
assert!(matches!(
pki::sign_intermediate(&root_pem, &root_key, &wrong, NOW),
Err(PkiError::CsrSubject)
));
// A tampered CSR (signature does not match) is refused.
let csr = pki::intermediate_csr(&key, pki::INTERMEDIATE_CN).unwrap();
let tampered = pki::testing::tamper_csr(&csr);
assert!(pki::sign_intermediate(&root_pem, &root_key, &tampered, NOW).is_err());
// Garbage is refused, never a panic.
assert!(pki::sign_intermediate(&root_pem, &root_key, "not a csr", NOW).is_err());
}
#[test]
fn intermediate_must_match_its_key_and_be_a_ca() {
let c = ca();
let other_key = pki::generate_key().unwrap();
assert!(matches!(
Intermediate::new(c.int.cert_pem(), other_key),
Err(PkiError::KeyMismatch)
));
let _ = c.root_key;
}
#[test]
fn match_code_is_three_two_digit_groups_and_stable() {
let a = pki::match_code(b"some csr");
assert_eq!(a, pki::match_code(b"some csr"));
assert_ne!(a, pki::match_code(b"other csr"));
let parts: Vec<&str> = a.split(' ').collect();
assert_eq!(parts.len(), 3);
assert!(
parts
.iter()
.all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit()))
);
}
#[test]
fn encrypted_key_needs_its_password() {
let key = pki::generate_key().unwrap();
let sealed = pki::encrypt_key_with(&key, b"correct horse battery", 1000).unwrap();
// Armoured so that the pre-commit hook would block it like any private key.
// (Split so that this file does not match the hook itself.)
assert!(sealed.starts_with(concat!(
"-----BEGIN IANITOR ENCRYPTED ",
"PRIVATE KEY-----\n"
)));
// The plain key is not inside.
assert!(!sealed.contains(&key.serialize_pem()));
let back = pki::decrypt_key(&sealed, b"correct horse battery").unwrap();
assert_eq!(back.public_key_der(), key.public_key_der());
assert!(matches!(
pki::decrypt_key(&sealed, b"wrong"),
Err(PkiError::WrongPassword)
));
// A changed byte is caught.
let mut bad = sealed.clone().into_bytes();
let i = bad.len() / 2;
bad[i] = if bad[i] == b'A' { b'B' } else { b'A' };
assert!(pki::decrypt_key(&String::from_utf8(bad).unwrap(), b"correct horse battery").is_err());
assert!(pki::decrypt_key("garbage", b"x").is_err());
// Default strength.
const { assert!(pki::KEY_KDF_ITERATIONS >= 600_000) };
}
#[test]
fn hostile_pem_input_is_an_error_not_a_panic() {
for bad in [
"",
"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n",
"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n",
"\u{0}\u{1}",
] {
assert!(pki::inspect(bad).is_err());
assert!(pki::issued_by(bad, bad).is_err());
assert!(pki::public_key_der(bad).is_err());
}
}
+3
View File
@@ -68,6 +68,7 @@ fn minimal_host_gets_documented_defaults() {
assert_eq!(h.auth, AuthMode::None);
assert!(h.websockets, "websockets default on, like Caddy");
assert!(!h.share_links);
assert!(!h.device_certs, "device certificates are opt-in");
assert_eq!(h.access_log, AccessLog::Off);
assert!(h.health_check.is_none());
assert!(h.request_headers.is_empty() && h.response_headers.is_empty());
@@ -85,6 +86,7 @@ auth = "forward-auth"
websockets = false
share_links = true
access_log = "truncated"
device_certs = true
[health_check]
path = "/healthz"
@@ -110,6 +112,7 @@ value = "max-age=31536000"
assert_eq!(h.auth, AuthMode::ForwardAuth);
assert!(!h.websockets);
assert!(h.share_links);
assert!(h.device_certs);
assert_eq!(h.access_log, AccessLog::Truncated);
let hc = h.health_check.as_ref().unwrap();
assert_eq!(hc.path, "/healthz");
+1
View File
@@ -36,6 +36,7 @@ form_urlencoded = "1.2"
[dev-dependencies]
ianitor-testkit.workspace = true
ring.workspace = true
rcgen.workspace = true
[lints]
workspace = true
+8 -1
View File
@@ -235,6 +235,10 @@ async fn handle(shared: Arc<Shared>, req: Request<Incoming>) -> Resp {
}
}
("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })),
("POST", "/v1/device-certs/reload") => match shared.reload_device_trust() {
Ok(n) => reply(StatusCode::OK, json!({ "reloaded": true, "allowed": n })),
Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
},
("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() {
Ok(()) => {
let r = shared.revocations();
@@ -331,7 +335,10 @@ impl BackgroundService for RevocationPoller {
loop {
tokio::select! {
_ = shutdown.changed() => return,
_ = tokio::time::sleep(Duration::from_secs(5)) => self.shared.poll_revocations(),
_ = tokio::time::sleep(Duration::from_secs(5)) => {
self.shared.poll_revocations();
self.shared.poll_device_trust();
}
}
}
}

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