Files
ianitor/docs/api.md
T

342 lines
18 KiB
Markdown

# 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 or sign-in.** A script sends `Authorization: Bearer <API token>`. The web UI sends
no token: it comes through edge on the admin host, behind Authelia (see "Sign-in" below).
Without either: `401` with `token.missing`, `token.unknown`, `token.expired` or
`token.revoked`; a `Remote-*` header without edge's proof is `401 ui.no_proof`, whatever
else the request carries. 120 calls a minute per token or user. The one exception is the
one-time device download (`GET /device-bundles/{token}`), where the link is the secret.
- **Host header.** Only `127.0.0.1:<port>`, `localhost:<port>`, `[::1]:<port>` 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. Errors about the request
itself (bad JSON, a wrong type, an odd field name, a path that is no hostname) never repeat
what you sent. Errors about a host can repeat its values (hostname, upstream, header name)
in `params` and `detail`, but never a URL's user name and password (shown as `…@`), a secret
value or a token.
- **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. While
the first request with a key is still being handled, a retry gets `409 request.in_progress`
(retry after 1 s). Keys are held in memory for 24 h (at most 2,000; then `429`).
- **`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 never stores the token on disk; only an `Idempotency-Key`
retry of this request gets the same answer again, from memory, for 24 h. 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": "<id>"` 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/<id>" # 204; anything using it stops now
curl -s "$API/overview" | jq .error.code # "token.missing"
```
## Sign-in (the web UI, G14)
The UI is served by control (`[ui] static_dir`) and reached through edge on the **admin host**,
a host in the routes repository with forward-auth to Authelia and one header rule:
```toml
# hosts/ianitor.example.toml
hostname = "ianitor.example"
upstreams = ["http://127.0.0.1:7878"]
tls = "domi"
auth = "forward-auth"
[[request_headers]]
action = "set"
name = "X-Ianitor-Proof"
secret = "ui-proof" # listed in ianitor.toml: secrets = ["ui-proof"]
```
- `ui-proof` is a **per-boot secret**: the `ianitor-ui-proof` unit writes 32 random bytes to
`/run/ianitor-proof/ui-proof` (root only), and edge, caddy-fallback and control load it with
`LoadCredential`. No other process can read it.
- Edge strips every client-sent `Remote-*` header on forward-auth hosts, asks Authelia, copies
Authelia's `Remote-User` (and `Remote-Name`, …) onto the request, and *sets* `X-Ianitor-Proof`
(replacing anything the client sent) only on requests Authelia allowed.
- Control (`[ui] proof_credential = "ui-proof"`, `hostname = "ianitor.example"`) trusts
`Remote-User` only on a request whose `X-Ianitor-Proof` matches (constant-time compare). Then
`Remote-User` is the actor (history, logs) and `Remote-Name` the name the UI shows. Every write
also needs `X-Ianitor-UI: 1` (CSRF; the session is a cookie).
- Any request with a `Remote-*` header but without the proof is `401 ui.no_proof`, so a local
process on loopback cannot claim a user; the proof without `Remote-User` is `401 ui.no_user`.
Tested in `crates/control/tests/ui_auth.rs`, including end to end through edge and a mock Authelia.
- `[ui] logout_url` (Authelia's logout address) becomes `overview.site.auth_logout_url`, the UI's
"Sign out". A Unix socket only edge can reach is Phase 4 hardening (decision Q2).
Why not the Unix socket now: edge's upstreams are `host:port` in the schema; a socket upstream is a
schema and compiler change in both engines, and the proof header needs neither.
## Certificates (the Domi CA)
Everything is in [pki.md](pki.md); the calls:
```sh
curl -s -H "$H" "$API/certs" | jq '{intermediate: .intermediate.state, root: .root.offline, devices: [.devices[].name]}'
curl -s -H "$H" -X POST "$API/certs/intermediate/renewal" | jq '{request_id, match_code, approve_command}'
curl -s -H "$H" "$API/pki-requests/$ID/csr" > req.csr; curl -s -H "$H" "$API/pki-requests/$ID/ext" > req.ext
curl -s -H "$H" -H 'Content-Type: application/json' -X PUT "$API/pki-requests/$ID/certificate" \
-d "$(jq -n --rawfile c int.crt '{certificate_pem: $c}')" | jq .state # "approved"
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/certs/devices" \
-d '{"name": "Mark'\''s phone", "kind": "phone"}' | jq '{request_id, match_code, approve_command}'
# on the server: sudo -u ianitor-control ianitor-control pki approve 47 19 83 --config /etc/ianitor/control.toml
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/certs/devices/$DEV/bundle" \
-d '{"format": "p12"}' | jq '{download_url, one_time_password}'
curl -s -o phone.p12 "$DOWNLOAD_URL" # once; a second try is 410 pki.bundle_used
curl -s -H "$H" -X DELETE "$API/certs/devices/$DEV" # 204, off the allow list at once
```
`overview.intermediate` is `{state ("ok"|"due"|"urgent"|"expired"|"missing"), subject, not_after,
days_left, renewal, banner}`, or `null` without `[pki]`. With `[pki]` configured, control issues
the server certificate of every `tls = "domi"` host before an apply is committed, renews it with 30
days left, and an apply with a Domi host and no intermediate fails with `pki.no_intermediate`.
## Engine switch (G18)
```sh
curl -s -H "$H" "$API/engine" | jq '{running, state, switchable}'
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/engine" -d '{"target": "caddy"}' # 202
# poll GET /engine until state = "running"; last_error says why if it went back
```
Control writes `/var/lib/ianitor/engine` first, stops the serving unit, starts the other one (polkit
allows exactly `ianitor-edge.service` and `caddy-fallback.service`, verbs start/stop/restart) and
waits until it serves; if it does not within 20 s, it starts the old one again and reports
`engine.switch_failed`. The switch waits for a running apply (same lock). Refusals:
`engine.unmanaged` (no `[engine]` in control.toml), `engine.same`, `engine.switching`,
`engine.not_ready` (Caddy's settings cannot be built from the current routes).
While Caddy serves (decisions Q3, Q4):
- changes are paused: `overview.paused_reason = "engine.caddy"`, writes get `409 control.paused`;
- **share links are off**: minting is `409 share.engine_caddy`, and a visitor with a link gets the
normal sign-in (fails closed). Caddy cannot check a share token and control never serves
visitors; a validator Caddy calls through `forward_auth` is planned before v1.1;
- device revocations restart caddy-fallback (Caddy reads the allow list when it starts).
## 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 /certs`, `POST /certs/devices`, `DELETE /certs/devices/{id}`, `POST /certs/devices/{id}/bundle` | the Domi CA screen, device requests, revocation, one-time install files |
| `POST /certs/intermediate/renewal`, `GET/DELETE /pki-requests/{id}`, `GET /pki-requests/{id}/csr`, `GET /pki-requests/{id}/ext`, `PUT /pki-requests/{id}/certificate` | renewals and approvals |
| `GET /device-bundles/{token}` | the one-time PKCS#12 download (no token; the link is the secret) |
| `GET /engine`, `POST /engine` | which engine serves; switch |
| `GET /openapi.json` | the OpenAPI document |