diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 78defcd..5b233e4 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -113,6 +113,16 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit 3. Does Pingora build on Windows? If not, develop in WSL2 and note it in CLAUDE.md. (phase 1) **Answer: it compiles and the unit tests run on Windows (MSVC, Rust 1.99), but the README calls Windows support "preliminary by community's best effort only".** Unix-only parts include graceful upgrade, the in-process runner and the integration tests. Caddy and Pebble are not on this Windows box. So the edge integration tests, the diff suite and the ACME test run in WSL2 Debian, as noted in CLAUDE.md. One gotcha: libz-ng-sys's CMake build fails under a very deep CARGO_TARGET_DIR (MSBuild path length). [S github.com/cloudflare/pingora README; local builds 2026-11-07] 4. Pingora graceful reload behaviour under load. (phase 2) + **Answer: no Pingora graceful upgrade for config changes; edge swaps its config in process.** A reload builds a complete new runtime from the config file (secrets, certificates, share-link key) and installs it with one atomic pointer swap (`arc-swap`); listeners, TLS sessions and keep-alive connections are untouched, each request keeps the runtime it started with, and the next request on the same connection uses the new one. A config that fails to build is refused and the old one keeps serving; listen addresses change only with a restart. Control triggers it through edge's admin Unix socket (mode 0660, never a TCP port) as a *trial* that edge reverts by itself unless control confirms it in time, so a control crash mid-apply cannot strand edge on an unverified config. Pingora's graceful upgrade (new process takes the listening sockets, old one drains for the grace period) stays for binary upgrades only: it needs a second process and fd passing, and idle keep-alive connections on the old process are closed after the drain, which clients see as a reset on their next request; it was not measured. [J] + Measured (`crates/edge/tests/reload.rs`, debug build, WSL2 Debian, 16 cores, one local upstream; alternating two configs that differ in a response header, `POST /v1/reload` every 100 ms, each client one TLS keep-alive connection sending requests back to back): + + | Clients | Duration | Reloads | Requests | Errors | Connection resets | Connections that saw both configs | p50 / p99 / max latency | + |--:|--:|--:|--:|--:|--:|--:|:--| + | 32 | 10 s | 98 | 30,198 | 0 | 0 | 32/32 | 10.5 / 17.2 / 132 ms | + | 64 | 30 s | 294 | 95,229 | 0 | 0 | 64/64 | 20.0 / 31.9 / 190 ms | + | 128 | 30 s | 292 | 87,796 | 0 | 0 | 128/128 | 43.1 / 69.1 / 215 ms | + + Reproduce: `IANITOR_RELOAD_CLIENTS=64 IANITOR_RELOAD_SECS=30 cargo test -p ianitor-edge --test reload -- --exact unix::reload_under_load_drops_nothing --nocapture`. Not measured: a release build, HTTP/2 clients, long-lived websockets across reloads (they keep the runtime they started with until they close), and Pingora graceful upgrade for comparison. [S local runs 2026-11-07] 5. Authelia forward-auth endpoint and headers to mirror exactly. (phase 1) **Answer: `GET /api/authz/forward-auth` (ForwardAuth implementation; legacy `/api/verify` not used).** Edge sends X-Forwarded-Method, -Proto, -Host, -URI (required) and X-Forwarded-For, and always sets them itself. It also forwards the client's headers (Cookie, Authorization) without hop-by-hop headers or body. A 2xx answer copies Remote-User, Remote-Groups, Remote-Email and Remote-Name onto the request (client copies removed). Any other answer (302 portal, 401 + WWW-Authenticate, 403) goes back to the client verbatim. An unreachable, silent (10 s deadline), oversized (>1 MiB), broken or `101` auth answer fails closed with 502; 1xx heads are skipped. Client-sent Remote-* headers are always stripped on forward-auth hosts, whatever copy_headers says. This mirrors `caddy adapt` output for Authelia's documented `forward_auth` snippet; tested against a mock, not a real Authelia. [S authelia.com/reference/guides/proxy-authorization, authelia.com/integration/proxies/caddy] 6. Custos CSR-signing operation with match-code approval. (phase 3) diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..017a7fd --- /dev/null +++ b/docs/api.md @@ -0,0 +1,245 @@ +# Ianitor control API + +`ianitor-control` serves a REST + JSON API on loopback only (`127.0.0.1:7878` by default), +under `/api/v1`. The OpenAPI document is generated from the code: `GET /api/v1/openapi.json`, +or `ianitor-control openapi` without a running server. The web UI's contract is +[docs/ui-api.md](ui-api.md); its last section lists where this API differs. + +Everything below was run end to end on loopback against `--dev` with a real edge +(2026-11-07, WSL2 Debian); the outputs are trimmed with `jq`, never edited. + +## Ground rules + +- **Token.** Every call needs `Authorization: Bearer `. Nothing else identifies a + caller (no `Remote-User`). Without a valid token: `401` with `token.missing`, + `token.unknown`, `token.expired` or `token.revoked`. 120 calls a minute per token. +- **Host header.** Only `127.0.0.1:`, `localhost:`, `[::1]:` and the + configured `allowed_hosts` are answered (DNS rebinding). A browser write (`Origin` or + `Sec-Fetch-Site` present) also needs `X-Ianitor-UI: 1` (CSRF). +- **Bodies** are JSON, at most 64 KiB, with no unknown fields. Error messages never repeat a + value you sent. +- **Errors** have one shape; `code` is stable, `message` is plain English, `field` points at + the form field, `params` holds the values in the message, `detail` is the technical text: + + ```json + { "error": { "code": "host.hostname.uppercase", "message": "Use lowercase letters only: wiki.dev.test.", + "field": "hostname", "params": { "hostname": "Wiki.dev.test", "suggestion": "wiki.dev.test" }, + "retry_after_s": null, "detail": "hosts/Wiki.dev.test.toml: `Wiki.dev.test` is not a valid hostname: it must be lowercase" }, + "errors": [ ... one per field problem ... ], "request_id": "9c1f…", "server_time": "2026-11-07T17:19:40Z" } + ``` +- **`server_time`** is in every JSON object answer. Times are RFC 3339 UTC. +- **Changes are applies.** Adding, changing, removing a host, Undo and Restore answer + `202 {"apply": {...}}` at once; poll `GET /applies/{id}` (every second) until `state` is + `kept`, `reverted`, `failed` or `needs_attention`. Applies run one at a time, in order; + the others are `queued`. +- **`Idempotency-Key`** on a write: a retry with the same key gets the same apply back. +- **`base_rev`** (from `GET /hosts/{h}` or the overview's `rev`): the change is refused with + `409 change.conflict` only if the same host file changed since. + +## Start + +Development, everything temporary on 127.0.0.1 (removed on Ctrl-C): + +```sh +cargo build -p ianitor-edge -p ianitor-control # so --dev finds ianitor-edge next to it +cargo run -p ianitor-control -- --dev +``` + +```text +Ianitor control (dev) on http://127.0.0.1:7878/api/v1 +Routes repository: /tmp/ianitor-dev-1523/routes.git +Dev proxy: …/ianitor-edge on https://127.0.0.1:18443 (HTTP 18080). tls = "domi" works for app.dev.test, wiki.dev.test, photos.dev.test; CA: /tmp/ianitor-dev-1523/certs/dev-ca.crt +API token (shown once): ian_06484a2c0a6ec73b_vceenNC… +Press Ctrl-C to stop and remove /tmp/ianitor-dev-1523 +``` + +Without `ianitor-edge` (or with `--edge-bin` pointing nowhere) applies are only validated, +compiled and written. In dev mode the health watch lasts 10 s (`--watch-secs`); in +production 60 s. + +Production: the first token comes from the CLI on the server, never over the network: + +```sh +ianitor-control token create --name mark-laptop --config /etc/ianitor/control.toml +``` + +The examples use: + +```sh +TOKEN=ian_… # from the line above +API=http://127.0.0.1:7878/api/v1 +H="Authorization: Bearer $TOKEN" +CA=/tmp/ianitor-dev-1523/certs/dev-ca.crt +visit() { curl -s -o /dev/null -w '%{http_code}\n' --cacert "$CA" --resolve "$1:18443:127.0.0.1" "${@:2}"; } +python3 -m http.server 3000 --bind 127.0.0.1 & # a test upstream +``` + +## Add a host + +```sh +curl -s -H "$H" -H 'Content-Type: application/json' -H 'Idempotency-Key: add-app-1' \ + -X POST "$API/hosts" -d '{"host": {"hostname": "app.dev.test", + "upstreams": ["http://127.0.0.1:3000"], "tls": "domi", "auth": "none", + "health_check": {"path": "/", "interval_secs": 5}}}' | jq '{state: .apply.state, id: .apply.id}' +``` +```json +{ "state": "queued", "id": "ch_b720484831a9" } +``` +```sh +curl -s -H "$H" "$API/applies/ch_b720484831a9" | jq '{state, summary, reason: .reason.message, steps: [.steps[] | "\(.key)=\(.state)"]}' +``` +```json +{ "state": "kept", "summary": "Added app.dev.test", + "reason": "app.dev.test is live. Health checks passed for 10 s.", + "steps": ["validate=done", "compile=done", "write=done", "reload=done", "watch=done", "push=skipped"] } +``` +```sh +visit app.dev.test https://app.dev.test:18443/ # 200 +``` + +The same request with the same `Idempotency-Key` returns `ch_b720484831a9` again and changes +nothing. A host that fails its health check during the watch is reverted: `state: +"reverted"`, and `reason` says why, e.g. `"a.test was not changed. 127.0.0.1:41999 answered +with an error page on 3 of 3 checks. Ianitor undid the change."` The routes repository then +holds the change and its revert commit; edge and the files never left the last good config. + +A form error comes back at once, field by field: + +```sh +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts" \ + -d '{"host": {"hostname": "Wiki.dev.test", "upstreams": ["http://10.0.0.23"]}}' \ + | jq '{code: .error.code, errors: [.errors[] | {code, field, message}]}' +``` +```json +{ "code": "apply.failed.validation", + "errors": [{ "code": "host.hostname.uppercase", "field": "hostname", "message": "Use lowercase letters only: wiki.dev.test." }] } +``` + +`POST /hosts/validate?mode=create` checks a body without applying it; `PUT /hosts/{h}` with +`{"host": …, "base_rev": …}` changes a host; `PATCH /hosts/{h}` with `{"share_links": true}` +turns share links on; `DELETE /hosts/{h}` removes one. + +## Undo + +Undo always names what it will undo; the POST must name the same change, or it is refused +with `409 undo.target_moved`. Undo right after an Undo is a redo, and `effect` says so. + +```sh +curl -s -H "$H" "$API/undo" | jq '{available, target: .target.summary, effect}' +``` +```json +{ "available": true, "target": "Added app.dev.test", "effect": "Removes app.dev.test" } +``` +```sh +TARGET=$(curl -s -H "$H" "$API/undo" | jq -r .target.change_id) +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/undo" \ + -d "{\"target_change_id\": \"$TARGET\"}" | jq -r .apply.id +# then poll /applies/{id}: +``` +```json +{ "state": "kept", "summary": "Undid: Added app.dev.test", "reason": "app.dev.test is removed.", + "steps": ["validate=done", "compile=done", "write=done", "reload=done", "watch=skipped", "push=skipped"] } +``` +```sh +visit app.dev.test https://app.dev.test:18443/ # 000: no certificate is served for a removed host +``` + +## History and Restore + +One entry per action (a reverted attempt is one `reverted` entry): + +```sh +curl -s -H "$H" "$API/history?limit=5" | jq '[.entries[] | {change_id, summary, state}]' +``` +```json +[ { "change_id": "ch_cf0b434ecb4c", "summary": "Undid: Added app.dev.test", "state": "kept" }, + { "change_id": "ch_b720484831a9", "summary": "Added app.dev.test", "state": "kept" } ] +``` +```sh +curl -s -H "$H" "$API/history/ch_b720484831a9/restore-preview" | jq '{restorable, changes}' +``` +```json +{ "restorable": true, "changes": [{ "effect": "added", "fields": [], "hostname": "app.dev.test" }] } +``` +```sh +REV=$(curl -s -H "$H" "$API/overview" | jq -r .rev) +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/restore" \ + -d "{\"change_id\": \"ch_b720484831a9\", \"base_rev\": \"$REV\"}" | jq -r .apply.id +# then poll /applies/{id}: +``` +```json +{ "state": "kept", "summary": "Restored the version of 7 November 2026", + "reason": "app.dev.test is live. Health checks passed for 10 s." } +``` +```sh +visit app.dev.test https://app.dev.test:18443/ # 200 +``` + +## Share link + +A host with `auth = "forward-auth"` and `share_links = true` (dev mode points sign-in at an +Authelia on 127.0.0.1:9091 that is not running, so without a link the request fails closed): + +```sh +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts" \ + -d '{"host": {"hostname": "wiki.dev.test", "upstreams": ["http://127.0.0.1:3000"], + "tls": "domi", "auth": "forward-auth", "share_links": true}}' # poll until kept +visit wiki.dev.test https://wiki.dev.test:18443/ # 502: sign-in unreachable, fails closed + +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts/wiki.dev.test/share-links" \ + -d '{"path_prefix": "/", "expires_in_s": 86400}' +``` +```json +{ "id": "ec724bb1420da0d8d81ee897e1e5344b", "expires_at": "2026-11-08T17:20:05Z", "path_prefix": "/", + "has_password": false, "url": "https://wiki.dev.test:18443/?share=ish1.…", "warning": null } +``` + +The URL is shown once (control keeps no token). The first visit trades the token for a +path-scoped `HttpOnly; Secure; SameSite=Lax` cookie and redirects to the same URL without it: + +```sh +curl -s -o /dev/null -w '%{http_code} -> %{redirect_url}\n' --cacert "$CA" \ + --resolve wiki.dev.test:18443:127.0.0.1 -c jar "$URL" # 303 -> https://wiki.dev.test:18443/ +visit wiki.dev.test -b jar https://wiki.dev.test:18443/ # 200, no sign-in +``` + +Stop it; edge refuses it at once (and within 5 s even if control's nudge is lost): + +```sh +curl -s -H "$H" -X DELETE -o /dev/null -w '%{http_code}\n' "$API/share-links/ec724bb1420da0d8d81ee897e1e5344b" # 204 +visit wiki.dev.test -b jar https://wiki.dev.test:18443/ # 502: back to sign-in +visit wiki.dev.test "$URL" # 403: "This link no longer works" +``` + +Options: `"password": "at least 8 characters"` (the visitor gets a password page; 5 wrong +tries a minute per link and network), `"replaces": ""` stops an earlier link, +`POST /share-links/stop-all` stops every link made so far, `GET /share-links` lists them +(without tokens). + +## Tokens + +```sh +curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/tokens" -d '{"name": "backup script"}' +# 201 {"id": "…", "name": "backup script", "token": "ian_…", "expires_at": "2027-11-07T…"} (shown once) +curl -s -H "$H" "$API/tokens" # ids, names, dates; never a value or hash +curl -s -H "$H" -X DELETE "$API/tokens/" # 204; anything using it stops now +curl -s "$API/overview" | jq .error.code # "token.missing" +``` + +## All calls + +| Call | Does | +|:--|:--| +| `GET /overview` | the main screen in one call (hosts with health, engine, last apply, undo, active apply, repo, site); `ETag`/`304` | +| `GET /hosts`, `GET /hosts/{h}` | hosts; one host with `rev`, its TOML, health and certificate | +| `POST /hosts/validate?mode=create\|edit` | check a host body | +| `POST /hosts`, `PUT /hosts/{h}`, `PATCH /hosts/{h}`, `DELETE /hosts/{h}?base_rev=` | applies | +| `POST /hosts/{h}/certificate/retry` | try Let's Encrypt again now | +| `GET /applies`, `GET /applies/{id}`, `DELETE /applies/{id}` | apply records; cancel a queued one | +| `GET /history`, `GET /history/{id}`, `GET /history/{id}/restore-preview` | history, one entry, restore preview | +| `GET /undo`, `POST /undo`, `POST /restore` | undo and restore | +| `POST /repo/push`, `GET /settings` | push now; settings | +| `GET/POST /tokens`, `PATCH/DELETE /tokens/{id}` | API tokens | +| `POST /hosts/{h}/share-links`, `GET /share-links`, `DELETE /share-links/{id}`, `POST /share-links/stop-all` | share links | +| `GET /health` | edge reachability, config hash, trial, paused state, hosts | +| `GET /openapi.json` | the OpenAPI document | diff --git a/docs/ui-api.md b/docs/ui-api.md index 25f9627..7c09afa 100644 --- a/docs/ui-api.md +++ b/docs/ui-api.md @@ -434,3 +434,69 @@ Not reachable (any host, shared or not; the main screen points to it): | G17 | A reverted attempt is a commit plus a revert in git, but the UI shows one entry, and "Edit and try again" needs what was tried. | Control groups them into one history entry and keeps `attempted_host` for each reverted or failed change. | | G18 | Engine switch: §1.6 and §3/§4 disagree (handover b). | `overview.engine` now, read only. The switch call waits on Mark's answer. | | G19 | `websockets` defaults to true [C], so a "Websockets" chip would show on almost every row. | The UI shows a chip only when websockets are off ("No websockets"); the API needs no change. | + +## 6. Where the Phase 2 API differs from this contract + +Recorded by the Phase 2 implementation (branch `control/phase-2`). docs/api.md has curl +examples; `GET /api/v1/openapi.json` has every shape. Everything not listed here is built as +written above. + +**Not built in Phase 2 (Phase 3 items):** +- G7: share links work only while Pingora serves. The Caddy JSON ignores `share_links`, so + under the fallback a share visitor gets the normal sign-in (fails closed). `share.engine_caddy` + is not emitted yet. +- G12, G13, G15 (clicks, device certificates and their downloads); §1.7, §1.8 and §3.6 (PKI). +- G14: control authenticates with API tokens only and trusts no `Remote-*` header; the UI in + Phase 3 needs the G14 mechanism (or a token) to call it. +- G18: `overview.engine` is read-only (`running: "pingora"`, `state: "running" | "stopped"`, + `fallback_ready: null`); no `POST /engine`. +- The "This site is not reachable right now" page (§4): edge still answers an unreachable + upstream with an empty `502`, exactly like Caddy, so the differential suite stays exact. + Serving the page needs the same page from Caddy's `handle_errors`. +- `overview.intermediate` is always `null`. + +**Shapes and behaviour that differ:** +- Apply states: there is no `interrupted` state. An apply cut off by a control restart ends as + `reverted` with `reason.code = "apply.interrupted"`; one that was still queued ends as + `failed` with `apply.interrupted.queued`; a cancelled one as `failed` with `apply.cancelled`. +- A change identical to what is live is refused with `409 change.unchanged` instead of + becoming a no-op apply. +- `reason` is `{code, message, hostname, upstream, field, count, of, detail, params}`; an + apply also carries `errors[]`, the full `commit`, `effect` (undo), `actor` (token name) and + `attempted_host`. `push` is present only on kept applies; with no remote configured the + `push` step is `skipped`. +- `apply.kept` says "Health checks passed for {seconds} s." only; the push result is in + `push` / `repo`, not in that sentence. Extra codes: `apply.kept.no_watch` (host without a + health check), `apply.kept.removed`, `apply.kept.no_edge` (dev mode without a proxy), + `apply.reverted.no_answer`, `apply.reverted.edge_lost` (edge restarted or vanished during + the watch), `apply.failed.edge_unreachable`. +- The watch: touched hosts are probed every `watch_every_secs` (5 s by default). A touched host + is reverted when every one of its upstreams failed its last 3 checks, or none passed its + last check at the end; hosts that were already `down` before the change are not judged. +- `undo.blocked = undo.watching` only while an Undo itself is running; any other running apply + just queues the Undo. +- `GET /tokens` lists `id`; the id is the non-secret first part of the token + (`ian__`), so it is a prefix of the token string, but reveals nothing of the + secret. `POST /tokens` takes `{name?, expires_in_days?, never_expires?}`. +- `GET /history` entries have `reason_short` as the last word of the reason code (e.g. + "server error"), and paging uses `before=` with `next_before` in the answer. + `GET /history/{id}` returns the full apply. +- `GET /history/{id}/restore-preview` field keys are `hostname`, `upstreams`, `tls`, `auth`, + `websockets`, `share_links`, `access_log`, `health_check.path`, + `health_check.interval_secs` and `headers`; it also has `blocked` (`restore.same`, + `restore.not_kept`). +- Share-link mint answers include `warning` (`host.share.no_signin`) for a host without + sign-in. The token is in `?share=`; edge only takes values starting `ish1.`, so an + upstream's own `share` parameter still works. The password page's "too many tries" answer + is `429`. For a password link the expired page is decided from the token's (unproven) date, + because nothing in the token can be proven before the password is given. +- `overview.site.acme_configured` is always `true` (Let's Encrypt is the default issuer); + extra fields `overview.rev`, `overview.health_error` and `site.share_links_available`. +- Health: one admin Unix socket (mode 0660) carries both the read-only `GET /v1/status` and + control's reload/trial calls, instead of a separate read-only socket. Edge keeps the last 5 + results per upstream; `health.since` is tracked by control and restarts with it. +- `Idempotency-Key`s are remembered in memory for 24 h; a control restart forgets them. +- Extra error codes: `change.unchanged`, `host.hostname.mismatch`, `host.upstream.host_name`, + `request.*`, `repo.unexpected_file`, `repo.no_remote`, `share.unavailable`, + `share.not_found`, `share.replaces`, `share.password_long`, `token.not_found`, `token.name`, + `token.expiry`, `file.*`, `site.*` (problems in `ianitor.toml`).