Files

21 KiB

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; 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 (/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:

    { "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):

cargo build -p ianitor-edge -p ianitor-control      # so --dev finds ianitor-edge next to it
cargo run -p ianitor-control -- --dev
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:

ianitor-control token create --name mark-laptop --config /etc/ianitor/control.toml

The examples use:

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

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}'
{ "state": "queued", "id": "ch_b720484831a9" }
curl -s -H "$H" "$API/applies/ch_b720484831a9" | jq '{state, summary, reason: .reason.message, steps: [.steps[] | "\(.key)=\(.state)"]}'
{ "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"] }
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:

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}]}'
{ "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.

curl -s -H "$H" "$API/undo" | jq '{available, target: .target.summary, effect}'
{ "available": true, "target": "Added app.dev.test", "effect": "Removes app.dev.test" }
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}:
{ "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"] }
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):

curl -s -H "$H" "$API/history?limit=5" | jq '[.entries[] | {change_id, summary, state}]'
[ { "change_id": "ch_cf0b434ecb4c", "summary": "Undid: Added app.dev.test", "state": "kept" },
  { "change_id": "ch_b720484831a9", "summary": "Added app.dev.test", "state": "kept" } ]
curl -s -H "$H" "$API/history/ch_b720484831a9/restore-preview" | jq '{restorable, changes}'
{ "restorable": true, "changes": [{ "effect": "added", "fields": [], "hostname": "app.dev.test" }] }
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}:
{ "state": "kept", "summary": "Restored the version of 7 November 2026",
  "reason": "app.dev.test is live. Health checks passed for 10 s." }
visit app.dev.test https://app.dev.test:18443/      # 200

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):

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}'
{ "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:

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):

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

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:

# hosts/ianitor.example.toml
hostname = "ianitor.example"
upstreams = ["unix:/run/ianitor-control/ui.sock"]   # [ui] socket (the NixOS module's default)
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.
  • The UI socket (G14 option b, phase 4). With [ui] socket = "/run/ianitor-control/ui.sock" (the NixOS module sets it; services.ianitor.ui.socket, default on), control also serves the API on that Unix socket, mode 0660, in its runtime directory (0750, ianitor-control:ianitor): only the ianitor group (edge, caddy-fallback) can connect, and no other user can create a socket there. The proof then counts only on the socket: over the loopback port it is 401 ui.no_proof even when it is right. Why: any local process can reach 127.0.0.1:7878, and one that took that port while control restarted would receive edge's requests, proof and all. The admin host's upstream is unix:/run/ianitor-control/ui.sock; control refuses a socket upstream on any other host, and any socket other than its own (host.upstream.unix_socket). The loopback port stays for API tokens (scripts, the CLI, the trial's SSH tunnel).
  • [ui] logout_url (Authelia's logout address) becomes overview.site.auth_logout_url, the UI's "Sign out".

Certificates (the Domi CA)

Everything is in pki.md; the calls:

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 -X POST -o phone.p12 "$DOWNLOAD_URL"   # once; a second try is 410 pki.bundle_used (GET is only its page)
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)

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 and stop) 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, first come first served: a queued switch runs right after the apply in progress, before any apply queued after it). Back on Pingora, edge is reloaded so it serves what was applied while Caddy served. Every switch, kept or gone back, ends by telling the engine that serves to read the device files again; a device change during a switch only writes them and shows devices_problem ("an engine switch is under way") until then, and the 2 s retry tells the serving engine too. Refusals: engine.unmanaged (no [engine] in control.toml), engine.same, engine.switching, engine.not_ready (Caddy's settings cannot be built from the current routes).

While Caddy serves (decisions Q3, Q4; Mark 2026-11-08):

  • changes keep working: applies, Undo and Restore go through the same pipeline. Both outputs are compiled; the trial is loaded into Caddy through its admin API (POST /load on the Unix socket [compile_caddy] caddy_admin_socket, /run/caddy-fallback/admin.sock under NixOS, group ianitor-caddy-admin: control and Caddy, not edge), and a revert loads the previous caddy.json again. Every load sends Cache-Control: must-revalidate, so Caddy reads its certificate and device files again even when the config is unchanged. The watch judges health as edge does: control probes the upstreams itself with edge's rules (health check: GET <path>, Host = the upstream, 2xx; none: GET /, Host = the hostname, below 500), and a probe through Caddy only asks that Caddy answers at all (any status, its sign-in redirect included). Each round also checks that Caddy still runs the trial (GET /config/); if anything else reloaded it, the change is undone as apply.reverted.edge_lost. Without caddy_admin_socket an apply under Caddy fails with apply.failed.reload and nothing changes;
  • an unconfirmed trial never outlives control, as with edge: control arms a deadline (caddy-trial.json in its state directory: watch + margin) before loading the trial and claims it right after the journal says confirmed (a crash in between leaves both, and recovery promotes). A guard revert counts only once Caddy is verified on caddy.json; a failed load is retried with a growing pause. With Pingora serving, caddy-revert only clears a stale deadline. ianitor-caddy-guard (a unit that runs with caddy-fallback, ianitor-control caddy-guard) reverts a trial past its deadline, which covers a hung control; ianitor-control's ExecStopPost=ianitor-control caddy-revert reverts at once after any stop or crash. Whoever renames the deadline file first wins, so a trial is either kept or reverted;
  • device issues and revocations never wait for an apply: the files are written and edge is told at once. Under Caddy, Caddy is reloaded at once and checked to serve the certificate on disk for a Domi host (else devices_problem, retried), except while a trial is out: then the end of that apply (promote or revert, both load caddy.json) brings the new files in;
  • share links are off: minting is 409 share.engine_caddy, and a visitor with a link gets the 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;

A revocation is in force only once the serving engine has the new list. If the list cannot be written or the engine does not take it, DELETE /certs/devices/{id} answers 503 pki.devices_unwritten (the revocation itself is recorded), GET /certs carries devices_problem until it is fixed, and control retries every 2 s; repeating the DELETE is safe and nudges the engine again. Edge also re-reads the device files by itself every 5 s.

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 link's page with a Download button (uses nothing up: link previews only GET)
POST /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