From 027bf3a553db6022149ac98bfbc5fe7724c153c0 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 17:22:53 +0100 Subject: [PATCH 01/38] [docs] UI API: the designer's contract for Phase 3 --- docs/ui-api.md | 436 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 436 insertions(+) create mode 100644 docs/ui-api.md diff --git a/docs/ui-api.md b/docs/ui-api.md new file mode 100644 index 0000000..25f9627 --- /dev/null +++ b/docs/ui-api.md @@ -0,0 +1,436 @@ +> This file is the web UI's contract with the control API for Phase 3 (from the designer; deviations are listed at the end). + +# Ianitor Domi: what the web UI needs from the Phase 2 API + +From the UI design (claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u, 9 boards) and ROADMAP §3, §4, §6, §10. +Shapes are resource + method + fields, not OpenAPI. Sources: [D] drawn on a board, [R] ROADMAP, [C] current code, [J] my call. + +## 0. Ground rules for every call + +- Base path `/api/v1`, JSON, times RFC 3339 UTC. The UI formats times in the browser's zone ("Today 14:02"). +- Every response carries `server_time`. The UI counts down from `ends_at - server_time`, never from the browser clock. +- Errors use one envelope: + ``` + { "error": { "code": "host.hostname.taken", "message": "", + "field": "hostname" | null, "params": { ... }, "retry_after_s": null }, + "errors": [ ...same shape, for several field errors... ], "request_id": "01J..." } + ``` + `code` is stable and is what the UI switches on. `message` is the §3 text, filled by the server, so curl users get the same words. + `params` holds the values in the message (hostname, address, counts, dates) so the UI can bold them. + A technical detail (core's own error text, log lines) goes only in `detail`, shown behind "Show details". It never holds a secret value or a token. +- Writes take an `Idempotency-Key` header, one per click. An apply can reload the proxy the UI talks through, so a dropped POST gets retried, and the retry must not apply twice. +- Writes that change routes take `base_rev`: the routes-tree commit the form was loaded from. The server refuses only if *the same host file* changed since then (§3 `change.conflict`). A change elsewhere in the tree is fine, so queued applies don't refuse each other. +- The UI sends `X-Ianitor-UI: 1` on every request, as a CSRF guard: control refuses browser-origin writes without it. Who the user is comes from the Authelia `Remote-User` that edge forwards (see gap G14). + +## 1. Per flow + +### 1.1 Main screen (desktop and phone boards) [D] + +**One call: `GET /overview`.** Yes, one call is possible, as long as control keeps a cached copy of health (edge pushes it or control pulls every 2 s; see G1). The request must never wait on a live probe. + +| Block | Fields | Shown as | +|:--|:--|:--| +| `counts` | `hosts, healthy, degraded, down, unknown` | "7 hosts · 5 healthy, 1 degraded, 1 down" | +| `hosts[]` | `hostname, upstreams[] (url), tls ("domi"\|"letsencrypt"), auth ("none"\|"forward-auth"), websockets, share_links, added_at` | row, chips, "Added today" | +| `hosts[].health` | `state ("healthy"\|"degraded"\|"down"\|"unknown"\|"pending"), last_check_at, latency_ms (nullable), since, failure {kind, upstream, count, of} \| null, upstreams[] {url, state, last_check_at, latency_ms, failure_kind}` | dot + word, "Checked 8 s ago · 42 ms", "Connection refused for 6 minutes" | +| `hosts[].certificate` | `state ("ok"\|"pending"\|"failed"), not_after, error_code` | extra line only when not `ok` | +| `engine` | `running ("pingora"\|"caddy"), state ("running"\|"switching"\|"stopped"), since, fallback_ready {built_at, compared, matched} \| null` | engine chip; popover (switch flow) | +| `last_apply` | the most recent apply record (§2), any outcome, or null | last-change bar: state word, summary, sub-line | +| `undo` | see §2.3 | the Undo button and its name | +| `active_apply` | `{id, state, summary, seconds_left}` \| null, plus `queued` (count) | "Applying wiki.home.example: 41 s left" when the user comes back to the main screen | +| `repo` | `name, last_push_at, unpushed (count), push_error_code` \| null | footer "Last pushed to Gitea at 14:03" | +| `intermediate` | `not_after, days_left, renewal {request_id, state, match_code, expires_at} \| null`; **null until Phase 3** | banner when `days_left <= 30` or `renewal` is open | +| `site` | `forward_auth_configured, acme_configured, secrets[] (names only), watch_seconds (60)` | add-host form: disables "Sign in first" if Authelia is not set up; secret picker in headers | +| `paused` | `{code, message}` \| null | full-width notice; disables + Host, Undo, Restore | + +Health `state` rules for the UI [J]: `healthy` = every upstream passed its last check. `degraded` = some passed, some failed, or the last 5 checks were mixed. `down` = no upstream passed the last check. `unknown` = no health check set. `pending` = added but not yet checked. The drawn "slow: 2.8 s, limit is 2 s" has no basis in the schema (see G2). + +Polling: every 5 s while the tab is visible, every 30 s when hidden. Send `If-None-Match` with the ETag and expect `304` when nothing changed. + +Clicks on the main screen: + +| Click | Call | +|:--|:--| +| + Host | none (opens the panel) | +| Undo | `POST /undo` (§1.3) | +| Renew (banner) | `POST /certs/intermediate/renewal` (Phase 3, §1.8) | +| ⋯ on a row | none (menu) | +| ⋯ → Edit host | `GET /hosts/{hostname}` → returns the full host (all §3 ROADMAP fields) + `rev` | +| ⋯ → Show in history | `GET /history?host={hostname}` | +| ⋯ → Remove host | `DELETE /hosts/{hostname}?base_rev=` → `202` apply. No confirmation dialog: Undo restores the host in 1 click [J] | +| Engine chip | none (popover from `engine`) | + +### 1.2 Add host: + Host → fill → Apply = 2 clicks [D][R] + +| State | Call | Shows | +|:--|:--|:--| +| Panel open | none; values come from `overview.site` | hostname focused; form defaults Domi certificate, Sign in first [D] (the UI always sends explicit values; schema defaults are letsencrypt and none [C]) | +| Typing (field blur, not a click) | `POST /hosts/validate` body = host, `?mode=create` | inline field errors (§3.1), including a taken hostname, before Apply | +| **Apply (click 2)** | `POST /hosts` body = `{host, base_rev}` | `422` with `errors[]` → keep the panel, mark the fields. `202 {apply}` → the panel shows the apply steps (§2) | +| Watching | `GET /applies/{id}` every 1 s (§2.2) | checklist + "41 s left" + progress bar | +| Kept | (final poll) | panel closes; the row appears; the bar shows `kept` + Undo | +| Reverted | (final poll) | panel stays open with the user's values; banner with the reason; "Edit and try again" focuses the field the reason names (`reason.field`, e.g. `upstreams[0]`) | + +Host body (mirrors the TOML [C]): +`hostname, upstreams[] (strings), tls, auth, websockets, share_links, access_log ("off"|"truncated"), health_check {path, interval_secs} | null, request_headers[] / response_headers[] {action ("set"|"remove"), name, value | secret}`. + +### 1.3 Undo last change = 1 click [D][R] + +- Data: `overview.undo` (§2.3). The button reads **Undo** with the target's name beside it in the bar. +- Click: `POST /undo {target_change_id}` → `202 {apply}`, with the same states as any apply. The server refuses with `409 undo.target_moved` if the target is no longer the latest kept change, so Undo never undoes something it did not name. +- During its own watch, Undo is disabled with "Wait for the check to finish (41 s)". If a *different* apply is running, Undo is queued like any change. + +### 1.4 Restore: History → pick → Restore = 3 clicks [D][R] + +| Click | Call | Fields shown | +|:--|:--|:--| +| 1 History | `GET /history?limit=50` (`before=` for more) | `entries[] {change_id, summary, kind ("add"\|"edit"\|"remove"\|"undo"\|"restore"\|"share_links"), state ("kept"\|"reverted"\|"failed"\|"queued"\|"running"), at, commit_short, hosts[], reason_short}` ("port refused") | +| 2 pick | `GET /history/{change_id}/restore-preview` | `restorable` (false for reverted or failed entries, which instead offer "Edit and try again" using `GET /history/{id}` → `attempted_host`), `same_as_current`, `changes[] {hostname, effect ("added"\|"removed"\|"changed"), fields[] {field, from, to}}` | +| 3 Restore this version | `POST /restore {change_id, base_rev}` | `202 {apply}` → bar: "Restored the version of 3 Nov, 09:30" | + +- History must show one entry per user action. An attempt that was reverted is one `reverted` entry, not a commit row plus a revert row. Control groups them. +- The UI writes the preview sentences from `fields[]` with this label map, so the wording is the same everywhere: 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", access_log "visit log", websockets "websockets", headers "header rules". +- Drop the drawn line "wiki.home.example is not affected (never kept)". The preview lists only real differences. + +### 1.5 Share link: ⋯ → Share link → Copy = 3 clicks [D][R] + +| Click | Call | Fields | +|:--|:--|:--| +| 1 ⋯ | none | menu; "Share link" is enabled when the host's `share_links` is true (from overview) | +| 2 Share link | `POST /hosts/{hostname}/share-links {path_prefix: "/", expires_in_s: 604800}` → `201` | `id, url, expires_at, path_prefix, has_password` | +| 3 Copy link | none (client clipboard only, so the copy happens inside the click) | "Copied. Expires on 14 November 2026 at 14:20." | +| Change expiry or prefix, add a password (extra clicks) | `POST /hosts/{h}/share-links {..., replaces: }` | the new link; the server stops the one it replaces. A link minted on open and never copied doesn't stay valid | + +- Expiry options in the UI: 1, 7, 30 days. The server accepts 1 hour to 90 days [J]. +- Password: `password` in the POST body; at least 8 characters [J]; never returned. +- Links off for this host: the dialog shows "Turn on share links and apply". Clicking it calls `PATCH /hosts/{h} {share_links: true, base_rev}` → `202 {apply}`. After `kept`, the UI auto-calls the mint POST and shows the link; Copy is click 4 (G10). +- Host with `auth = none`: the dialog says anyone can already open it. Mint anyway if asked; the UI does not block it. +- Settings → Share links: `GET /share-links` → `items[] {id, hostname, path_prefix, created_at, expires_at, has_password, state ("active"|"expired"|"stopped")}`. "Stop this link" calls `DELETE /share-links/{id}` → `204`. "Stop all share links" calls `POST /share-links/stop-all` (G8). + +### 1.6 API token: ⚙ → API → New token = 3 clicks [D][R] + +| Click | Call | Fields | +|:--|:--|:--| +| 1 Settings | `GET /settings` | `repo {name, last_push_at}, watch_seconds` (read-only in v1) | +| 2 API tab | `GET /tokens` | `items[] {id, name, created_at, last_used_at, expires_at \| null}`; never a hash or a prefix | +| 3 New token | `POST /tokens {name?}` → `201 {id, name, token, expires_at}` | the token is shown once and returned only in this response. The UI drops it from memory when the dialog closes | +| Rename (optional) | `PATCH /tokens/{id} {name}` | | +| Revoke | `DELETE /tokens/{id}` → `204` | the row goes to "Revoked today 14:40" until the next reload | + +- Recommendation that removes the 4th click (G12): click 3 is **Make and copy token**. The UI calls `navigator.clipboard.write([new ClipboardItem({"text/plain": tokenPromise})])` inside the click, so the copy belongs to that click even though the POST is async. The POST must answer in under 1 s. The dialog then says "Copied. Paste it into Custos now." and keeps a Copy again button. +- Default lifetime 365 days, or "Never expires" as an option [J]. Expiry is needed for the expired-token message in §3. + +### 1.7 Device certificate (Phase 3): Certificates → + Device → Issue = 3 clicks [D][R] + +| State | Call | Fields | +|:--|:--|:--| +| 1 Certificates | `GET /certs` | `intermediate {subject, not_after, days_left}`, `root {offline: true}`, `devices[] {id, name, kind ("phone"\|"computer"\|"app"), not_after, state ("valid"\|"revoked"\|"expired")}`, `device_lifetime_days` | +| 2 + Device | none | form | +| 3 Issue | `POST /certs/devices {name, kind}` → `202 {request_id, match_code, expires_at}` | "47 19 83", "The request stays open for 10 minutes" | +| Waiting | `GET /pki-requests/{id}` every 2 s | `state ("waiting"\|"approved"\|"denied"\|"expired"\|"cancelled"\|"failed"), approved_at, device_id` | +| Cancel request | `DELETE /pki-requests/{id}` | | +| Issued, install (click 4) | `POST /certs/devices/{id}/bundle {format: "p12"\|"qr"}` → `{download_url, one_time_password, expires_at}` | one download only, then deleted; QR encodes `download_url` (G15) | +| Revoke a device | `DELETE /certs/devices/{id}` | | + +### 1.8 Renew intermediate (Phase 3): banner Renew = 1 click [D][R] + +- Click: `POST /certs/intermediate/renewal` → `202 {request_id, match_code, expires_at}`. The banner turns into the match code and "Approve it in Custos". +- Then `GET /pki-requests/{id}` every 2 s. Once `approved`, `overview.intermediate.not_after` moves on and the banner says "Renewed. The Domi intermediate certificate is now valid until 30 November 2027." for this session. +- Banner states the UI needs: `due` (≤ 30 days), `urgent` (≤ 7 days, uses the `down` colour), `waiting` (match code), `expired`, `failed` (§3.6). + +### 1.9 Switch engine (not in this brief's scope, but on the main screen) + +`overview.engine` is enough to draw the chip and the popover. The switch call (`POST /engine {target}` → `202`, polled like an apply) waits on Mark's decision (b) in §10. + +## 2. Apply outcomes + +### 2.1 The apply record + +`GET /applies/{id}` (also embedded as `last_apply` and in every `202`): + +``` +id, change_id, kind, summary ("Added wiki.home.example"), hosts[], state, created_at, finished_at, +steps[] { key ("validate"|"compile"|"write"|"reload"|"watch"|"push"), state ("pending"|"running"|"done"|"failed"|"skipped") }, +queue { position, waiting_for { apply_id, summary, seconds_left } } | null, +watch { ends_at, seconds_left, hosts[] { hostname, passed, failed, total } } | null, +reason { code, message, hostname, upstream, field, count, of } | null, +commit_short | null, push { state ("pushed"|"pending"|"failed"), at, error_code, next_try_at } | null, +undo_of | null, restore_of | null +``` + +| `state` | When | The UI shows (copy in §3.2) | +|:--|:--|:--| +| `queued` | another apply is running | "Waiting for 'Added recipes.home.example' to finish (about 40 s)." + Cancel (`DELETE /applies/{id}`, allowed only while queued) | +| `validating` | checking the files again in the queue | step 1 running | +| `applying` | compile, write, reload | steps 2–3 running | +| `watching` | the 60 s health watch | step 4, "41 s left", progress `60 - seconds_left` of 60 | +| `kept` | passed; committed | bar `kept`; push sub-state below | +| `kept` + `push.state = failed` | kept, but Gitea refused or did not answer | bar `kept` + "Not yet saved to Gitea" + Try now (`POST /repo/push`) | +| `reverted` | failed the watch; undone | banner `reverted` + `reason.message` + Edit and try again | +| `failed` | never went live (validation in the queue, compile, reload refused) | banner + reason; nothing changed | +| `interrupted` → `reverted` | control restarted mid-apply | reason `apply.interrupted` | +| `needs_attention` | the revert itself failed | red banner, Restore last kept version (§3.2) | + +Watch rule recommendation [J]: watch only the hosts this change touches. A host that was already down before the change is no reason to revert. A touched host fails if it has no healthy upstream for 3 checks in a row, or none at the end of the 60 s. During the watch, edge checks touched hosts every 5 s whatever their interval, so a watch has about 12 checks, not 6. Removing a host has nothing to watch: `watch` is `skipped` and the result is `kept`. Hosts without a health check: see G3. + +### 2.2 How the UI learns progress: polling, 1 s + +**Pick: polling `GET /applies/{id}` every 1 s while the state is queued, validating, applying or watching; then stop.** + +Why not SSE: +1. The browser reaches control *through the proxy the apply reloads*: edge with forward-auth, or Caddy after a switch. A graceful reload either holds the old process open for a long-lived stream or cuts it at the drain timeout. A revert reloads a second time. Every apply would break the SSE stream at its most important moment. A 1 s poll just retries. +2. Engine switches and control restarts drop every connection too. Polling needs no resume logic; SSE needs `Last-Event-ID` replay. +3. Cost is trivial: one small JSON per second on loopback, 60 per apply, one apply at a time. +4. Smoothness: the UI counts down locally from `watch.ends_at - server_time` between polls, so the seconds tick evenly even if a poll is late. + +Errors while polling: retry quietly for 10 s (a reload takes about 2 s), then show `ui.lost_contact` and keep polling every 5 s. + +### 2.3 What the Undo bar needs + +`overview.undo`: +``` +available, target { change_id, summary, kept_at, commit_short } | null, +effect ("Removes recipes.home.example"), blocked { code, message } | null +``` +- The target is always the latest **kept** change, never a reverted or failed one. +- Right after a reverted apply, the bar has two lines. Line 1 is `last_apply`: "`reverted` wiki.home.example was not added. Reason: …". Line 2 is the Undo button labelled with `undo.target.summary`: "Undo: Added recipes.home.example". The two lines come from two fields, so the bar always names what Undo will touch. +- After an Undo is kept, the latest kept change *is* the undo, so Undo again redoes it. `summary` for an undo reads "Undid: Added recipes.home.example", and `effect` reads "Adds recipes.home.example back". The button then says "Undo: Undid Added recipes.home.example", with the effect line under it. +- `blocked` codes: `undo.nothing` (no kept change yet), `undo.watching` (its own apply is still running), `undo.paused` (§3.2 needs_attention or repo paused). + +## 3. Every user-facing message + +`{x}` are `params`. Bold in the UI: hostnames and addresses. Tone: say what happened, what still works, and what to do. No "error", "failed to", "invalid", status codes, or protocol names. + +### 3.1 Host form validation (one row per core error [C]; `field` in brackets) + +| Code | Field | Message | UI offers | +|:--|:--|:--|:--| +| `host.hostname.missing` | hostname | Enter the address people will type, like wiki.home.example. | focus | +| `host.hostname.uppercase` | hostname | Use lowercase letters only: {suggestion}. | "Use {suggestion}" (fills it) | +| `host.hostname.characters` | hostname | Use only letters a–z, digits, dots and dashes. | focus | +| `host.hostname.spaces` | hostname | Remove the spaces from the address. | focus | +| `host.hostname.wildcard` | hostname | Addresses with * are not supported yet. Add each name as its own host. | focus | +| `host.hostname.trailing_dot` | hostname | Remove the dot at the end. | "Use {suggestion}" | +| `host.hostname.empty_label` | hostname | There are two dots in a row. Remove one. | focus | +| `host.hostname.label_dash` | hostname | A part of the address cannot start or end with a dash. | focus | +| `host.hostname.label_long` | hostname | Each part between dots can be at most 63 characters. | focus | +| `host.hostname.too_long` | hostname | The address can be at most 253 characters. | focus | +| `host.hostname.numeric` | hostname | That looks like an IP address. Use a name, like wiki.home.example. | focus | +| `host.hostname.taken` | hostname | {hostname} is already a host. | "Open {hostname}" (edit form) | +| `host.upstreams.missing` | upstreams | Enter where Ianitor should send traffic, like http://10.0.0.23:3000. | focus | +| `host.upstream.not_url` | upstreams[i] | Write it as a full address, like http://10.0.0.23:3000. | focus | +| `host.upstream.scheme` | upstreams[i] | Start the address with http:// or https://. | focus | +| `host.upstream.no_host` | upstreams[i] | Add the server's name or IP address after http://. | focus | +| `host.upstream.no_port` | upstreams[i] | Add the port at the end, like :3000. | focus | +| `host.upstream.port_zero` | upstreams[i] | Port 0 cannot be used. Enter the port the service listens on. | focus | +| `host.upstream.path` | upstreams[i] | Leave out the path after the port. Visitors keep their own path. | "Use {suggestion}" | +| `host.upstream.query` / `.fragment` | upstreams[i] | Leave out everything after ? or #. | "Use {suggestion}" | +| `host.upstream.credentials` | upstreams[i] | Leave out the user name and password. Put them in a header rule with a secret instead. | open More options → Headers | +| `host.upstream.duplicate` | upstreams[i] | This address is listed twice. | "Remove it" | +| `host.upstream.mixed_schemes` | upstreams | All addresses for one host must start the same way: all http:// or all https://. | focus | +| `host.upstream.too_many` | upstreams | One host can send traffic to at most {max} addresses. | — | +| `host.auth.not_configured` | auth | 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. | the option is disabled up front when `site.forward_auth_configured` is false; the hint says why | +| `host.header.name` | {list}[i].name | "{name}" cannot be a header name. Use letters, digits and dashes. | focus | +| `host.header.value` | {list}[i].value | This value has characters a header cannot carry. Use visible characters and spaces only. | focus | +| `host.header.empty` | {list}[i].value | Enter a value, or choose Remove to drop the header. | switch to Remove | +| `host.header.protected` | {list}[i].name | Ianitor sets {name} itself, so a rule cannot change it. | — | +| `host.header.duplicate` | {list}[i].name | {name} already has a rule in this list. | jump to that rule | +| `host.header.both` | {list}[i] | Choose a fixed value or a secret, not both. | — | +| `host.header.remove_value` | {list}[i] | Remove needs only the header name. | clear the value | +| `host.header.secret_unknown` | {list}[i].secret | There is no secret named {secret}. Secrets are listed in ianitor.toml and loaded from the server's credentials. | picker shows `site.secrets` | +| `host.header.secret_response` | response_headers[i] | Secrets can only be sent to your service, never back to visitors. | move to request headers | +| `host.health.path` | health_check.path | Start with / and use plain characters, like /health. | focus | +| `host.health.interval` | health_check.interval_secs | Check every 1 to 3600 seconds. | focus | +| `host.field.unknown` | {field} | Ianitor does not know the setting "{field}". | (API clients only) | +| `change.conflict` | — | {hostname} was changed at {time} ("{summary}") after you opened it. Your edits are still here. Check them, then Apply again. | "Show the new version" | +| `host.not_found` | — | {hostname} is no longer a host. It was removed at {time}. | back to the list | + +Warning, not an error: `host.share.no_signin`: "Anyone can already open {hostname}, so a share link changes nothing." It appears in the share dialog and the form; it doesn't block anything. + +### 3.2 Apply, undo, restore, repository + +| Code | Message | UI offers | +|:--|:--|:--| +| `apply.queued` | Waiting for "{summary}" to finish, about {seconds} s. | Cancel | +| `apply.kept` | {hostname} is live. Health checks passed for 60 s. Saved and sent to Gitea. | Undo | +| `apply.kept.no_watch` | {hostname} is live. It has no health check, so Ianitor only checked that it answers. | Add a health check (edit form) | +| `apply.reverted.refused` | {hostname} was not {verb}. {upstream} refused the connection on {count} of {of} checks. Ianitor undid the change; every other host kept running. | Edit and try again | +| `apply.reverted.timeout` | {hostname} was not {verb}. {upstream} did not answer within 5 seconds on {count} of {of} checks. Ianitor undid the change. | Edit and try again | +| `apply.reverted.not_found` | {hostname} was not {verb}. {upstream} says {path} does not exist. Check the health check address. Ianitor undid the change. | Edit health check | +| `apply.reverted.server_error` | {hostname} was not {verb}. {upstream} answered with an error page on {count} of {of} checks. Ianitor undid the change. | Edit and try again | +| `apply.reverted.redirect` | {hostname} was not {verb}. {upstream} sent visitors elsewhere instead of answering {path}. Use an address that answers directly, like /health. | Edit health check | +| `apply.reverted.sign_in` | {hostname} was not {verb}. {upstream} asked for a sign-in on {path}. Use an address that answers without signing in. | Edit health check | +| `apply.reverted.name` | {hostname} was not {verb}. The name {upstream_host} could not be found on this network. | Edit and try again | +| `apply.reverted.tls` | {hostname} was not {verb}. {upstream} uses https://, but its certificate could not be checked. | Edit and try again | +| `apply.failed.reload` | {engine} did not take the new settings, so nothing changed. Every host kept running. | Show details | +| `apply.failed.build` | Ianitor could not build the settings for this change, so nothing changed. | Show details | +| `apply.failed.validation` | This change no longer fits with the routes: {first_error}. Nothing changed. | Edit and try again | +| `apply.interrupted` | Ianitor restarted during the check, so it undid the change to be safe. | Try again | +| `apply.needs_attention` | The change failed its check, and Ianitor could not undo it by itself. Visitors are served the last good settings, but the routes repository still has the change. | Restore last kept version (1 click, `POST /restore` with `undo.target`) | +| `push.failed.unreachable` | Kept, but not yet saved to Gitea: Gitea did not answer. Ianitor tries again at {time}. | Try now | +| `push.failed.rejected` | Kept, but Gitea has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server. | Show details | +| `push.failed.auth` | Kept, but Gitea refused Ianitor's access key. Check the key in Custos. | Try now | +| `undo.nothing` | Nothing to undo yet. | — | +| `undo.watching` | Wait for the check to finish ({seconds} s). | — | +| `undo.target_moved` | The last change is now "{summary}", so Undo did nothing. Look again and choose. | bar refreshes | +| `restore.same` | This version is the same as the current one. Nothing to restore. | Close | +| `restore.not_kept` | This change was undone at the time, so there is nothing to go back to. | Edit and try again | +| `repo.unreadable` | {file} in the routes repository cannot be read (line {line}). Changes are paused until it is fixed. | Show details | + +`{verb}` is "added", "changed" or "removed", from the change kind. `{engine}` is "Pingora" or "Caddy"; product names are allowed. + +### 3.3 Host health lines (main screen) and visitor errors + +| `failure.kind` | Row line | +|:--|:--| +| `refused` | Connection refused for {duration}. Visitors see a "not reachable" page. | +| `timeout` | Not answering for {duration}. Visitors see a "not reachable" page. | +| `name` | The name {upstream_host} cannot be found. Visitors see a "not reachable" page. | +| `tls` | The certificate of {upstream} cannot be checked. | +| `bad_answer` | Answering with an error page for {duration}. | +| partial (degraded) | {n} of {m} addresses answer. Visitors are sent to the ones that do. | +| `unknown` | No health check set for this host. | +| `pending` | Waiting for the first check. | +| cert `pending` | Waiting for Let's Encrypt to issue the certificate. | +| cert `failed` | Let's Encrypt could not confirm {hostname}. The name must point to this server, and port 80 must be open from the internet. — offers Try again | +| `health.unavailable` (global) | Ianitor cannot read health from {engine} right now. Traffic is not affected. | + +### 3.4 Share links + +Admin side: + +| Code | Message | UI offers | +|:--|:--|:--| +| `share.disabled` | Share links are off for {hostname}. Turning them on is a change to the host, checked like any other. | Turn on share links and apply | +| `share.prefix` | Start with /, like /share/summer-2026. / shares the whole site. | focus | +| `share.expiry` | Choose between 1 hour and 90 days. | — | +| `share.password_short` | Use at least 8 characters. | focus | +| `share.stopped` | Stopped. The link stops working within a few seconds. | — | +| `share.stopped_all` | All share links are stopped. New ones work as usual. | — | +| `share.engine_caddy` | Share links are paused while Caddy serves. They work again after switching back. (Only if G7 is not solved.) | — | + +Visitor side (pages in §4): + +| Code | Heading | Text | Offers | +|:--|:--|:--|:--| +| `share.visit.password` | This link is protected | Someone shared {hostname} with you. Enter the password they gave you. | Password field, Open | +| `share.visit.wrong_password` | (same page) | That password is not right. Check it with the person who sent the link. | field cleared and focused | +| `share.visit.too_many` | (same page) | Too many tries. Wait a minute, then try again. | button disabled | +| `share.visit.expired` | This link has expired | It worked until {date}. Ask the person who sent it for a new one. | Have an account? Sign in | +| `share.visit.invalid` (stopped, altered, other host, share links turned off) | This link no longer works | It may have been stopped, or not copied in full. Ask the person who sent it for a new one. | Have an account? Sign in | +| outside the prefix | — (no page) | the request goes to the normal sign-in, as if there were no link | — | +| `visit.unreachable` | This site is not reachable right now | The service behind this address is not answering. It is not your connection. Try again in a few minutes. | Try again | + +Don't tell "stopped" apart from "altered": both use `invalid`. "Expired" is told apart because the signature proves the date. + +### 3.5 API tokens, sign-in, limits, connection + +| Code | Message | Who sees it | Offers | +|:--|:--|:--|:--| +| `token.missing` | This request needs an API token. Make one in Settings, API. | script | — | +| `token.unknown` | This API token is not one Ianitor issued, or it was copied incompletely. | script | — | +| `token.expired` | This API token expired on {date}. Make a new one in Settings, API, then revoke this one. | script | — | +| `token.revoked` | This API token was revoked on {date}. | script | — | +| `token.created` | Copied. Paste it into Custos now. Ianitor cannot show it again. | UI | Copy again, I have saved it | +| `token.revoke_done` | Revoked. Anything using "{name}" stops working now. | UI | — | +| `rate.limited` | Too many requests in a short time. Try again in {seconds} s. | both; UI retries once by itself first | — | +| `ui.signed_out` | Your sign-in has ended. Sign in again; this page keeps what you typed. | UI | Sign in | +| `ui.lost_contact` | Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back. | UI | retries every 5 s | +| `control.paused` | Changes are paused: {reason}. Traffic keeps flowing. | UI | per reason | + +Detecting sign-out: when Authelia's session ends, edge returns its portal redirect as is. The UI uses `fetch(..., {redirect: "manual"})` and treats an `opaqueredirect` or a `401` as `ui.signed_out`. Nothing from control is needed. + +Rate limits [J]: 120 requests a minute per signed-in user or token; share-link mint 30 a minute; token creation 10 an hour. Wrong share passwords: 5 a minute per link and visitor /24. Answers carry `retry_after_s`. + +### 3.6 PKI (Phase 3) + +| Code | Message | Offers | +|:--|:--|:--| +| `pki.waiting` | Open Custos on your phone. Approve only if it shows the same code: {code}. | Cancel request | +| `pki.denied` | The request was turned down in Custos. Nothing was issued. | Try again | +| `pki.expired` | Nobody approved it within 10 minutes, so the request closed. Nothing was issued. | Try again | +| `pki.custos_unreachable` | Custos is not answering, so the request could not be sent. | Try again | +| `pki.device_name_taken` | A device named "{name}" already has a certificate. Use another name, or revoke the old one first. | Show it | +| `pki.issued` | {name} has a certificate. Approved in Custos at {time}. | Show QR code, Download file | +| `pki.bundle_used` | This download was already used. Make a new one from the device's row. | — | +| `pki.renew_due` | The Domi intermediate certificate expires in {days} days, on {date}. | Renew | +| `pki.renew_urgent` | The Domi intermediate certificate expires in {days} days. After that, Domi certificates stop working. | Renew | +| `pki.intermediate_expired` | The Domi intermediate certificate expired on {date}. Hosts with a Domi certificate are not trusted until it is renewed. | Renew | +| `pki.renewed` | Renewed. The Domi intermediate certificate is now valid until {date}. | — | + +## 4. Share-link visitor pages (served by edge) + +These are four pages: password prompt (with its wrong-password and too-many states), link expired, link no longer works, and service not reachable. + +**Build constraints** +- One self-contained HTML file per page with inline CSS, under 8 KB. No JavaScript, no external requests, no web fonts. These pages must work on a visitor's phone with nothing else loaded. System font stack: `system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`. +- Headers: `Cache-Control: no-store`, `Referrer-Policy: no-referrer`, `X-Robots-Tag: noindex`, `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; form-action 'self'`. `lang="en"`. Status codes are not visible to visitors: prompt 401, expired 410, invalid 403, not reachable 502. +- Password form: `POST` to a reserved path `/.well-known/ianitor/share` with hidden `t` (the token) and `password`. On success, edge sets an HttpOnly, Secure, SameSite=Lax cookie scoped to the host and `path_prefix` until the link's expiry. It then redirects to the prefix *without* `?share=` so the token never sits in the address bar or a referrer. A link without a password takes the same redirect at once. +- Only the hostname and the expiry date come from the request. Escape both. Nothing else from the request is echoed. + +**Layout** (murex palette, same on all four) +- `body`: background `#0c0b0f` (ground), text `#f1edf3`, margin 0. Centre one card vertically and horizontally; on a phone it sits 16 px from each edge. +- Card: max-width 420 px, padding 32 px (24 px under 480 px wide), background `#18151d` (surface), border 1 px `#3c3445`, radius 18 px. +- Top of the card: the hostname in `#cfc6d4`, 0.95 rem, weight 600, the only line that changes per host. Then the heading, 1.5 rem, weight 700, `#f1edf3`. Then body text, 1 rem, line-height 1.5, `#cfc6d4`. +- A 40 px stroke icon above the heading: a lock for the prompt, a clock for expired, a broken link for invalid, a cloud with a slash for not reachable. Expired and invalid icons in `#d99a35`; not reachable in `#e2683a`; the lock in `#e0a3dc`. +- Password field: label "Password" above it, `#cfc6d4` 0.9 rem. Field height 48 px, background `#0c0b0f`, border 1 px `#7d7189`, radius 10 px, text `#f1edf3`. Focus: border `#e0a3dc` plus a 4 px ring `rgba(224,163,220,0.16)`. `autocomplete="current-password"`, `autofocus`. +- Primary button "Open": full width, 48 px high, radius 12 px. Fill: gradient top to bottom `#8d3b89` → `#76306f` 55% → `#5c2257`. Edge 1 px `#c77cc1`; label `#ffffff`, weight 700. Focus ring `#f2c9ee`. +- Error line under the field (wrong password, too many tries): `#e2683a`, 0.92 rem, with a small ring icon, announced with `role="alert"`. Never colour alone; the words carry it. +- Secondary link "Have an account? Sign in": `#e0a3dc`, underlined, 44 px tall hit area. It points to the host root without `?share=`. +- "Try again" on the not-reachable page: an outline button (border `#7d7189`, text `#f1edf3`), as a plain link to the same URL. +- Footer under the card, outside it: "IANITOR DOMI" in `#a99eb1`, 0.72 rem, letter-spacing 0.2em, uppercase. Small and plain; no other branding. + +**Copy, exactly** + +Password prompt: +> photos.home.example +> **This link is protected** +> Someone shared photos.home.example with you. Enter the password they gave you. +> Password [__________] +> [ Open ] +> The link works until 14 November 2026. + +Wrong password: the same page, with "That password is not right. Check it with the person who sent the link." under the field, which comes back empty. +Too many tries: the same page, with "Too many tries. Wait a minute, then try again." The Open button is disabled for that response. + +Link expired: +> photos.home.example +> **This link has expired** +> It worked until 14 November 2026. Ask the person who sent it for a new one. +> Have an account? Sign in + +Link no longer works: +> photos.home.example +> **This link no longer works** +> It may have been stopped, or not copied in full. Ask the person who sent it for a new one. +> Have an account? Sign in + +Not reachable (any host, shared or not; the main screen points to it): +> photos.home.example +> **This site is not reachable right now** +> The service behind this address is not answering. It is not your connection. Try again in a few minutes. +> [ Try again ] + +## 5. Gaps, and what I recommend + +| # | Gap | Recommendation | +|:--|:--|:--| +| G1 | Edge keeps health in memory with no way out [C: edge/src/health.rs keeps one healthy bit per upstream, no latency, no failure kind, no history]. The main screen, the watch and the revert reasons all need it. | Edge exposes a read-only status endpoint on a Unix socket only control can read. Per upstream: state, last check time, latency, failure kind, the last 5 results. Control caches it for `/overview`. Under Caddy, map the admin API's `/reverse_proxy/upstreams`; latency and failure kind are null there, and the UI hides them. | +| G2 | The boards show "degraded: slow, 2.8 s, limit is 2 s" and a history entry "health limit 2 s", but the schema has no latency limit (fixed 5 s timeout [C]). | No limit in v1. Degraded = some upstreams fail, or mixed results in the last 5 checks. I will correct the boards in Phase 3. | +| G3 | A host without a health check gives the 60 s watch nothing to judge, so "auto-kept or auto-reverted" is empty. A default check on / would revert apps that redirect to a login page (edge counts only 2xx as healthy [C]). | During the watch only, test each touched host without a health check by connecting and sending `GET /`; any answer below 500 counts as alive. Message `apply.kept.no_watch`. Don't add a default health check to new hosts. | +| G4 | ROADMAP doesn't say which hosts the watch judges. | Only the hosts the change touches; a host that was already down never triggers a revert. Check every 5 s during the watch. | +| G5 | Let's Encrypt issuance can take longer than 60 s and is not part of keep or revert. | Keep it out of the watch; report it as `hosts[].certificate` with its own messages and Try again. | +| G6 | Core validation errors are written per file in schema words (`{file}: upstream \`x\` is not usable: …`, "TOML") and carry no field path or stable code [C: core/src/error.rs]. | Add `code()`, `field()` and `params()` to `ValidationError`, using §3.1's codes and field paths. Keep the existing text as `detail`. The API maps code to the §3.1 message. | +| G7 | Under the Caddy fallback no one checks share tokens. Caddy cannot verify them, yet the engine popover promises "share links stay the same". | Compile share-link hosts for Caddy with `forward_auth` to a small validator on loopback, from the same core code. If that is too much for v1, show `share.engine_caddy` and change the popover copy. | +| G8 | ROADMAP revokes share links "by key rotation or a small deny list", but the key comes from systemd credentials, which control cannot rotate at runtime. A deny list that goes through the routes repo would make Stop wait 60 s and add a git commit. | Stop one link: a deny-list file outside git that edge reloads within 5 s, with no watch. Stop all: an `epoch` number inside every token and in the edge config; raising it ends every old link without changing the key. | +| G9 | "Optional password hash" inside a stateless token lets anyone holding the link guess the password offline. | The token carries only a "needs a password" flag. Edge checks `HMAC(key, link_id ‖ password)`, so guessing needs the server. Rate-limit in edge (§3.5). | +| G10 | Share link when links are off for the host: 4 clicks (handover c). Turning them on is an apply with a 60 s watch, and the clipboard needs a click after it. | Accept 4 for that path and say so in §4: "3 clicks, 4 if share links are off". The common path stays 3. | +| G11 | The link is minted when the dialog opens, so changing expiry or prefix would leave unused valid links behind. | `replaces` on the mint call stops the previous one (§1.5). | +| G12 | API token: copying is a 4th click (handover c). | Click 3 "Make and copy token" uses an async `ClipboardItem`; that needs the POST to answer in under 1 s. If Mark rejects writing a secret to the clipboard in the same click, accept 4. | +| G13 | Device cert: install is a 4th click (handover c), because approval in Custos is asynchronous. | Accept "3 to issue, +1 to install" in §4. No API change removes it. | +| G14 | The UI is identified by `Remote-User` from edge, but any local process can send that header to control on loopback. | The admin host's file sets a request header from a systemd-credential secret (an existing feature), and control requires it on every request. Alternatively, control listens on a Unix socket that only edge can reach. Plus the `X-Ianitor-UI` header against CSRF. | +| G15 | A device QR code must point to a download the tablet can reach, and control is loopback only. | A one-time download route on the admin host, served by edge to control, valid for 10 minutes and one use. Phase 3. | +| G16 | ROADMAP doesn't define Undo after an Undo. | "Revert the last kept commit" means a redo. Name it with `effect` (§2.3), so the button never surprises. | +| 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. | From 73a9f3da4573c354c66811b1240eef5995696a53 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 17:32:09 +0100 Subject: [PATCH 02/38] [core] Tests first: share tokens, prefix escapes, repo layout, exact host path, error codes (red) --- Cargo.lock | 2 + Cargo.toml | 2 + crates/core/Cargo.toml | 2 + crates/core/src/compile/edge.rs | 1 + crates/core/src/edge_config.rs | 5 +- crates/core/src/error.rs | 171 ++++++++++++++- crates/core/src/lib.rs | 4 +- crates/core/src/routes.rs | 61 ++++++ crates/core/src/share.rs | 370 +++++++++++++++++++++++++++++++ crates/core/src/validate.rs | 132 +++++++---- crates/core/tests/routes.rs | 233 ++++++++++++++++++++ crates/core/tests/schema.rs | 87 +++----- crates/core/tests/share.rs | 378 ++++++++++++++++++++++++++++++++ 13 files changed, 1342 insertions(+), 106 deletions(-) create mode 100644 crates/core/src/routes.rs create mode 100644 crates/core/src/share.rs create mode 100644 crates/core/tests/routes.rs create mode 100644 crates/core/tests/share.rs diff --git a/Cargo.lock b/Cargo.lock index be5f6ae..57d267c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1010,6 +1010,8 @@ version = "0.1.0" name = "ianitor-core" version = "0.1.0" dependencies = [ + "base64 0.22.1", + "ring", "serde", "serde_json", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 2259be2..f9d8cc9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,8 @@ serde_json = "1.0.145" toml = "1.2.1" thiserror = "2.0.17" url = "2.5.7" +ring = "0.17.14" +base64 = "0.22.1" tokio = { version = "1.48", features = ["full"] } bytes = "1.10" http = "1.3" diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 51de11d..93c7462 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -13,6 +13,8 @@ serde_json.workspace = true toml.workspace = true thiserror.workspace = true url.workspace = true +ring.workspace = true +base64.workspace = true [lints] workspace = true diff --git a/crates/core/src/compile/edge.rs b/crates/core/src/compile/edge.rs index e6d7e13..65a80c3 100644 --- a/crates/core/src/compile/edge.rs +++ b/crates/core/src/compile/edge.rs @@ -54,6 +54,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig { interval_secs: hc.interval_secs, }), access_log: h.access_log == AccessLog::Truncated, + share_links: h.share_links, }) .collect(), } diff --git a/crates/core/src/edge_config.rs b/crates/core/src/edge_config.rs index a50d8c9..fdece67 100644 --- a/crates/core/src/edge_config.rs +++ b/crates/core/src/edge_config.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; /// Bumped on any incompatible change; edge refuses other versions. -pub const EDGE_CONFIG_VERSION: u32 = 1; +pub const EDGE_CONFIG_VERSION: u32 = 2; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -103,4 +103,7 @@ pub struct EdgeHost { pub response_headers: Vec, pub health_check: Option, pub access_log: bool, + /// 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, } diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index ed088dd..e3560c4 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -2,11 +2,67 @@ // 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/. -//! Typed validation errors. Every message names the file and says what is wrong in plain English, -//! so the UI can show it as is. +//! Typed validation errors. Every message names the file and says what is wrong in plain English. +//! +//! Each error also has a stable [`ValidationError::code`], the form field it is about +//! ([`ValidationError::field`], e.g. `upstreams[1]`) and the values the UI shows in bold +//! ([`ValidationError::params`]). The control API maps the code to the UI's copy +//! (docs/ui-api.md §3.1) and keeps the `Display` text below as the technical detail. +use std::collections::BTreeMap; use std::fmt; +/// The reasons carried in `&'static str` fields. [`ValidationError::code`] compares them by +/// value, so every reason is written once, here. +pub(crate) mod reason { + pub const HOST_EMPTY: &str = "it is empty"; + pub const HOST_TOO_LONG: &str = "it is longer than 253 characters"; + pub const HOST_IP: &str = "IP addresses are not hostnames"; + pub const HOST_WILDCARD: &str = "wildcards are not supported"; + pub const HOST_TRAILING_DOT: &str = "it must not end with a dot"; + pub const HOST_UPPERCASE: &str = "it must be lowercase"; + pub const HOST_SPACES: &str = "it must not contain spaces"; + pub const HOST_EMPTY_LABEL: &str = "it has an empty label"; + pub const HOST_LABEL_LONG: &str = "a label is longer than 63 characters"; + pub const HOST_CHARACTERS: &str = "only a-z, 0-9, '-' and '.' are allowed"; + pub const HOST_LABEL_DASH: &str = "a label must not start or end with '-'"; + pub const HOST_NUMERIC: &str = "the last label must not be numeric"; + + pub const URL_ASCII: &str = "it must be plain ASCII without spaces"; + pub const URL_NOT_URL: &str = "it is not a URL like http://127.0.0.1:8080"; + pub const URL_SCHEME: &str = "only http:// and https:// are supported"; + pub const URL_CREDENTIALS: &str = "credentials in the URL are not allowed"; + pub const URL_FRAGMENT: &str = "a #fragment is not allowed"; + pub const URL_NO_HOST: &str = "it has no host"; + pub const URL_HOST_NAME: &str = "the host name is not valid"; + pub const URL_NO_PORT: &str = "it has no port"; + pub const URL_PORT_ZERO: &str = "port 0 is not usable"; + pub const URL_PATH: &str = "a path is not allowed; requests keep their own path"; + pub const URL_QUERY: &str = "a ?query is not allowed"; + pub const URL_BRACES: &str = "'{' and '}' are not allowed"; + pub const URL_MIXED: &str = "all upstreams of a host must use the same scheme"; + + pub const VALUE_EMPTY: &str = "an empty value is not allowed; use action = \"remove\""; + pub const VALUE_LONG: &str = "it is longer than 4096 characters"; + pub const VALUE_ASCII: &str = "only visible ASCII characters and spaces are allowed"; + pub const VALUE_BRACES: &str = "'{' and '}' are not allowed (they are placeholders in Caddy)"; + pub const VALUE_EDGE_SPACE: &str = "it must not start or end with a space"; + + pub const RULE_REMOVE_VALUE: &str = "remove takes no value or secret"; + pub const RULE_BOTH: &str = "give either value or secret, not both"; + pub const RULE_NEITHER: &str = "set needs a value or a secret"; + + pub const HEALTH_PATH: &str = + "path must start with '/' and contain only visible ASCII without '{', '}' or '#'"; + pub const HEALTH_INTERVAL: &str = "interval_secs must be between 1 and 3600"; + + pub const PATH_LAYOUT: &str = + "only ianitor.toml and hosts/.toml belong in the routes repository"; + pub const PATH_SUBDIR: &str = "folders inside hosts/ are not allowed"; + pub const PATH_NAME: &str = "the file name must be a lowercase hostname followed by .toml"; + pub const PATH_KIND: &str = "symbolic links, executables and submodules are not allowed"; +} + /// One problem found in the route files. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ValidationError { @@ -26,8 +82,10 @@ pub enum ValidationError { DuplicateFile { file: String }, #[error("{file} is larger than {max} bytes")] FileTooLarge { file: String, max: usize }, - #[error("{file} must be named after its hostname: {hostname}.toml")] + #[error("{file} must be named after its hostname: hosts/{hostname}.toml")] FileNameMismatch { file: String, hostname: String }, + #[error("{file}: {reason}")] + UnexpectedFile { file: String, reason: &'static str }, #[error("{file}: at most {max} upstreams per host")] TooManyUpstreams { file: String, max: usize }, #[error("{file}: `{hostname}` is not a valid hostname: {reason}")] @@ -49,36 +107,64 @@ pub enum ValidationError { file: String, url: String, reason: &'static str, + /// Position in `upstreams`; `None` when the problem is about the list as a whole. + index: Option, }, #[error("{file}: upstream `{url}` is listed twice")] - DuplicateUpstream { file: String, url: String }, + DuplicateUpstream { + file: String, + url: String, + index: usize, + }, #[error("{file}: secret `{secret}` is used but not declared in the site file")] - UndefinedSecret { file: String, secret: String }, + UndefinedSecret { + file: String, + secret: String, + field: String, + }, #[error( "{file}: response header `{header}` may not use a secret; secrets only go to upstreams" )] - SecretInResponseHeader { file: String, header: String }, + SecretInResponseHeader { + file: String, + header: String, + field: String, + }, #[error( "{file}: `{name}` is not a valid secret name (use a-z, 0-9, '_' and '-', at most 64 characters)" )] InvalidSecretName { file: String, name: String }, #[error("{file}: `{name}` is not a valid header name")] - InvalidHeaderName { file: String, name: String }, + InvalidHeaderName { + file: String, + name: String, + field: String, + }, #[error("{file}: value for header `{header}` is not allowed: {reason}")] InvalidHeaderValue { file: String, header: String, reason: &'static str, + field: String, }, #[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")] - ProtectedHeader { file: String, header: String }, + ProtectedHeader { + file: String, + header: String, + field: String, + }, #[error("{file}: header `{header}` has more than one rule in the same list")] - DuplicateHeaderRule { file: String, header: String }, + DuplicateHeaderRule { + file: String, + header: String, + field: String, + }, #[error("{file}: rule for header `{header}` is incomplete: {reason}")] BadHeaderRule { file: String, header: String, reason: &'static str, + field: String, }, #[error("{file}: health check is not usable: {reason}")] BadHealthCheck { file: String, reason: &'static str }, @@ -97,6 +183,68 @@ fn line_suffix(line: Option) -> String { } } +impl ValidationError { + /// The file the problem is in (for a duplicate hostname: the second file). + pub fn file(&self) -> &str { + use ValidationError as E; + match self { + E::Syntax { file, .. } + | E::UnknownField { file, .. } + | E::MissingField { file, .. } + | E::InvalidValue { file, .. } + | E::DuplicateFile { file } + | E::FileTooLarge { file, .. } + | E::FileNameMismatch { file, .. } + | E::UnexpectedFile { file, .. } + | E::TooManyUpstreams { file, .. } + | E::InvalidHostname { file, .. } + | E::NoUpstreams { file } + | E::BadUpstreamUrl { file, .. } + | E::DuplicateUpstream { file, .. } + | E::UndefinedSecret { file, .. } + | E::SecretInResponseHeader { file, .. } + | E::InvalidSecretName { file, .. } + | E::InvalidHeaderName { file, .. } + | E::InvalidHeaderValue { file, .. } + | E::ProtectedHeader { file, .. } + | E::DuplicateHeaderRule { file, .. } + | E::BadHeaderRule { file, .. } + | E::BadHealthCheck { file, .. } + | E::ForwardAuthNotConfigured { file } + | E::BadForwardAuth { file, .. } + | E::BadAcme { file, .. } => file, + E::DuplicateHostname { second, .. } => second, + } + } + + /// True when the problem is in the site file (or a stray file), not in a host file. + pub fn in_site_file(&self) -> bool { + !self.file().starts_with("hosts/") + } + + /// A stable code the UI switches on, e.g. `host.upstream.no_port` (docs/ui-api.md §3.1). + pub fn code(&self) -> &'static str { + // Tests first: not written yet. + "unknown" + } + + /// The form field the problem is about, as a path into the host body (`hostname`, + /// `upstreams[0]`, `request_headers[2].name`, `health_check.path`), or `None`. + pub fn field(&self) -> Option { + // Tests first: not written yet. + None + } + + /// The values a message shows: always `file`, plus `line`, `field`, `max`, `hostname`, + /// `suggestion`, `url`, `name` or `secret` where they apply. + pub fn params(&self) -> BTreeMap<&'static str, String> { + // Tests first: not written yet. + let mut p = BTreeMap::new(); + p.insert("file", self.file().to_owned()); + p + } +} + /// All problems found in one load, in a stable order (file by file, then hostname checks). #[derive(Debug, Clone, PartialEq, Eq)] pub struct ValidationErrors(pub(crate) Vec); @@ -109,6 +257,11 @@ impl ValidationErrors { pub fn into_errors(self) -> Vec { self.0 } + + /// Wrap errors found outside [`crate::load`] (e.g. by [`crate::routes::check_path`]). + pub fn from_errors(errors: Vec) -> ValidationErrors { + ValidationErrors(errors) + } } impl fmt::Display for ValidationErrors { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index eda6c33..01d47c5 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,12 +12,14 @@ pub mod compile; pub mod edge_config; mod error; mod model; +pub mod routes; +pub mod share; mod validate; pub use error::{ValidationError, ValidationErrors}; pub use model::{ AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, Model, Scheme, - SecretName, Site, TlsMode, Upstream, UpstreamHost, + MAX_FILE_BYTES, MAX_UPSTREAMS, SecretName, Site, TlsMode, Upstream, UpstreamHost, }; pub use validate::{SourceFile, load}; diff --git a/crates/core/src/routes.rs b/crates/core/src/routes.rs new file mode 100644 index 0000000..8bb863a --- /dev/null +++ b/crates/core/src/routes.rs @@ -0,0 +1,61 @@ +// 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 shape of the routes repository: exactly `ianitor.toml` and `hosts/.toml`, +//! regular files only. Anything else (other names, folders inside `hosts/`, symbolic links, +//! submodules, executables) is refused, so the repository can never hold something the +//! compilers do not read. + +use crate::error::{ValidationError, reason}; +use crate::validate::check_hostname; + +/// The site file at the root of the repository. +pub const SITE_FILE: &str = "ianitor.toml"; +/// The folder holding one file per host. +pub const HOSTS_DIR: &str = "hosts"; +/// Most host files one repository may hold. +pub const MAX_HOST_FILES: usize = 1000; + +/// What a tree entry is, as git reports it (`git ls-tree` modes). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EntryKind { + /// Mode 100644. + File, + /// Mode 100755. + Executable, + /// Mode 120000. + Symlink, + /// Mode 160000. + Submodule, +} + +/// A path the repository may hold. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RoutePath { + Site, + Host { hostname: String }, +} + +/// The path of the file for `hostname`. +pub fn host_path(hostname: &str) -> String { + format!("{HOSTS_DIR}/{hostname}.toml") +} + +/// Check one path of the repository tree (as listed recursively, `/`-separated). +pub fn check_path(path: &str, kind: EntryKind) -> Result { + // Tests first: not written yet. + let _ = (kind, reason::PATH_LAYOUT, check_hostname); + match path.strip_prefix("hosts/").and_then(|r| r.strip_suffix(".toml")) { + Some(h) => Ok(RoutePath::Host { hostname: h.to_owned() }), + None => Ok(RoutePath::Site), + } +} + +/// Check a whole tree listing. +pub fn check_tree<'a>( + entries: impl IntoIterator, +) -> Result<(), Vec> { + let _ = entries.into_iter().count(); + Ok(()) +} diff --git a/crates/core/src/share.rs b/crates/core/src/share.rs new file mode 100644 index 0000000..884b961 --- /dev/null +++ b/crates/core/src/share.rs @@ -0,0 +1,370 @@ +// 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/. + +//! Share links: stateless tokens minted by control and checked by edge. +//! +//! A link token is `ish1.` + base64url(payload ‖ mac): +//! +//! ```text +//! payload = version (1) ‖ id (16) ‖ epoch (u32 BE) ‖ expires_at (u64 BE, Unix s) ‖ flags (1) ‖ path prefix +//! mac = HMAC-SHA256(key, "ianitor share link v1" 0 host 0 payload [0 HMAC-SHA256(key, "ianitor share password v1" 0 id password)]) +//! ``` +//! +//! - The host is not in the token but in the MAC, so a token for one host fails on another. +//! - With a password (flag bit 0), the MAC can only be checked by someone who has both the key +//! and the password: the token carries no password hash, so holding a link does not allow +//! guessing its password offline. Edge rate-limits guesses. +//! - The session cookie edge sets after a successful check is `iss1.` + base64url(payload ‖ +//! HMAC(key, "ianitor share session v1" 0 host 0 payload)): a different domain, so a link +//! token is never accepted as a cookie and a cookie never as a link (and a cookie for a +//! password link proves the password was given). +//! - Revocation: every token carries the epoch it was minted in; edge refuses tokens from an +//! older epoch ("stop all") and ids on the deny list ("stop this link"). +//! +//! [`path_within`] decides whether a raw request path lies under a link's prefix. It refuses +//! anything an upstream might read differently from a plain byte comparison. + +use std::collections::BTreeSet; +use std::fmt; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use ring::hmac; + +/// Name of the credential (`$CREDENTIALS_DIRECTORY/`) holding the share-link key, read by +/// both edge and control. +pub const KEY_CREDENTIAL: &str = "share-link-key"; +/// Shortest key accepted, in bytes. +pub const MIN_KEY_LEN: usize = 32; +/// Query parameter carrying a link token. Edge only takes values that start with +/// [`LINK_PREFIX`]; anything else is left to the upstream. +pub const QUERY_PARAM: &str = "share"; +/// Start of every link token. +pub const LINK_PREFIX: &str = "ish1."; +/// Start of every session cookie value. +pub const SESSION_PREFIX: &str = "iss1."; +/// Session cookie name (`__Secure-`: browsers only accept it with `Secure`). +pub const COOKIE_NAME: &str = "__Secure-ianitor-share"; +/// Path the password form posts to, on hosts with share links. +pub const PASSWORD_PATH: &str = "/.well-known/ianitor/share"; +/// Longest path prefix. +pub const MAX_PREFIX_LEN: usize = 256; +/// Password length limits, in characters. +pub const MIN_PASSWORD_CHARS: usize = 8; +pub const MAX_PASSWORD_CHARS: usize = 128; + +const VERSION: u8 = 1; +const FLAG_PASSWORD: u8 = 1; +const FIXED_LEN: usize = 1 + 16 + 4 + 8 + 1; +const MAC_LEN: usize = 32; +/// Longest token or cookie accepted before decoding. +const MAX_ENCODED_LEN: usize = 1024; + +/// A link id: 16 random bytes, written as 32 lowercase hex digits. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ShareId(pub [u8; 16]); + +impl ShareId { + pub fn to_hex(&self) -> String { + self.0.iter().map(|b| format!("{b:02x}")).collect() + } + + pub fn from_hex(s: &str) -> Option { + if s.len() != 32 + || !s + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + { + return None; + } + let mut out = [0u8; 16]; + for (i, o) in out.iter_mut().enumerate() { + *o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?; + } + Some(ShareId(out)) + } +} + +impl fmt::Display for ShareId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_hex()) + } +} + +/// The HMAC key. Never printed. +pub struct ShareKey(hmac::Key); + +impl fmt::Debug for ShareKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ShareKey()") + } +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ShareError { + #[error("the share-link key must be at least {MIN_KEY_LEN} bytes")] + KeyTooShort, + #[error("the path prefix is not usable: {0}")] + Prefix(&'static str), + #[error("the password must be {MIN_PASSWORD_CHARS} to {MAX_PASSWORD_CHARS} characters")] + Password, +} + +impl ShareKey { + pub fn new(bytes: &[u8]) -> Result { + if bytes.len() < MIN_KEY_LEN { + return Err(ShareError::KeyTooShort); + } + Ok(ShareKey(hmac::Key::new(hmac::HMAC_SHA256, bytes))) + } +} + +/// What a token says. For a token checked with [`verify_link`] or [`verify_session`], all of +/// it is proven by the MAC; from [`peek`], none of it is. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Claims { + pub id: ShareId, + pub epoch: u32, + pub expires_at: u64, + pub password: bool, + pub prefix: String, +} + +/// What to mint. +#[derive(Debug, Clone)] +pub struct LinkSpec<'a> { + pub id: ShareId, + pub epoch: u32, + pub expires_at: u64, + /// Already checked with [`check_prefix`]. + pub prefix: &'a str, + pub password: Option<&'a str>, +} + +/// Why a token was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Rejection { + /// Not a token at all (bad encoding, wrong version, too long). + Malformed, + /// The MAC does not match: altered, minted for another host, made with another key, or + /// (for a password link) the wrong password. + Invalid, + /// The link needs a password and none was given. + PasswordRequired, + /// Proven genuine, but past its expiry. + Expired { expires_at: u64 }, + /// Proven genuine, but stopped (deny list or an older epoch). + Revoked, +} + +/// The revocation state edge checks against (from the deny-list file control writes). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Revocations { + /// Tokens minted in an older epoch are refused ("stop all"). + pub epoch: u32, + /// Stopped links. + pub deny: BTreeSet, +} + +impl Revocations { + pub fn is_revoked(&self, c: &Claims) -> bool { + c.epoch < self.epoch || self.deny.contains(&c.id) + } +} + +fn payload(spec: &LinkSpec<'_>) -> Vec { + let mut p = Vec::with_capacity(FIXED_LEN + spec.prefix.len()); + p.push(VERSION); + p.extend_from_slice(&spec.id.0); + p.extend_from_slice(&spec.epoch.to_be_bytes()); + p.extend_from_slice(&spec.expires_at.to_be_bytes()); + p.push(if spec.password.is_some() { + FLAG_PASSWORD + } else { + 0 + }); + p.extend_from_slice(spec.prefix.as_bytes()); + p +} + +fn password_tag(key: &ShareKey, id: &ShareId, password: &str) -> hmac::Tag { + let mut ctx = hmac::Context::with_key(&key.0); + ctx.update(b"ianitor share password v1\0"); + ctx.update(&id.0); + ctx.update(password.as_bytes()); + ctx.sign() +} + +fn link_message( + key: &ShareKey, + host: &str, + payload: &[u8], + id: &ShareId, + password: Option<&str>, +) -> Vec { + let mut m = Vec::with_capacity(64 + host.len() + payload.len()); + m.extend_from_slice(b"ianitor share link v1\0"); + m.extend_from_slice(host.as_bytes()); + m.push(0); + m.extend_from_slice(payload); + if let Some(pw) = password { + m.push(0); + m.extend_from_slice(password_tag(key, id, pw).as_ref()); + } + m +} + +fn session_message(host: &str, payload: &[u8]) -> Vec { + let mut m = Vec::with_capacity(64 + host.len() + payload.len()); + m.extend_from_slice(b"ianitor share session v1\0"); + m.extend_from_slice(host.as_bytes()); + m.push(0); + m.extend_from_slice(payload); + m +} + +fn check_password(pw: &str) -> Result<(), ShareError> { + let n = pw.chars().count(); + if (MIN_PASSWORD_CHARS..=MAX_PASSWORD_CHARS).contains(&n) { + Ok(()) + } else { + Err(ShareError::Password) + } +} + +/// Mint a link token for `host` (a validated hostname). +pub fn mint(key: &ShareKey, host: &str, spec: &LinkSpec<'_>) -> Result { + let prefix = check_prefix(spec.prefix).map_err(ShareError::Prefix)?; + if prefix != spec.prefix { + return Err(ShareError::Prefix("it is not in its normal form")); + } + if let Some(pw) = spec.password { + check_password(pw)?; + } + let p = payload(spec); + let tag = hmac::sign( + &key.0, + &link_message(key, host, &p, &spec.id, spec.password), + ); + let mut raw = p; + raw.extend_from_slice(tag.as_ref()); + Ok(format!("{LINK_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw))) +} + +/// Split and decode without checking the MAC. Only for showing a password page. +fn decode(token: &str, prefix: &str) -> Result<(Claims, Vec, Vec), Rejection> { + if token.len() > MAX_ENCODED_LEN { + return Err(Rejection::Malformed); + } + let body = token.strip_prefix(prefix).ok_or(Rejection::Malformed)?; + let raw = URL_SAFE_NO_PAD + .decode(body) + .map_err(|_| Rejection::Malformed)?; + if raw.len() < FIXED_LEN + MAC_LEN + 1 { + return Err(Rejection::Malformed); + } + let (p, mac) = raw.split_at(raw.len() - MAC_LEN); + if p[0] != VERSION || p[FIXED_LEN - 1] & !FLAG_PASSWORD != 0 { + return Err(Rejection::Malformed); + } + let mut id = [0u8; 16]; + id.copy_from_slice(&p[1..17]); + let mut e = [0u8; 4]; + e.copy_from_slice(&p[17..21]); + let mut x = [0u8; 8]; + x.copy_from_slice(&p[21..29]); + let prefix = std::str::from_utf8(&p[FIXED_LEN..]).map_err(|_| Rejection::Malformed)?; + // A token whose prefix is not in normal form was never minted. + Ok(( + Claims { + id: ShareId(id), + epoch: u32::from_be_bytes(e), + expires_at: u64::from_be_bytes(x), + password: p[FIXED_LEN - 1] & FLAG_PASSWORD != 0, + prefix: prefix.to_owned(), + }, + p.to_vec(), + mac.to_vec(), + )) +} + +/// What a link token claims, unchecked (for the password page: is a password needed, and +/// until when does it claim to work). Never grant anything on this alone. +pub fn peek(token: &str) -> Result { + decode(token, LINK_PREFIX).map(|(c, _, _)| c) +} + +/// Check a link token for `host`. The order of checks fixes what a visitor learns: a password +/// is asked for before anything else is proven; expiry and revocation are reported only for +/// tokens proven genuine. +pub fn verify_link( + key: &ShareKey, + host: &str, + token: &str, + password: Option<&str>, + now: u64, + revocations: &Revocations, +) -> Result { + let _ = (key, host, password, now, revocations); + peek(token) +} + +fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result { + if now >= claims.expires_at { + return Err(Rejection::Expired { + expires_at: claims.expires_at, + }); + } + if revocations.is_revoked(&claims) { + return Err(Rejection::Revoked); + } + Ok(claims) +} + +/// The session cookie value for claims proven by [`verify_link`]. +pub fn session_value(key: &ShareKey, host: &str, claims: &Claims) -> String { + let spec = LinkSpec { + id: claims.id, + epoch: claims.epoch, + expires_at: claims.expires_at, + prefix: &claims.prefix, + password: claims.password.then_some(""), + }; + let p = payload(&spec); + let tag = hmac::sign(&key.0, &session_message(host, &p)); + let mut raw = p; + raw.extend_from_slice(tag.as_ref()); + format!("{SESSION_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw)) +} + +/// Check a session cookie value for `host`. +pub fn verify_session( + key: &ShareKey, + host: &str, + value: &str, + now: u64, + revocations: &Revocations, +) -> Result { + let _ = (key, host, now, revocations); + decode(value, SESSION_PREFIX).map(|(c, _, _)| c) +} + +/// Normalise and check a path prefix: starts with `/`, at most [`MAX_PREFIX_LEN`] bytes, only +/// unreserved characters and `!$&'()*+,=:@-._~`, no `%`, `;`, backslash, empty segment or dot +/// segment. A trailing `/` is dropped (except for `/` itself). +pub fn check_prefix(prefix: &str) -> Result { + // Tests first: not written yet. + Ok(prefix.to_owned()) +} + +/// Is `raw_path` (the request path exactly as sent, still percent-encoded) under `prefix`? +/// +/// Refused outright, whatever the prefix: anything but visible ASCII, a backslash, an empty +/// segment (`//`), a dot segment (`.`, `..`, also with `;params`), and the percent-encoded +/// forms of `.`, `/`, `\`, `%` and NUL. Other paths match on whole segments, case-sensitively: +/// prefix `/a` covers `/a` and `/a/x`, not `/ab` or `/A`. +pub fn path_within(prefix: &str, raw_path: &str) -> bool { + // Tests first: not written yet. + raw_path.starts_with(prefix) +} diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index f86c154..0158415 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -11,7 +11,7 @@ use std::net::IpAddr; use serde::Deserialize; use serde::de::DeserializeOwned; -use crate::error::{ValidationError as E, ValidationErrors}; +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, @@ -274,11 +274,13 @@ fn check_site(file: &str, raw: RawSite, errors: &mut Vec) -> Option { errors.push(E::InvalidHeaderName { file: file.to_owned(), name: h.clone(), + field: "forward_auth.copy_headers".into(), }); } else if is_protected(h) { errors.push(E::ProtectedHeader { file: file.to_owned(), header: h.clone(), + field: "forward_auth.copy_headers".into(), }); } else if !seen.insert(h.to_ascii_lowercase()) { errors.push(bad("copy_headers lists a header twice")); @@ -397,7 +399,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec } let mut upstreams: Vec = Vec::new(); let mut seen_upstreams = BTreeSet::new(); - for u in raw.upstreams.iter().take(MAX_UPSTREAMS) { + for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() { match parse_url(u, false) { Ok((up, _)) => { if seen_upstreams.insert(up.clone()) { @@ -406,6 +408,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec errors.push(E::DuplicateUpstream { file: f(), url: u.clone(), + index, }); } } @@ -413,6 +416,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec file: f(), url: u.clone(), reason, + index: Some(index), }), } } @@ -421,7 +425,8 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec errors.push(E::BadUpstreamUrl { file: f(), url: raw.upstreams.join(", "), - reason: "all upstreams of a host must use the same scheme", + reason: r::URL_MIXED, + index: None, }); } @@ -450,8 +455,22 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec } AuthMode::None => Vec::new(), }; - let request_headers = check_rules(file, raw.request_headers, true, &identity, site, errors); - let response_headers = check_rules(file, raw.response_headers, false, &[], site, errors); + let request_headers = check_rules( + file, + "request_headers", + raw.request_headers, + &identity, + site, + errors, + ); + let response_headers = check_rules( + file, + "response_headers", + raw.response_headers, + &[], + site, + errors, + ); let health_check = raw.health_check.and_then(|hc| { let bad = |reason| E::BadHealthCheck { file: f(), reason }; @@ -463,7 +482,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec .all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c)); if !ok_path { errors.push(bad( - "path must start with '/' and contain only visible ASCII without '{', '}' or '#'", + r::HEALTH_PATH, )); return None; } @@ -473,7 +492,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec interval_secs: i, }), _ => { - errors.push(bad("interval_secs must be between 1 and 3600")); + errors.push(bad(r::HEALTH_INTERVAL)); None } } @@ -527,45 +546,63 @@ fn is_protected(name: &str) -> bool { fn check_rules( file: &str, + list: &str, raw: Vec, - request: bool, identity: &[String], site: Option<&Site>, errors: &mut Vec, ) -> Vec { + let request = list == "request_headers"; let f = || file.to_owned(); let mut out = Vec::new(); let mut seen = BTreeSet::new(); - for r in raw { + for (i, r) in raw.into_iter().enumerate() { + let at = |part: &str| { + if part.is_empty() { + format!("{list}[{i}]") + } else { + format!("{list}[{i}].{part}") + } + }; let header = r.name.clone(); if !valid_header_name(&r.name) { errors.push(E::InvalidHeaderName { file: f(), name: r.name, + field: at("name"), }); continue; } let lower = r.name.to_ascii_lowercase(); if is_protected(&r.name) || identity.contains(&lower) { - errors.push(E::ProtectedHeader { file: f(), header }); + errors.push(E::ProtectedHeader { + file: f(), + header, + field: at("name"), + }); continue; } if !seen.insert(lower) { - errors.push(E::DuplicateHeaderRule { file: f(), header }); + errors.push(E::DuplicateHeaderRule { + file: f(), + header, + field: at("name"), + }); continue; } let bad = |reason| E::BadHeaderRule { file: f(), header: header.clone(), reason, + field: at(if reason == r::RULE_NEITHER { "value" } else { "" }), }; match (r.action, r.value, r.secret) { (RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }), - (RawAction::Remove, _, _) => errors.push(bad("remove takes no value or secret")), + (RawAction::Remove, _, _) => errors.push(bad(r::RULE_REMOVE_VALUE)), (RawAction::Set, Some(_), Some(_)) => { - errors.push(bad("give either value or secret, not both")) + errors.push(bad(r::RULE_BOTH)) } - (RawAction::Set, None, None) => errors.push(bad("set needs a value or a secret")), + (RawAction::Set, None, None) => errors.push(bad(r::RULE_NEITHER)), (RawAction::Set, Some(v), None) => match check_header_value(&v) { Ok(()) => out.push(HeaderRule::Set { name: r.name, @@ -575,15 +612,21 @@ fn check_rules( file: f(), header, reason, + field: at("value"), }), }, (RawAction::Set, None, Some(s)) => { if !request { - errors.push(E::SecretInResponseHeader { file: f(), header }); + errors.push(E::SecretInResponseHeader { + file: f(), + header, + field: at(""), + }); } else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) { errors.push(E::UndefinedSecret { file: f(), secret: s, + field: at("secret"), }); } else { out.push(HeaderRule::Set { @@ -608,19 +651,19 @@ fn valid_header_name(n: &str) -> bool { fn check_header_value(v: &str) -> Result<(), &'static str> { if v.is_empty() { - return Err("an empty value is not allowed; use action = \"remove\""); + return Err(r::VALUE_EMPTY); } if v.len() > 4096 { - return Err("it is longer than 4096 characters"); + return Err(r::VALUE_LONG); } if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) { - return Err("only visible ASCII characters and spaces are allowed"); + return Err(r::VALUE_ASCII); } if v.contains(['{', '}']) { - return Err("'{' and '}' are not allowed (they are placeholders in Caddy)"); + return Err(r::VALUE_BRACES); } if v.starts_with(' ') || v.ends_with(' ') { - return Err("it must not start or end with a space"); + return Err(r::VALUE_EDGE_SPACE); } Ok(()) } @@ -629,44 +672,47 @@ fn check_header_value(v: &str) -> Result<(), &'static str> { pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> { if h.is_empty() { - return Err("it is empty"); + return Err(r::HOST_EMPTY); } if h.len() > 253 { - return Err("it is longer than 253 characters"); + return Err(r::HOST_TOO_LONG); } if h.parse::().is_ok() || h.starts_with('[') { - return Err("IP addresses are not hostnames"); + return Err(r::HOST_IP); } if h.contains('*') { - return Err("wildcards are not supported"); + return Err(r::HOST_WILDCARD); + } + if h.contains(char::is_whitespace) { + return Err(r::HOST_SPACES); } if h.ends_with('.') { - return Err("it must not end with a dot"); + return Err(r::HOST_TRAILING_DOT); } if h.bytes().any(|c| c.is_ascii_uppercase()) { - return Err("it must be lowercase"); + return Err(r::HOST_UPPERCASE); } let mut last = ""; for label in h.split('.') { if label.is_empty() { - return Err("it has an empty label"); + return Err(r::HOST_EMPTY_LABEL); } if label.len() > 63 { - return Err("a label is longer than 63 characters"); + return Err(r::HOST_LABEL_LONG); } if !label .bytes() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-') { - return Err("only a-z, 0-9, '-' and '.' are allowed"); + return Err(r::HOST_CHARACTERS); } if label.starts_with('-') || label.ends_with('-') { - return Err("a label must not start or end with '-'"); + return Err(r::HOST_LABEL_DASH); } last = label; } if last.bytes().all(|c| c.is_ascii_digit()) { - return Err("the last label must not be numeric"); + return Err(r::HOST_NUMERIC); } Ok(()) } @@ -675,42 +721,42 @@ pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> { /// (for the forward-auth endpoint); otherwise any path other than `/` is rejected. fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static str> { if !raw.bytes().all(|c| c.is_ascii_graphic()) { - return Err("it must be plain ASCII without spaces"); + return Err(r::URL_ASCII); } - let u = url::Url::parse(raw).map_err(|_| "it is not a URL like http://127.0.0.1:8080")?; + let u = url::Url::parse(raw).map_err(|_| r::URL_NOT_URL)?; let scheme = match u.scheme() { "http" => Scheme::Http, "https" => Scheme::Https, - _ => return Err("only http:// and https:// are supported"), + _ => return Err(r::URL_SCHEME), }; if !u.username().is_empty() || u.password().is_some() { - return Err("credentials in the URL are not allowed"); + return Err(r::URL_CREDENTIALS); } if u.fragment().is_some() { - return Err("a #fragment is not allowed"); + return Err(r::URL_FRAGMENT); } let host = match u.host() { - None => return Err("it has no host"), + None => return Err(r::URL_NO_HOST), Some(url::Host::Ipv4(ip)) => UpstreamHost::Ip(IpAddr::V4(ip)), Some(url::Host::Ipv6(ip)) => UpstreamHost::Ip(IpAddr::V6(ip)), Some(url::Host::Domain(d)) => { if check_hostname(d).is_err() { - return Err("the host name is not valid"); + return Err(r::URL_HOST_NAME); } UpstreamHost::Name(d.to_owned()) } }; - let port = u.port_or_known_default().ok_or("it has no port")?; + let port = u.port_or_known_default().ok_or(r::URL_NO_PORT)?; if port == 0 { - return Err("port 0 is not usable"); + return Err(r::URL_PORT_ZERO); } let mut path = u.path().to_owned(); if !allow_path { if path != "/" && !path.is_empty() { - return Err("a path is not allowed; requests keep their own path"); + return Err(r::URL_PATH); } if u.query().is_some() { - return Err("a ?query is not allowed"); + return Err(r::URL_QUERY); } } else { if let Some(q) = u.query() { @@ -718,7 +764,7 @@ fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static path.push_str(q); } if path.contains(['{', '}']) { - return Err("'{' and '}' are not allowed"); + return Err(r::URL_BRACES); } } Ok((Upstream { scheme, host, port }, path)) diff --git a/crates/core/tests/routes.rs b/crates/core/tests/routes.rs new file mode 100644 index 0000000..f288343 --- /dev/null +++ b/crates/core/tests/routes.rs @@ -0,0 +1,233 @@ +// 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 routes repository holds exactly `ianitor.toml` and `hosts/.toml`, and the +//! loader requires the exact path (ROADMAP §10: the check used to look at the base name only). +//! Validation errors carry a stable code, a field path and params for the UI (docs/ui-api.md §3.1). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use ianitor_core::routes::{EntryKind, RoutePath, check_path, check_tree}; +use ianitor_core::{SourceFile, ValidationError, load}; + +#[test] +fn only_the_site_file_and_host_files_are_allowed() { + assert_eq!( + check_path("ianitor.toml", EntryKind::File).unwrap(), + RoutePath::Site + ); + assert_eq!( + check_path("hosts/wiki.home.test.toml", EntryKind::File).unwrap(), + RoutePath::Host { + hostname: "wiki.home.test".into() + } + ); + for bad in [ + "README.md", + ".gitattributes", + "hosts.toml", + "other/wiki.home.test.toml", + "hosts/sub/wiki.home.test.toml", + "hosts/wiki.home.test.toml/x", + "hosts/Wiki.home.test.toml", + "hosts/wiki.home.test.TOML", + "hosts/wiki.home.test", + "hosts/.toml", + "hosts/*.home.test.toml", + "hosts/wiki..test.toml", + "hosts/10.0.0.1.toml", + "hosts/wiki home.toml", + "hosts\\wiki.home.test.toml", + "hosts/wiki\\x.toml", + "IANITOR.toml", + "./ianitor.toml", + ] { + let e = check_path(bad, EntryKind::File).unwrap_err(); + assert!( + matches!(e, ValidationError::UnexpectedFile { ref file, .. } if file == bad), + "{bad}: {e:?}" + ); + assert_eq!(e.code(), "repo.unexpected_file"); + } +} + +#[test] +fn links_executables_and_submodules_are_refused() { + for kind in [ + EntryKind::Symlink, + EntryKind::Submodule, + EntryKind::Executable, + ] { + assert!(check_path("hosts/a.test.toml", kind).is_err(), "{kind:?}"); + assert!(check_path("ianitor.toml", kind).is_err(), "{kind:?}"); + } +} + +#[test] +fn a_tree_needs_the_site_file_and_reports_every_stray_file() { + let ok = [ + ("ianitor.toml", EntryKind::File), + ("hosts/a.test.toml", EntryKind::File), + ]; + assert!(check_tree(ok).is_ok()); + let errs = check_tree([ + ("hosts/a.test.toml", EntryKind::File), + ("notes.txt", EntryKind::File), + ("hosts/b/c.toml", EntryKind::File), + ]) + .unwrap_err(); + assert_eq!(errs.len(), 3, "{errs:?}"); +} + +#[test] +fn the_loader_requires_the_exact_path() { + let site = SourceFile { + name: "ianitor.toml", + contents: "", + }; + let body = "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n"; + for name in [ + "app.test.toml", + "other/app.test.toml", + "hosts/x/app.test.toml", + "hosts\\app.test.toml", + "./hosts/app.test.toml", + ] { + let errs = load( + &site, + &[SourceFile { + name, + contents: body, + }], + ) + .unwrap_err(); + assert!( + errs.errors() + .iter() + .any(|e| matches!(e, ValidationError::FileNameMismatch { .. })), + "{name}: {errs:?}" + ); + } + assert!( + load( + &site, + &[SourceFile { + name: "hosts/app.test.toml", + contents: body + }] + ) + .is_ok() + ); +} + +fn errors_for(body: &str) -> Vec { + let site = SourceFile { + name: "ianitor.toml", + contents: "secrets = [\"api_key\"]\n", + }; + load( + &site, + &[SourceFile { + name: "hosts/app.test.toml", + contents: body, + }], + ) + .unwrap_err() + .into_errors() +} + +#[test] +fn errors_have_codes_fields_and_params_for_the_ui() { + let cases: &[(&str, &str, Option<&str>)] = &[ + ( + "upstreams = [\"http://127.0.0.1:1\"]\n", + "host.hostname.missing", + Some("hostname"), + ), + ("hostname = \"app.test\"\n", "host.upstreams.missing", Some("upstreams")), + ( + "hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + "host.hostname.uppercase", + Some("hostname"), + ), + ( + "hostname = \"app test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + "host.hostname.spaces", + Some("hostname"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"ftp://x\"]\n", + "host.upstream.scheme", + Some("upstreams[1]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1/x\"]\n", + "host.upstream.path", + Some("upstreams[0]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"http://127.0.0.1:1\"]\n", + "host.upstream.duplicate", + Some("upstreams[1]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"https://127.0.0.1:2\"]\n", + "host.upstream.mixed_schemes", + Some("upstreams"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ncolour = 1\n", + "host.field.unknown", + Some("colour"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"set\"\nname = \"Host\"\nvalue = \"x\"\n", + "host.header.protected", + Some("request_headers[1].name"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n", + "host.header.secret_response", + Some("response_headers[0]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"nope\"\n", + "host.header.secret_unknown", + Some("request_headers[0].secret"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[health_check]\npath = \"/x\"\ninterval_secs = 0\n", + "host.health.interval", + Some("health_check.interval_secs"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\nauth = \"forward-auth\"\n", + "host.auth.not_configured", + Some("auth"), + ), + ]; + for (body, code, field) in cases { + let errs = errors_for(body); + let e = errs + .iter() + .find(|e| e.code() == *code) + .unwrap_or_else(|| panic!("no {code} for {body:?}: {errs:?}")); + assert_eq!(e.field().as_deref(), *field, "{code}"); + assert_eq!(e.params()["file"], "hosts/app.test.toml"); + } +} + +#[test] +fn params_carry_suggestions() { + let errs = errors_for("hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n"); + let e = errs + .iter() + .find(|e| e.code() == "host.hostname.uppercase") + .unwrap(); + assert_eq!(e.params()["suggestion"], "app.test"); + let errs = errors_for("hostname = \"app.test\"\nupstreams = [\"http://10.0.0.2:3000/app\"]\n"); + let e = errs.iter().find(|e| e.code() == "host.upstream.path").unwrap(); + assert_eq!(e.params()["suggestion"], "http://10.0.0.2:3000"); + assert_eq!(e.params()["url"], "http://10.0.0.2:3000/app"); +} diff --git a/crates/core/tests/schema.rs b/crates/core/tests/schema.rs index bcd4845..f1ecd49 100644 --- a/crates/core/tests/schema.rs +++ b/crates/core/tests/schema.rs @@ -148,11 +148,11 @@ value = "max-age=31536000" #[test] fn hosts_are_sorted_by_hostname_whatever_the_file_order() { let a = SourceFile { - name: "b.test.toml", + name: "hosts/b.test.toml", contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }; let b = SourceFile { - name: "a.test.toml", + name: "hosts/a.test.toml", contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }; let m1 = load(&site(), &[a, b]).unwrap(); @@ -175,7 +175,7 @@ fn empty_site_file_is_allowed() { contents: "", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -236,7 +236,7 @@ fn rejects_unknown_field_in_site_file() { contents: "secrets = []\nsecret_values = { a = \"b\" }\n", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -348,10 +348,11 @@ fn accepts_good_hostnames() { } #[test] -fn rejects_duplicate_hostnames_across_files() { - let r = load( - &site(), - &[ +fn a_second_file_for_the_same_host_is_refused_by_its_path() { + // With the exact `hosts/.toml` rule, two files can never hold one hostname: + // the second one is in the wrong place, whatever the file order. + for order in [false, true] { + let mut files = vec![ SourceFile { name: "hosts/app.test.toml", contents: MINIMAL, @@ -360,38 +361,19 @@ fn rejects_duplicate_hostnames_across_files() { name: "other/app.test.toml", contents: MINIMAL, }, - ], - ); - let errs = r.unwrap_err(); - assert_eq!( - errs.errors(), - [ValidationError::DuplicateHostname { - hostname: "app.test".into(), - first: "hosts/app.test.toml".into(), - second: "other/app.test.toml".into() - }] - ); -} - -#[test] -fn duplicate_detection_is_independent_of_file_order() { - let r = load( - &site(), - &[ - SourceFile { - name: "other/app.test.toml", - contents: MINIMAL, - }, - SourceFile { - name: "hosts/app.test.toml", - contents: MINIMAL, - }, - ], - ); - let errs = r.unwrap_err(); - assert!( - matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/app.test.toml" && second == "other/app.test.toml") - ); + ]; + if order { + files.reverse(); + } + let errs = load(&site(), &files).unwrap_err(); + assert_eq!( + errs.errors(), + [ValidationError::FileNameMismatch { + file: "other/app.test.toml".into(), + hostname: "app.test".into() + }] + ); + } } #[test] @@ -400,11 +382,11 @@ fn rejects_duplicate_source_file_names() { &site(), &[ SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, ], @@ -485,7 +467,8 @@ fn rejects_undefined_secret_reference() { e, ValidationError::UndefinedSecret { file: "hosts/app.test.toml".into(), - secret: "nope".into() + secret: "nope".into(), + field: "request_headers[0].secret".into() } ); } @@ -498,7 +481,7 @@ fn undefined_secret_is_reported_when_site_declares_none() { contents: "", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: &format!( "{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n" ), @@ -532,7 +515,7 @@ fn rejects_bad_secret_names_in_site_file() { contents: &format!("secrets = [{bad:?}]\n"), }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -678,7 +661,7 @@ fn forward_auth_requires_site_configuration() { contents: "", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"), }], ); @@ -704,7 +687,7 @@ fn rejects_bad_forward_auth_site_config() { contents: &format!("[forward_auth]\nurl = {bad:?}\n"), }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -743,15 +726,15 @@ fn collects_errors_from_every_file() { &site(), &[ SourceFile { - name: "a.test.toml", + name: "hosts/a.test.toml", contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n", }, SourceFile { - name: "B.test.toml", + name: "hosts/B.test.toml", contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }, SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, ], @@ -830,7 +813,7 @@ fn rejects_wildcards_in_copy_headers() { contents: "[forward_auth]\nurl = \"http://127.0.0.1:9091/x\"\ncopy_headers = [\"Remote-*\"]\n", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -861,7 +844,7 @@ fn rejects_oversized_route_files() { contents: &big, }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); diff --git a/crates/core/tests/share.rs b/crates/core/tests/share.rs new file mode 100644 index 0000000..f7f8146 --- /dev/null +++ b/crates/core/tests/share.rs @@ -0,0 +1,378 @@ +// 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/. + +//! Share-link tokens (ROADMAP §6 phase 2, tests first): a token is refused when expired, for +//! the wrong path, for the wrong host, tampered, without its password or with a wrong one, +//! and no path trick lets it escape its prefix. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::BTreeSet; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use ianitor_core::share::{ + Claims, LinkSpec, Rejection, Revocations, ShareId, ShareKey, check_prefix, mint, path_within, + peek, session_value, verify_link, verify_session, +}; + +const NOW: u64 = 1_800_000_000; +const HOST: &str = "photos.home.test"; + +fn key() -> ShareKey { + ShareKey::new(b"0123456789abcdef0123456789abcdef-test-key").unwrap() +} + +fn other_key() -> ShareKey { + ShareKey::new(b"fedcba9876543210fedcba9876543210-test-key").unwrap() +} + +fn id(n: u8) -> ShareId { + ShareId([n; 16]) +} + +fn spec<'a>(prefix: &'a str, password: Option<&'a str>) -> LinkSpec<'a> { + LinkSpec { + id: id(7), + epoch: 3, + expires_at: NOW + 3600, + prefix, + password, + } +} + +fn none() -> Revocations { + Revocations { + epoch: 3, + deny: BTreeSet::new(), + } +} + +fn token(prefix: &str, password: Option<&str>) -> String { + mint(&key(), HOST, &spec(prefix, password)).unwrap() +} + +#[test] +fn a_fresh_token_is_accepted_and_says_what_it_covers() { + let t = token("/albums/summer", None); + assert!(t.starts_with("ish1."), "{t}"); + let c = verify_link(&key(), HOST, &t, None, NOW, &none()).unwrap(); + assert_eq!( + c, + Claims { + id: id(7), + epoch: 3, + expires_at: NOW + 3600, + password: false, + prefix: "/albums/summer".into() + } + ); +} + +#[test] +fn an_expired_token_is_refused_as_expired() { + let t = token("/", None); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW + 3600, &none()), + Err(Rejection::Expired { + expires_at: NOW + 3600 + }) + ); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW + 99_999, &none()), + Err(Rejection::Expired { + expires_at: NOW + 3600 + }) + ); +} + +#[test] +fn a_token_for_another_host_is_refused() { + let t = token("/", None); + for host in ["other.home.test", "PHOTOS.home.test", "photos.home.test.", "photos.home"] { + assert_eq!( + verify_link(&key(), host, &t, None, NOW, &none()), + Err(Rejection::Invalid), + "{host}" + ); + } +} + +#[test] +fn a_token_made_with_another_key_is_refused() { + let t = mint(&other_key(), HOST, &spec("/", None)).unwrap(); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &none()), + Err(Rejection::Invalid) + ); +} + +#[test] +fn every_single_bit_flip_is_refused() { + let t = token("/albums", None); + let raw = URL_SAFE_NO_PAD.decode(t.strip_prefix("ish1.").unwrap()).unwrap(); + for i in 0..raw.len() { + for bit in 0..8 { + let mut r = raw.clone(); + r[i] ^= 1 << bit; + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&r)); + let got = verify_link(&key(), HOST, &forged, None, NOW, &none()); + assert!( + matches!( + got, + Err(Rejection::Invalid | Rejection::Malformed | Rejection::PasswordRequired) + ), + "byte {i} bit {bit}: {got:?}" + ); + } + } +} + +#[test] +fn a_longer_expiry_or_wider_prefix_cannot_be_spliced_in() { + let t = token("/albums/summer", None); + let raw = URL_SAFE_NO_PAD.decode(t.strip_prefix("ish1.").unwrap()).unwrap(); + let (payload, mac) = raw.split_at(raw.len() - 32); + // Same MAC, prefix cut down to "/albums". + let mut p = payload[..30].to_vec(); + p.extend_from_slice(b"/albums"); + p.extend_from_slice(mac); + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p)); + assert_eq!( + verify_link(&key(), HOST, &forged, None, NOW, &none()), + Err(Rejection::Invalid) + ); + // Same MAC, expiry pushed out. + let mut p = payload.to_vec(); + p[21..29].copy_from_slice(&(NOW + 10 * 3600).to_be_bytes()); + p.extend_from_slice(mac); + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p)); + assert_eq!( + verify_link(&key(), HOST, &forged, None, NOW, &none()), + Err(Rejection::Invalid) + ); +} + +#[test] +fn garbage_is_malformed_never_a_panic() { + for bad in [ + "", + "ish1.", + "ish1.!!!!", + "ish2.AAAA", + "iss1.AAAA", + "ish1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + &"ish1.".repeat(400), + "ish1.\u{0}", + ] { + assert_eq!( + verify_link(&key(), HOST, bad, None, NOW, &none()), + Err(Rejection::Malformed), + "{bad:?}" + ); + } +} + +#[test] +fn a_password_link_needs_its_password() { + let t = token("/", Some("correct horse")); + assert!(peek(&t).unwrap().password); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &none()), + Err(Rejection::PasswordRequired) + ); + for wrong in ["", "correct hors", "correct horse ", "Correct horse", "x"] { + assert_eq!( + verify_link(&key(), HOST, &t, Some(wrong), NOW, &none()), + Err(Rejection::Invalid), + "{wrong:?}" + ); + } + let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap(); + assert!(c.password); +} + +#[test] +fn the_token_carries_no_password_hash() { + // Two links that differ only in the password have the same payload; only the MAC differs. + let a = token("/", Some("password-one")); + let b = token("/", Some("password-two")); + let ra = URL_SAFE_NO_PAD.decode(a.strip_prefix("ish1.").unwrap()).unwrap(); + let rb = URL_SAFE_NO_PAD.decode(b.strip_prefix("ish1.").unwrap()).unwrap(); + assert_eq!(ra.len(), rb.len()); + assert_eq!(ra[..ra.len() - 32], rb[..rb.len() - 32]); + assert_ne!(ra[ra.len() - 32..], rb[rb.len() - 32..]); +} + +#[test] +fn a_dropped_password_flag_does_not_open_the_link() { + let t = token("/", Some("correct horse")); + let mut raw = URL_SAFE_NO_PAD.decode(t.strip_prefix("ish1.").unwrap()).unwrap(); + raw[29] = 0; + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&raw)); + assert_eq!( + verify_link(&key(), HOST, &forged, None, NOW, &none()), + Err(Rejection::Invalid) + ); +} + +#[test] +fn passwords_are_8_to_128_characters() { + assert!(mint(&key(), HOST, &spec("/", Some("short"))).is_err()); + assert!(mint(&key(), HOST, &spec("/", Some(&"x".repeat(129)))).is_err()); + assert!(mint(&key(), HOST, &spec("/", Some("12345678"))).is_ok()); +} + +#[test] +fn stopped_links_and_older_epochs_are_revoked() { + let t = token("/", None); + let mut r = none(); + r.deny.insert(id(7)); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &r), + Err(Rejection::Revoked) + ); + let r = Revocations { + epoch: 4, + deny: BTreeSet::new(), + }; + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &r), + Err(Rejection::Revoked) + ); + // Another link on the deny list does not matter. + let mut r = none(); + r.deny.insert(id(8)); + assert!(verify_link(&key(), HOST, &t, None, NOW, &r).is_ok()); +} + +#[test] +fn session_cookies_and_link_tokens_are_not_interchangeable() { + let t = token("/albums", Some("correct horse")); + let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap(); + let s = session_value(&key(), HOST, &c); + assert!(s.starts_with("iss1.")); + assert_eq!(verify_session(&key(), HOST, &s, NOW, &none()).unwrap(), c); + // A cookie is not a link, a link is not a cookie, even with the prefix swapped. + assert!(verify_link(&key(), HOST, &s, None, NOW, &none()).is_err()); + assert!(verify_session(&key(), HOST, &t, NOW, &none()).is_err()); + let swapped = s.replacen("iss1.", "ish1.", 1); + assert!(verify_link(&key(), HOST, &swapped, Some("correct horse"), NOW, &none()).is_err()); + let swapped = t.replacen("ish1.", "iss1.", 1); + assert!(verify_session(&key(), HOST, &swapped, NOW, &none()).is_err()); + // Cookies are host-bound, expire and are revoked like links. + assert_eq!( + verify_session(&key(), "other.home.test", &s, NOW, &none()), + Err(Rejection::Invalid) + ); + assert!(matches!( + verify_session(&key(), HOST, &s, NOW + 3600, &none()), + Err(Rejection::Expired { .. }) + )); + let mut r = none(); + r.deny.insert(id(7)); + assert_eq!( + verify_session(&key(), HOST, &s, NOW, &r), + Err(Rejection::Revoked) + ); +} + +#[test] +fn short_keys_are_refused() { + assert!(ShareKey::new(b"short").is_err()); + assert!(ShareKey::new(&[0u8; 31]).is_err()); + assert!(ShareKey::new(&[0u8; 32]).is_ok()); + assert!(!format!("{:?}", key()).contains("0123")); +} + +#[test] +fn prefixes_are_normalised_or_refused() { + assert_eq!(check_prefix("/").unwrap(), "/"); + assert_eq!(check_prefix("/a/").unwrap(), "/a"); + assert_eq!(check_prefix("/albums/summer-2026").unwrap(), "/albums/summer-2026"); + for bad in [ + "", "a", "//", "/a//b", "/a/../b", "/..", "/.", "/a/./b", "/a%2fb", "/a\\b", "/a b", + "/a;b", "/ä", "/a?b", "/a#b", + ] { + assert!(check_prefix(bad).is_err(), "{bad:?} accepted"); + } + assert!(check_prefix(&format!("/{}", "a".repeat(256))).is_err()); + // A prefix that is not in normal form is not minted. + assert!(mint(&key(), HOST, &spec("/a/", None)).is_err()); +} + +#[test] +fn ids_round_trip_as_hex() { + let i = ShareId([0xab; 16]); + assert_eq!(i.to_hex(), "ab".repeat(16)); + assert_eq!(ShareId::from_hex(&i.to_hex()), Some(i)); + for bad in ["", "ab", &"AB".repeat(16), &"zz".repeat(16), &"a".repeat(33)] { + assert_eq!(ShareId::from_hex(bad), None, "{bad:?}"); + } +} + +// ------------------------------------------------------------------ prefix escapes + +#[test] +fn paths_under_the_prefix_are_within() { + for (prefix, path) in [ + ("/a", "/a"), + ("/a", "/a/"), + ("/a", "/a/b"), + ("/a", "/a/b/c.jpg"), + ("/a", "/a/b%20c"), + ("/a", "/a/%E2%9C%93"), + ("/", "/"), + ("/", "/anything/at/all"), + ("/a/b", "/a/b/c"), + ("/a", "/a/b;v=1"), + ("/a", "/a/.well"), + ] { + assert!(path_within(prefix, path), "{prefix} should cover {path}"); + } +} + +#[test] +fn no_path_trick_escapes_the_prefix() { + let cases = [ + ("/a", "/ab"), + ("/a", "/abc/d"), + ("/a", "/A"), + ("/a", "/A/b"), + ("/a/b", "/a"), + ("/a/b", "/a/bc"), + ("/a", "/b"), + ("/a", "/a/../b"), + ("/a", "/a/.."), + ("/a", "/a/./../b"), + ("/a", "/a/%2e%2e/b"), + ("/a", "/a/%2E%2E/b"), + ("/a", "/a/.%2e/b"), + ("/a", "/a/%2e./b"), + ("/a", "/a/%252e%252e/b"), + ("/a", "/a/%25252e/b"), + ("/a", "/a%2f..%2fb"), + ("/a", "/a%2F..%2Fb"), + ("/a", "/a/..%2fb"), + ("/a", "/a//b"), + ("/a", "//a/b"), + ("/a", "/a\\..\\b"), + ("/a", "/a/..\\b"), + ("/a", "/a%5c..%5cb"), + ("/a", "/a/..;/b"), + ("/a", "/a/.;/b"), + ("/a", "/a/%00/b"), + ("/a", "/a/b c"), + ("/a", "/a/\tb"), + ("/a", "a/b"), + ("/a", ""), + ("/a", "/a/ä"), + ("/", "/../etc/passwd"), + ("/", "//evil"), + ("/", "/%2e%2e/x"), + ]; + for (prefix, path) in cases { + assert!(!path_within(prefix, path), "{prefix} must not cover {path:?}"); + } +} From 94ba18d38bff9caadefad7a4f40331bae8167472 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 17:32:44 +0100 Subject: [PATCH 03/38] [core] Share links and repo layout: HMAC tokens with epoch, prefix check, exact hosts/.toml, error codes; edge config v2 --- crates/core/src/error.rs | 162 ++++++++++++++++++++++++++++- crates/core/src/lib.rs | 4 +- crates/core/src/routes.rs | 60 +++++++++-- crates/core/src/share.rs | 84 +++++++++++++-- crates/core/src/validate.rs | 19 ++-- crates/core/tests/golden/edge.json | 11 +- crates/core/tests/routes.rs | 11 +- crates/core/tests/share.rs | 45 ++++++-- 8 files changed, 348 insertions(+), 48 deletions(-) diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index e3560c4..a371155 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -224,23 +224,175 @@ impl ValidationError { /// A stable code the UI switches on, e.g. `host.upstream.no_port` (docs/ui-api.md §3.1). pub fn code(&self) -> &'static str { - // Tests first: not written yet. - "unknown" + use ValidationError as E; + use reason as r; + let site = self.in_site_file(); + match self { + E::Syntax { .. } => "file.syntax", + E::UnknownField { .. } if site => "site.field.unknown", + E::UnknownField { .. } => "host.field.unknown", + E::MissingField { field, .. } if !site && field == "hostname" => { + "host.hostname.missing" + } + E::MissingField { field, .. } if !site && field == "upstreams" => { + "host.upstreams.missing" + } + E::MissingField { .. } => "file.field.missing", + E::InvalidValue { .. } => "file.field.invalid", + E::DuplicateFile { .. } => "repo.duplicate_file", + E::FileTooLarge { .. } => "file.too_large", + E::FileNameMismatch { .. } => "host.file_name", + E::UnexpectedFile { .. } => "repo.unexpected_file", + E::TooManyUpstreams { .. } => "host.upstream.too_many", + E::InvalidHostname { reason, .. } => match *reason { + x if x == r::HOST_EMPTY => "host.hostname.missing", + x if x == r::HOST_TOO_LONG => "host.hostname.too_long", + x if x == r::HOST_IP || x == r::HOST_NUMERIC => "host.hostname.numeric", + x if x == r::HOST_WILDCARD => "host.hostname.wildcard", + x if x == r::HOST_TRAILING_DOT => "host.hostname.trailing_dot", + x if x == r::HOST_UPPERCASE => "host.hostname.uppercase", + x if x == r::HOST_SPACES => "host.hostname.spaces", + x if x == r::HOST_EMPTY_LABEL => "host.hostname.empty_label", + x if x == r::HOST_LABEL_LONG => "host.hostname.label_long", + x if x == r::HOST_LABEL_DASH => "host.hostname.label_dash", + _ => "host.hostname.characters", + }, + E::DuplicateHostname { .. } => "host.hostname.taken", + E::NoUpstreams { .. } => "host.upstreams.missing", + E::BadUpstreamUrl { reason, .. } => match *reason { + x if x == r::URL_SCHEME => "host.upstream.scheme", + x if x == r::URL_CREDENTIALS => "host.upstream.credentials", + x if x == r::URL_FRAGMENT => "host.upstream.fragment", + x if x == r::URL_NO_HOST => "host.upstream.no_host", + x if x == r::URL_HOST_NAME => "host.upstream.host_name", + x if x == r::URL_NO_PORT => "host.upstream.no_port", + x if x == r::URL_PORT_ZERO => "host.upstream.port_zero", + x if x == r::URL_PATH => "host.upstream.path", + x if x == r::URL_QUERY => "host.upstream.query", + x if x == r::URL_MIXED => "host.upstream.mixed_schemes", + _ => "host.upstream.not_url", + }, + E::DuplicateUpstream { .. } => "host.upstream.duplicate", + E::UndefinedSecret { .. } => "host.header.secret_unknown", + E::SecretInResponseHeader { .. } => "host.header.secret_response", + E::InvalidSecretName { .. } => "site.secret.name", + E::InvalidHeaderName { .. } | E::ProtectedHeader { .. } if site => { + "site.forward_auth.header" + } + E::InvalidHeaderName { .. } => "host.header.name", + E::InvalidHeaderValue { reason, .. } if *reason == r::VALUE_EMPTY => { + "host.header.empty" + } + E::InvalidHeaderValue { .. } => "host.header.value", + E::ProtectedHeader { .. } => "host.header.protected", + E::DuplicateHeaderRule { .. } => "host.header.duplicate", + E::BadHeaderRule { reason, .. } => match *reason { + x if x == r::RULE_BOTH => "host.header.both", + x if x == r::RULE_REMOVE_VALUE => "host.header.remove_value", + _ => "host.header.empty", + }, + E::BadHealthCheck { reason, .. } if *reason == r::HEALTH_INTERVAL => { + "host.health.interval" + } + E::BadHealthCheck { .. } => "host.health.path", + E::ForwardAuthNotConfigured { .. } => "host.auth.not_configured", + E::BadForwardAuth { .. } => "site.forward_auth", + E::BadAcme { .. } => "site.acme", + } } /// The form field the problem is about, as a path into the host body (`hostname`, /// `upstreams[0]`, `request_headers[2].name`, `health_check.path`), or `None`. pub fn field(&self) -> Option { - // Tests first: not written yet. - None + use ValidationError as E; + if self.in_site_file() { + return None; + } + match self { + E::UnknownField { field, .. } | E::MissingField { field, .. } => Some(field.clone()), + E::FileNameMismatch { .. } + | E::InvalidHostname { .. } + | E::DuplicateHostname { .. } => Some("hostname".into()), + E::TooManyUpstreams { .. } | E::NoUpstreams { .. } => Some("upstreams".into()), + E::BadUpstreamUrl { index, .. } => Some(match index { + Some(i) => format!("upstreams[{i}]"), + None => "upstreams".into(), + }), + E::DuplicateUpstream { index, .. } => Some(format!("upstreams[{index}]")), + E::UndefinedSecret { field, .. } + | E::SecretInResponseHeader { field, .. } + | E::InvalidHeaderName { field, .. } + | E::InvalidHeaderValue { field, .. } + | E::ProtectedHeader { field, .. } + | E::DuplicateHeaderRule { field, .. } + | E::BadHeaderRule { field, .. } => Some(field.clone()), + E::BadHealthCheck { reason, .. } if *reason == reason::HEALTH_INTERVAL => { + Some("health_check.interval_secs".into()) + } + E::BadHealthCheck { .. } => Some("health_check.path".into()), + E::ForwardAuthNotConfigured { .. } => Some("auth".into()), + _ => None, + } } /// The values a message shows: always `file`, plus `line`, `field`, `max`, `hostname`, /// `suggestion`, `url`, `name` or `secret` where they apply. pub fn params(&self) -> BTreeMap<&'static str, String> { - // Tests first: not written yet. + use ValidationError as E; let mut p = BTreeMap::new(); p.insert("file", self.file().to_owned()); + match self { + E::Syntax { line: Some(l), .. } => { + p.insert("line", l.to_string()); + } + E::UnknownField { field, .. } | E::MissingField { field, .. } => { + p.insert("field", field.clone()); + } + E::FileTooLarge { max, .. } | E::TooManyUpstreams { max, .. } => { + p.insert("max", max.to_string()); + } + E::FileNameMismatch { hostname, .. } | E::DuplicateHostname { hostname, .. } => { + p.insert("hostname", hostname.clone()); + } + E::InvalidHostname { + hostname, reason, .. + } => { + p.insert("hostname", hostname.clone()); + if *reason == reason::HOST_UPPERCASE || *reason == reason::HOST_TRAILING_DOT { + p.insert( + "suggestion", + hostname.trim_end_matches('.').to_ascii_lowercase(), + ); + } + } + E::BadUpstreamUrl { url, reason, .. } => { + p.insert("url", url.clone()); + if [reason::URL_PATH, reason::URL_QUERY, reason::URL_FRAGMENT].contains(reason) + && let Ok(u) = url::Url::parse(url) + && let Some(host) = u.host_str() + { + let port = u.port().map(|p| format!(":{p}")).unwrap_or_default(); + p.insert("suggestion", format!("{}://{host}{port}", u.scheme())); + } + } + E::DuplicateUpstream { url, .. } => { + p.insert("url", url.clone()); + } + E::UndefinedSecret { secret, .. } => { + p.insert("secret", secret.clone()); + } + E::InvalidSecretName { name, .. } | E::InvalidHeaderName { name, .. } => { + p.insert("name", name.clone()); + } + E::SecretInResponseHeader { header, .. } + | E::InvalidHeaderValue { header, .. } + | E::ProtectedHeader { header, .. } + | E::DuplicateHeaderRule { header, .. } + | E::BadHeaderRule { header, .. } => { + p.insert("name", header.clone()); + } + _ => {} + } p } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 01d47c5..bf364ff 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -19,7 +19,7 @@ mod validate; pub use error::{ValidationError, ValidationErrors}; pub use model::{ AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, - HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, Model, Scheme, - MAX_FILE_BYTES, MAX_UPSTREAMS, SecretName, Site, TlsMode, Upstream, UpstreamHost, + HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES, + MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, }; pub use validate::{SourceFile, load}; diff --git a/crates/core/src/routes.rs b/crates/core/src/routes.rs index 8bb863a..9ca5430 100644 --- a/crates/core/src/routes.rs +++ b/crates/core/src/routes.rs @@ -44,18 +44,62 @@ pub fn host_path(hostname: &str) -> String { /// Check one path of the repository tree (as listed recursively, `/`-separated). pub fn check_path(path: &str, kind: EntryKind) -> Result { - // Tests first: not written yet. - let _ = (kind, reason::PATH_LAYOUT, check_hostname); - match path.strip_prefix("hosts/").and_then(|r| r.strip_suffix(".toml")) { - Some(h) => Ok(RoutePath::Host { hostname: h.to_owned() }), - None => Ok(RoutePath::Site), + let bad = |reason| ValidationError::UnexpectedFile { + file: path.to_owned(), + reason, + }; + if kind != EntryKind::File { + return Err(bad(reason::PATH_KIND)); } + if path == SITE_FILE { + return Ok(RoutePath::Site); + } + let Some(rest) = path.strip_prefix("hosts/") else { + return Err(bad(reason::PATH_LAYOUT)); + }; + if rest.contains(['/', '\\']) { + return Err(bad(reason::PATH_SUBDIR)); + } + let Some(hostname) = rest.strip_suffix(".toml") else { + return Err(bad(reason::PATH_NAME)); + }; + if check_hostname(hostname).is_err() { + return Err(bad(reason::PATH_NAME)); + } + Ok(RoutePath::Host { + hostname: hostname.to_owned(), + }) } -/// Check a whole tree listing. +/// Check a whole tree listing. Returns every problem; at most [`MAX_HOST_FILES`] host files. pub fn check_tree<'a>( entries: impl IntoIterator, ) -> Result<(), Vec> { - let _ = entries.into_iter().count(); - Ok(()) + let mut errors = Vec::new(); + let mut hosts = 0usize; + let mut site = false; + for (path, kind) in entries { + match check_path(path, kind) { + Ok(RoutePath::Site) => site = true, + Ok(RoutePath::Host { .. }) => hosts += 1, + Err(e) => errors.push(e), + } + } + if !site { + errors.push(ValidationError::MissingField { + file: SITE_FILE.into(), + field: "(the file itself)".into(), + }); + } + if hosts > MAX_HOST_FILES { + errors.push(ValidationError::UnexpectedFile { + file: HOSTS_DIR.into(), + reason: "more than 1000 host files", + }); + } + if errors.is_empty() { + Ok(()) + } else { + Err(errors) + } } diff --git a/crates/core/src/share.rs b/crates/core/src/share.rs index 884b961..e06e5c3 100644 --- a/crates/core/src/share.rs +++ b/crates/core/src/share.rs @@ -276,6 +276,9 @@ fn decode(token: &str, prefix: &str) -> Result<(Claims, Vec, Vec), Rejec x.copy_from_slice(&p[21..29]); let prefix = std::str::from_utf8(&p[FIXED_LEN..]).map_err(|_| Rejection::Malformed)?; // A token whose prefix is not in normal form was never minted. + if check_prefix(prefix).ok().as_deref() != Some(prefix) { + return Err(Rejection::Malformed); + } Ok(( Claims { id: ShareId(id), @@ -306,8 +309,15 @@ pub fn verify_link( now: u64, revocations: &Revocations, ) -> Result { - let _ = (key, host, password, now, revocations); - peek(token) + let (claims, p, mac) = decode(token, LINK_PREFIX)?; + let password = match (claims.password, password) { + (true, None) => return Err(Rejection::PasswordRequired), + (true, Some(pw)) => Some(pw), + (false, _) => None, + }; + let msg = link_message(key, host, &p, &claims.id, password); + hmac::verify(&key.0, &msg, &mac).map_err(|_| Rejection::Invalid)?; + finish(claims, now, revocations) } fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result { @@ -346,16 +356,45 @@ pub fn verify_session( now: u64, revocations: &Revocations, ) -> Result { - let _ = (key, host, now, revocations); - decode(value, SESSION_PREFIX).map(|(c, _, _)| c) + let (claims, p, mac) = decode(value, SESSION_PREFIX)?; + hmac::verify(&key.0, &session_message(host, &p), &mac).map_err(|_| Rejection::Invalid)?; + finish(claims, now, revocations) } /// Normalise and check a path prefix: starts with `/`, at most [`MAX_PREFIX_LEN`] bytes, only /// unreserved characters and `!$&'()*+,=:@-._~`, no `%`, `;`, backslash, empty segment or dot /// segment. A trailing `/` is dropped (except for `/` itself). pub fn check_prefix(prefix: &str) -> Result { - // Tests first: not written yet. - Ok(prefix.to_owned()) + if !prefix.starts_with('/') { + return Err("it must start with /"); + } + if prefix.len() > MAX_PREFIX_LEN { + return Err("it is longer than 256 characters"); + } + let ok = |c: u8| c.is_ascii_alphanumeric() || b"/!$&'()*+,=:@-._~".contains(&c); + if !prefix.bytes().all(ok) { + return Err("only letters, digits, / and -._~!$&'()*+,=:@ are allowed"); + } + if prefix.contains("//") { + return Err("it has an empty segment (//)"); + } + let trimmed = if prefix.len() > 1 { + prefix.strip_suffix('/').unwrap_or(prefix) + } else { + prefix + }; + if trimmed == "/" { + return Ok("/".into()); + } + for seg in trimmed[1..].split('/') { + if seg.is_empty() { + return Err("it has an empty segment (//)"); + } + if seg.bytes().all(|c| c == b'.') { + return Err("it has a . or .. segment"); + } + } + Ok(trimmed.to_owned()) } /// Is `raw_path` (the request path exactly as sent, still percent-encoded) under `prefix`? @@ -365,6 +404,35 @@ pub fn check_prefix(prefix: &str) -> Result { /// forms of `.`, `/`, `\`, `%` and NUL. Other paths match on whole segments, case-sensitively: /// prefix `/a` covers `/a` and `/a/x`, not `/ab` or `/A`. pub fn path_within(prefix: &str, raw_path: &str) -> bool { - // Tests first: not written yet. - raw_path.starts_with(prefix) + if !raw_path.starts_with('/') + || !raw_path.bytes().all(|c| c.is_ascii_graphic()) + || raw_path.contains('\\') + { + return false; + } + let lower = raw_path.to_ascii_lowercase(); + if ["%2e", "%2f", "%5c", "%25", "%00"] + .iter() + .any(|bad| lower.contains(bad)) + { + return false; + } + // An empty segment anywhere but at the end (a trailing slash) is `//`. + if raw_path.contains("//") { + return false; + } + for seg in raw_path[1..].split('/') { + // `..;x` is `..` to Tomcat and friends. + let name = seg.split(';').next().unwrap_or(seg); + if !name.is_empty() && name.bytes().all(|c| c == b'.') { + return false; + } + } + if prefix == "/" { + return true; + } + match raw_path.strip_prefix(prefix) { + Some(rest) => rest.is_empty() || rest.starts_with('/'), + None => false, + } } diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index 0158415..ffde427 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -377,9 +377,8 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec reason, }), Ok(()) => { - // One TOML per host, named after it: `hosts/.toml`. - let base = file.rsplit(['/', '\\']).next().unwrap_or(file); - if base != format!("{}.toml", raw.hostname) { + // One TOML per host, named after it: exactly `hosts/.toml`. + if file != format!("hosts/{}.toml", raw.hostname) { errors.push(E::FileNameMismatch { file: f(), hostname: raw.hostname.clone(), @@ -481,9 +480,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec .bytes() .all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c)); if !ok_path { - errors.push(bad( - r::HEALTH_PATH, - )); + errors.push(bad(r::HEALTH_PATH)); return None; } match u32::try_from(hc.interval_secs) { @@ -594,14 +591,16 @@ fn check_rules( file: f(), header: header.clone(), reason, - field: at(if reason == r::RULE_NEITHER { "value" } else { "" }), + field: at(if reason == r::RULE_NEITHER { + "value" + } else { + "" + }), }; match (r.action, r.value, r.secret) { (RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }), (RawAction::Remove, _, _) => errors.push(bad(r::RULE_REMOVE_VALUE)), - (RawAction::Set, Some(_), Some(_)) => { - errors.push(bad(r::RULE_BOTH)) - } + (RawAction::Set, Some(_), Some(_)) => errors.push(bad(r::RULE_BOTH)), (RawAction::Set, None, None) => errors.push(bad(r::RULE_NEITHER)), (RawAction::Set, Some(v), None) => match check_header_value(&v) { Ok(()) => out.push(HeaderRule::Set { diff --git a/crates/core/tests/golden/edge.json b/crates/core/tests/golden/edge.json index f7bb580..d673595 100644 --- a/crates/core/tests/golden/edge.json +++ b/crates/core/tests/golden/edge.json @@ -1,5 +1,5 @@ { - "version": 1, + "version": 2, "http_listen": "0.0.0.0:80", "https_listen": "0.0.0.0:443", "https_port": 443, @@ -82,7 +82,8 @@ "path": "/api/v1/status", "interval_secs": 15 }, - "access_log": true + "access_log": true, + "share_links": false }, { "hostname": "status.example.org", @@ -101,7 +102,8 @@ "request_headers": [], "response_headers": [], "health_check": null, - "access_log": false + "access_log": false, + "share_links": false }, { "hostname": "wiki.home.test", @@ -131,7 +133,8 @@ ], "response_headers": [], "health_check": null, - "access_log": false + "access_log": false, + "share_links": false } ] } diff --git a/crates/core/tests/routes.rs b/crates/core/tests/routes.rs index f288343..3122d63 100644 --- a/crates/core/tests/routes.rs +++ b/crates/core/tests/routes.rs @@ -145,7 +145,11 @@ fn errors_have_codes_fields_and_params_for_the_ui() { "host.hostname.missing", Some("hostname"), ), - ("hostname = \"app.test\"\n", "host.upstreams.missing", Some("upstreams")), + ( + "hostname = \"app.test\"\n", + "host.upstreams.missing", + Some("upstreams"), + ), ( "hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", "host.hostname.uppercase", @@ -227,7 +231,10 @@ fn params_carry_suggestions() { .unwrap(); assert_eq!(e.params()["suggestion"], "app.test"); let errs = errors_for("hostname = \"app.test\"\nupstreams = [\"http://10.0.0.2:3000/app\"]\n"); - let e = errs.iter().find(|e| e.code() == "host.upstream.path").unwrap(); + let e = errs + .iter() + .find(|e| e.code() == "host.upstream.path") + .unwrap(); assert_eq!(e.params()["suggestion"], "http://10.0.0.2:3000"); assert_eq!(e.params()["url"], "http://10.0.0.2:3000/app"); } diff --git a/crates/core/tests/share.rs b/crates/core/tests/share.rs index f7f8146..716620b 100644 --- a/crates/core/tests/share.rs +++ b/crates/core/tests/share.rs @@ -90,7 +90,12 @@ fn an_expired_token_is_refused_as_expired() { #[test] fn a_token_for_another_host_is_refused() { let t = token("/", None); - for host in ["other.home.test", "PHOTOS.home.test", "photos.home.test.", "photos.home"] { + for host in [ + "other.home.test", + "PHOTOS.home.test", + "photos.home.test.", + "photos.home", + ] { assert_eq!( verify_link(&key(), host, &t, None, NOW, &none()), Err(Rejection::Invalid), @@ -111,7 +116,9 @@ fn a_token_made_with_another_key_is_refused() { #[test] fn every_single_bit_flip_is_refused() { let t = token("/albums", None); - let raw = URL_SAFE_NO_PAD.decode(t.strip_prefix("ish1.").unwrap()).unwrap(); + let raw = URL_SAFE_NO_PAD + .decode(t.strip_prefix("ish1.").unwrap()) + .unwrap(); for i in 0..raw.len() { for bit in 0..8 { let mut r = raw.clone(); @@ -132,7 +139,9 @@ fn every_single_bit_flip_is_refused() { #[test] fn a_longer_expiry_or_wider_prefix_cannot_be_spliced_in() { let t = token("/albums/summer", None); - let raw = URL_SAFE_NO_PAD.decode(t.strip_prefix("ish1.").unwrap()).unwrap(); + let raw = URL_SAFE_NO_PAD + .decode(t.strip_prefix("ish1.").unwrap()) + .unwrap(); let (payload, mac) = raw.split_at(raw.len() - 32); // Same MAC, prefix cut down to "/albums". let mut p = payload[..30].to_vec(); @@ -198,8 +207,12 @@ fn the_token_carries_no_password_hash() { // Two links that differ only in the password have the same payload; only the MAC differs. let a = token("/", Some("password-one")); let b = token("/", Some("password-two")); - let ra = URL_SAFE_NO_PAD.decode(a.strip_prefix("ish1.").unwrap()).unwrap(); - let rb = URL_SAFE_NO_PAD.decode(b.strip_prefix("ish1.").unwrap()).unwrap(); + let ra = URL_SAFE_NO_PAD + .decode(a.strip_prefix("ish1.").unwrap()) + .unwrap(); + let rb = URL_SAFE_NO_PAD + .decode(b.strip_prefix("ish1.").unwrap()) + .unwrap(); assert_eq!(ra.len(), rb.len()); assert_eq!(ra[..ra.len() - 32], rb[..rb.len() - 32]); assert_ne!(ra[ra.len() - 32..], rb[rb.len() - 32..]); @@ -208,7 +221,9 @@ fn the_token_carries_no_password_hash() { #[test] fn a_dropped_password_flag_does_not_open_the_link() { let t = token("/", Some("correct horse")); - let mut raw = URL_SAFE_NO_PAD.decode(t.strip_prefix("ish1.").unwrap()).unwrap(); + let mut raw = URL_SAFE_NO_PAD + .decode(t.strip_prefix("ish1.").unwrap()) + .unwrap(); raw[29] = 0; let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&raw)); assert_eq!( @@ -290,7 +305,10 @@ fn short_keys_are_refused() { fn prefixes_are_normalised_or_refused() { assert_eq!(check_prefix("/").unwrap(), "/"); assert_eq!(check_prefix("/a/").unwrap(), "/a"); - assert_eq!(check_prefix("/albums/summer-2026").unwrap(), "/albums/summer-2026"); + assert_eq!( + check_prefix("/albums/summer-2026").unwrap(), + "/albums/summer-2026" + ); for bad in [ "", "a", "//", "/a//b", "/a/../b", "/..", "/.", "/a/./b", "/a%2fb", "/a\\b", "/a b", "/a;b", "/ä", "/a?b", "/a#b", @@ -307,7 +325,13 @@ fn ids_round_trip_as_hex() { let i = ShareId([0xab; 16]); assert_eq!(i.to_hex(), "ab".repeat(16)); assert_eq!(ShareId::from_hex(&i.to_hex()), Some(i)); - for bad in ["", "ab", &"AB".repeat(16), &"zz".repeat(16), &"a".repeat(33)] { + for bad in [ + "", + "ab", + &"AB".repeat(16), + &"zz".repeat(16), + &"a".repeat(33), + ] { assert_eq!(ShareId::from_hex(bad), None, "{bad:?}"); } } @@ -373,6 +397,9 @@ fn no_path_trick_escapes_the_prefix() { ("/", "/%2e%2e/x"), ]; for (prefix, path) in cases { - assert!(!path_within(prefix, path), "{prefix} must not cover {path:?}"); + assert!( + !path_within(prefix, path), + "{prefix} must not cover {path:?}" + ); } } From 7c8194577163a16dca2f6da405d823a51f0296c6 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 17:47:42 +0100 Subject: [PATCH 04/38] [core] Time: RFC 3339 and long dates from Unix seconds --- crates/core/src/lib.rs | 1 + crates/core/src/time.rs | 73 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 crates/core/src/time.rs diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index bf364ff..c3536b0 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -14,6 +14,7 @@ mod error; mod model; pub mod routes; pub mod share; +pub mod time; mod validate; pub use error::{ValidationError, ValidationErrors}; diff --git a/crates/core/src/time.rs b/crates/core/src/time.rs new file mode 100644 index 0000000..56eee7c --- /dev/null +++ b/crates/core/src/time.rs @@ -0,0 +1,73 @@ +// 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/. + +//! Unix seconds to calendar dates (UTC), for API timestamps and visitor pages. Pure: the +//! caller passes the time in. + +/// Days since 1970-01-01 → (year, month 1–12, day 1–31). Howard Hinnant's `civil_from_days`. +fn civil_from_days(days: i64) -> (i64, u32, u32) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +/// `2026-11-14T14:20:00Z`. +pub fn rfc3339(unix: u64) -> String { + let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2); + let (y, m, d) = civil_from_days(secs.div_euclid(86_400)); + let s = secs.rem_euclid(86_400); + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + s / 3600, + (s / 60) % 60, + s % 60 + ) +} + +const MONTHS: [&str; 12] = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +]; + +/// `14 November 2026` (UTC). +pub fn long_date(unix: u64) -> String { + let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2); + let (y, m, d) = civil_from_days(secs.div_euclid(86_400)); + let month = MONTHS + .get(m.saturating_sub(1) as usize) + .copied() + .unwrap_or("?"); + format!("{d} {month} {y}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_dates() { + assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z"); + assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z"); + assert_eq!(rfc3339(1_794_666_000), "2026-11-14T14:20:00Z"); + assert_eq!(long_date(1_794_666_000), "14 November 2026"); + assert_eq!(long_date(4_133_980_799), "31 December 2100"); + } +} From c0ed9c65c53033f7721a0ae7124364ab2ba298ce Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 17:47:43 +0100 Subject: [PATCH 05/38] [edge] Tests first: reload under load, refused and trial configs, admin status, share-link visits and prefix escapes (red) --- Cargo.lock | 1 + crates/edge/Cargo.toml | 1 + crates/edge/tests/common/mod.rs | 105 ++++++-- crates/edge/tests/reload.rs | 403 ++++++++++++++++++++++++++++++ crates/edge/tests/share_links.rs | 413 +++++++++++++++++++++++++++++++ tests/support/src/lib.rs | 1 + tests/support/src/more.rs | 274 ++++++++++++++++++++ 7 files changed, 1178 insertions(+), 20 deletions(-) create mode 100644 crates/edge/tests/reload.rs create mode 100644 crates/edge/tests/share_links.rs create mode 100644 tests/support/src/more.rs diff --git a/Cargo.lock b/Cargo.lock index 57d267c..cdd8120 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1044,6 +1044,7 @@ dependencies = [ "instant-acme", "log", "pingora", + "ring", "rustls", "rustls-pki-types", "serde", diff --git a/crates/edge/Cargo.toml b/crates/edge/Cargo.toml index f83f1f9..3eb54e9 100644 --- a/crates/edge/Cargo.toml +++ b/crates/edge/Cargo.toml @@ -30,6 +30,7 @@ thiserror.workspace = true [dev-dependencies] ianitor-testkit.workspace = true +ring.workspace = true [lints] workspace = true diff --git a/crates/edge/tests/common/mod.rs b/crates/edge/tests/common/mod.rs index 952dba0..2ca2b7a 100644 --- a/crates/edge/tests/common/mod.rs +++ b/crates/edge/tests/common/mod.rs @@ -4,20 +4,26 @@ //! Runs the real `ianitor-edge` binary on 127.0.0.1 with a compiled config, a test CA for //! `tls = "domi"` hosts and a credentials directory. stderr goes to a file the tests inspect. +//! Every edge also gets an admin socket and a share-link revocation file in its directory. #![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::net::SocketAddr; +use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::Arc; use std::time::Duration; use ianitor_core::compile::{self, CompileOptions}; use ianitor_core::{SourceFile, TlsMode, load}; +use ianitor_testkit::more::{JsonResp, unix_json}; use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port}; use ianitor_testkit::tls::TestCa; use rustls::RootCertStore; +/// The share-link key written as the `share-link-key` credential of every test edge. +pub const SHARE_KEY: &[u8] = b"edge-test-share-key-0123456789abcdef0123456789"; + pub struct Edge { pub child: ChildGuard, pub http: SocketAddr, @@ -25,6 +31,7 @@ pub struct Edge { pub dir: TempDir, pub ca: TestCa, pub config_text: String, + pub opts: CompileOptions, } impl Edge { @@ -53,6 +60,44 @@ impl Edge { pub fn exited(&mut self) -> Option { self.child.0.try_wait().unwrap() } + + pub fn admin_socket(&self) -> PathBuf { + self.dir.join("admin.sock") + } + + pub fn config_path(&self) -> PathBuf { + self.dir.join("edge.json") + } + + pub fn trial_path(&self) -> PathBuf { + self.dir.join("edge.json.trial") + } + + pub fn revocations_path(&self) -> PathBuf { + self.dir.join("share-revocations.json") + } + + /// Compile routes with this edge's options (same ports, same directories). + pub fn compile(&self, site: &str, hosts: &[(String, String)]) -> String { + compile_with(&self.dir, &self.ca, &self.opts, site, hosts) + } + + /// Call the admin socket. + pub async fn admin( + &self, + method: &str, + path: &str, + body: Option, + ) -> JsonResp { + unix_json(&self.admin_socket(), method, path, body.as_ref()) + .await + .unwrap_or_else(|e| panic!("admin {method} {path}: {e}\n{}", self.stderr())) + } + + pub fn write_revocations(&self, epoch: u32, deny: &[String]) { + let v = serde_json::json!({ "epoch": epoch, "deny": deny }); + std::fs::write(self.revocations_path(), v.to_string()).unwrap(); + } } pub struct EdgeSpec<'a> { @@ -78,14 +123,15 @@ impl Default for EdgeSpec<'_> { } } -/// Compile, write certificates and credentials, start the binary. Does not wait for readiness. -pub fn spawn(spec: EdgeSpec<'_>) -> Edge { - let dir = TempDir::new("edge"); - for d in ["certs", "state", "creds", "logs"] { - std::fs::create_dir_all(dir.join(d)).unwrap(); - } - let sources: Vec = spec - .hosts +/// Load and compile; write a Domi certificate for every `tls = "domi"` host that has none. +fn compile_with( + dir: &TempDir, + ca: &TestCa, + opts: &CompileOptions, + site: &str, + hosts: &[(String, String)], +) -> String { + let sources: Vec = hosts .iter() .map(|(n, c)| SourceFile { name: n, @@ -95,27 +141,38 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { let model = load( &SourceFile { name: "ianitor.toml", - contents: spec.site, + contents: site, }, &sources, ) .expect("valid routes"); - - let ca = TestCa::new("Ianitor Test CA"); for h in model.hosts() { - if h.tls == TlsMode::Domi { + let crt = dir.join(&format!("certs/{}.crt", h.hostname)); + if h.tls == TlsMode::Domi && !crt.exists() { let leaf = ca.issue(&[h.hostname.as_str()]); - std::fs::write( - dir.join(&format!("certs/{}.crt", h.hostname)), - leaf.cert_pem, - ) - .unwrap(); + std::fs::write(&crt, leaf.cert_pem).unwrap(); std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap(); } } + compile::edge(&model, opts).unwrap() +} + +/// Compile, write certificates and credentials, start the binary. Does not wait for readiness. +pub fn spawn(spec: EdgeSpec<'_>) -> Edge { + let dir = TempDir::new("edge"); + for d in ["certs", "state", "creds", "logs"] { + std::fs::create_dir_all(dir.join(d)).unwrap(); + } + let ca = TestCa::new("Ianitor Test CA"); + std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap(); for (name, value) in &spec.secrets { std::fs::write(dir.join(&format!("creds/{name}")), value).unwrap(); } + std::fs::write( + dir.join("share-revocations.json"), + "{\"epoch\": 0, \"deny\": []}", + ) + .unwrap(); let http = local(spec.http_port.unwrap_or_else(free_port)); let https = local(free_port()); @@ -128,12 +185,15 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(), caddy_admin: None, }; - let config_text = compile::edge(&model, &opts).unwrap(); + let config_text = compile_with(&dir, &ca, &opts, spec.site, &spec.hosts); std::fs::write(dir.join("edge.json"), &config_text).unwrap(); let stderr = std::fs::File::create(dir.join("edge.stderr")).unwrap(); let mut cmd = Command::new(env!("CARGO_BIN_EXE_ianitor-edge")); cmd.arg("--config").arg(dir.join("edge.json")); + cmd.arg("--admin-socket").arg(dir.join("admin.sock")); + cmd.arg("--share-revocations") + .arg(dir.join("share-revocations.json")); cmd.args(&spec.extra_args); cmd.env("CREDENTIALS_DIRECTORY", dir.join("creds")); cmd.env("IANITOR_LOG", spec.log_level); @@ -147,15 +207,20 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { dir, ca, config_text, + opts, } } -/// Spawn and wait until both listeners accept connections. +/// Spawn and wait until both listeners and the admin socket accept connections. pub fn start(spec: EdgeSpec<'_>) -> Edge { let mut e = spawn(spec); let ok = wait_for_port(e.https, Duration::from_secs(20)) && wait_for_port(e.http, Duration::from_secs(5)); - if !ok || e.exited().is_some() { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while !e.admin_socket().exists() && std::time::Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + if !ok || !e.admin_socket().exists() || e.exited().is_some() { panic!("ianitor-edge did not start:\n{}", e.stderr()); } e diff --git a/crates/edge/tests/reload.rs b/crates/edge/tests/reload.rs new file mode 100644 index 0000000..34171ee --- /dev/null +++ b/crates/edge/tests/reload.rs @@ -0,0 +1,403 @@ +// 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/. + +//! Reload (ROADMAP §8.4, tests first): edge swaps its config in process, so a reload under +//! load drops no request and no keep-alive connection; an invalid config is refused and the +//! old one keeps serving; a trial config reverts by itself unless control confirms it; the +//! admin socket reports health per host and upstream. + +#![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 (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::time::{Duration, Instant}; + + use crate::common::{Edge, EdgeSpec, host_file, start}; + use ianitor_testkit::client::{self, Req}; + use ianitor_testkit::more::KeepAlive; + use ianitor_testkit::upstream::Echo; + use serde_json::json; + + fn gen_host(echo: &Echo, generation: &str) -> Vec<(String, String)> { + vec![host_file( + "app.test", + &format!( + "upstreams = [\"{}\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-Generation\"\nvalue = \"{generation}\"\n", + echo.url() + ), + )] + } + + async fn generation(edge: &Edge) -> String { + let r = client::https(edge.https, "app.test", edge.roots(), &Req::get("app.test", "/")) + .await + .unwrap(); + assert_eq!(r.status, 200, "{}", r.text()); + r.header("x-generation").unwrap_or("none").to_owned() + } + + fn sha256(text: &str) -> String { + ring::digest::digest(&ring::digest::SHA256, text.as_bytes()) + .as_ref() + .iter() + .map(|b| format!("{b:02x}")) + .collect() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 8)] + async fn reload_under_load_drops_nothing() { + let echo = Echo::start("app").await; + let edge = start(EdgeSpec { + hosts: gen_host(&echo, "a"), + log_level: "warn", + ..Default::default() + }); + let config_a = edge.config_text.clone(); + let config_b = edge.compile("", &gen_host(&echo, "b")); + + let clients: usize = std::env::var("IANITOR_RELOAD_CLIENTS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(32); + let secs: u64 = std::env::var("IANITOR_RELOAD_SECS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(10); + + let stop = Arc::new(AtomicBool::new(false)); + let ok = Arc::new(AtomicU64::new(0)); + let errors = Arc::new(AtomicU64::new(0)); + let resets = Arc::new(AtomicU64::new(0)); + let mut tasks = Vec::new(); + for _ in 0..clients { + let (stop, ok, errors, resets) = + (stop.clone(), ok.clone(), errors.clone(), resets.clone()); + let (addr, roots) = (edge.https, edge.roots()); + tasks.push(tokio::spawn(async move { + let mut conn = KeepAlive::connect(addr, "app.test", roots).await.unwrap(); + let mut seen = std::collections::BTreeSet::new(); + let mut latencies = Vec::new(); + while !stop.load(Ordering::Relaxed) { + let t = Instant::now(); + match conn.send(&Req::get("app.test", "/load")).await { + Ok(r) if r.status == 200 => { + ok.fetch_add(1, Ordering::Relaxed); + seen.insert(r.header("x-generation").unwrap_or("none").to_owned()); + latencies.push(t.elapsed()); + } + Ok(_) => { + errors.fetch_add(1, Ordering::Relaxed); + } + Err(_) => { + // The keep-alive connection is gone. + resets.fetch_add(1, Ordering::Relaxed); + break; + } + } + } + (seen, latencies) + })); + } + + let started = Instant::now(); + let mut reloads = 0u64; + let mut refused = 0u64; + while started.elapsed() < Duration::from_secs(secs) { + let text = if reloads % 2 == 0 { &config_b } else { &config_a }; + let tmp = edge.config_path().with_extension("tmp"); + std::fs::write(&tmp, text).unwrap(); + std::fs::rename(&tmp, edge.config_path()).unwrap(); + let r = edge.admin("POST", "/v1/reload", None).await; + if r.status == 200 { + reloads += 1; + } else { + refused += 1; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + stop.store(true, Ordering::Relaxed); + let mut all_latencies = Vec::new(); + let mut both = 0; + for t in tasks { + let (seen, lat) = t.await.unwrap(); + if seen.contains("a") && seen.contains("b") { + both += 1; + } + all_latencies.extend(lat); + } + all_latencies.sort(); + let pct = |p: f64| { + all_latencies + .get(((all_latencies.len() as f64 - 1.0) * p) as usize) + .copied() + .unwrap_or_default() + }; + println!( + "RELOAD UNDER LOAD: {clients} keep-alive clients, {secs} s, {reloads} reloads ({refused} refused), \ + {} requests ok, {} errors, {} connection resets, {both}/{clients} connections saw both configs, \ + latency p50 {:?} p99 {:?} max {:?}", + ok.load(Ordering::Relaxed), + errors.load(Ordering::Relaxed), + resets.load(Ordering::Relaxed), + pct(0.5), + pct(0.99), + pct(1.0), + ); + assert_eq!(refused, 0, "{}", edge.stderr()); + assert!(reloads >= secs * 5, "only {reloads} reloads"); + assert_eq!(errors.load(Ordering::Relaxed), 0); + assert_eq!(resets.load(Ordering::Relaxed), 0); + assert!(ok.load(Ordering::Relaxed) > 1000); + assert_eq!( + both, clients, + "every keep-alive connection must pick up new configs" + ); + } + + #[tokio::test(flavor = "multi_thread")] + async fn an_invalid_config_is_refused_and_the_old_one_keeps_serving() { + let echo = Echo::start("app").await; + let edge = start(EdgeSpec { + hosts: gen_host(&echo, "a"), + ..Default::default() + }); + let before = edge.admin("GET", "/v1/status", None).await; + assert_eq!(before.status, 200, "{}", before.text); + let sha = before.json["config_sha256"].as_str().unwrap().to_owned(); + assert_eq!(sha, sha256(&edge.config_text)); + + let good_b = edge.compile("", &gen_host(&echo, "b")); + let mut broken_cert: serde_json::Value = serde_json::from_str(&good_b).unwrap(); + broken_cert["hosts"][0]["tls"]["cert"] = json!("/nonexistent/app.test.crt"); + let mut moved: serde_json::Value = serde_json::from_str(&good_b).unwrap(); + moved["https_listen"] = json!("127.0.0.1:1"); + let mut old_version: serde_json::Value = serde_json::from_str(&good_b).unwrap(); + old_version["version"] = json!(1); + let mut share_without_key: serde_json::Value = serde_json::from_str(&good_b).unwrap(); + share_without_key["hosts"][0]["share_links"] = json!(true); + std::fs::remove_file(edge.dir.join("creds/share-link-key")).unwrap(); + + for (what, text) in [ + ("not JSON", "{ not json".to_owned()), + ("unknown field", good_b.replace("\"hosts\"", "\"hostz\"")), + ("missing certificate", broken_cert.to_string()), + ("listen address change", moved.to_string()), + ("old version", old_version.to_string()), + ("share links without key", share_without_key.to_string()), + ] { + std::fs::write(edge.config_path(), &text).unwrap(); + let r = edge.admin("POST", "/v1/reload", None).await; + assert_eq!(r.status, 422, "{what}: {}", r.text); + assert!( + r.json["error"].as_str().is_some_and(|e| !e.is_empty()), + "{what}: {}", + r.text + ); + assert_eq!(generation(&edge).await, "a", "{what}"); + let s = edge.admin("GET", "/v1/status", None).await; + assert_eq!(s.json["config_sha256"], sha, "{what}"); + } + // A missing file is refused too. + std::fs::remove_file(edge.config_path()).unwrap(); + assert_eq!(edge.admin("POST", "/v1/reload", None).await.status, 422); + assert_eq!(generation(&edge).await, "a"); + + // And a good one is taken. + std::fs::write(edge.config_path(), &good_b).unwrap(); + let r = edge.admin("POST", "/v1/reload", None).await; + assert_eq!(r.status, 200, "{}", r.text); + assert_eq!(r.json["config_sha256"], sha256(&good_b)); + assert_eq!(generation(&edge).await, "b"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_trial_reverts_by_itself_unless_confirmed() { + let echo = Echo::start("app").await; + let edge = start(EdgeSpec { + hosts: gen_host(&echo, "a"), + ..Default::default() + }); + let config_b = edge.compile("", &gen_host(&echo, "b")); + std::fs::write(edge.trial_path(), &config_b).unwrap(); + + // Not confirmed: back to "a" after the deadline, without anyone asking. + let r = edge + .admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2 }))) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let trial_sha = r.json["config_sha256"].as_str().unwrap().to_owned(); + assert_eq!(trial_sha, sha256(&config_b)); + assert_eq!(generation(&edge).await, "b"); + let s = edge.admin("GET", "/v1/status", None).await; + assert_eq!(s.json["trial"]["config_sha256"], trial_sha); + // No reload and no second trial while one runs. + assert_eq!(edge.admin("POST", "/v1/reload", None).await.status, 409); + assert_eq!( + edge.admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2 }))) + .await + .status, + 409 + ); + tokio::time::sleep(Duration::from_millis(3500)).await; + assert_eq!(generation(&edge).await, "a"); + let s = edge.admin("GET", "/v1/status", None).await; + assert!(s.json["trial"].is_null(), "{}", s.text); + assert_eq!(s.json["config_sha256"], sha256(&edge.config_text)); + // Confirming a trial that already reverted fails. + let r = edge + .admin("POST", "/v1/confirm", Some(json!({ "config_sha256": trial_sha }))) + .await; + assert_eq!(r.status, 409, "{}", r.text); + + // Confirmed: stays. + let r = edge + .admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2 }))) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let wrong = edge + .admin("POST", "/v1/confirm", Some(json!({ "config_sha256": "00" }))) + .await; + assert_eq!(wrong.status, 409); + let r = edge + .admin("POST", "/v1/confirm", Some(json!({ "config_sha256": trial_sha }))) + .await; + assert_eq!(r.status, 200, "{}", r.text); + tokio::time::sleep(Duration::from_millis(2500)).await; + assert_eq!(generation(&edge).await, "b"); + + // Aborted: back at once. Abort is idempotent. + std::fs::write(edge.trial_path(), &edge.config_text).unwrap(); + let r = edge + .admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 30 }))) + .await; + assert_eq!(r.status, 200, "{}", r.text); + assert_eq!(generation(&edge).await, "a"); + let r = edge.admin("POST", "/v1/abort", None).await; + assert_eq!(r.status, 200); + assert_eq!(r.json["reverted"], true); + assert_eq!(generation(&edge).await, "b"); + let r = edge.admin("POST", "/v1/abort", None).await; + assert_eq!(r.status, 200); + assert_eq!(r.json["reverted"], false); + + // A broken trial is refused and nothing changes. + std::fs::write(edge.trial_path(), "{}").unwrap(); + let r = edge + .admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 30 }))) + .await; + assert_eq!(r.status, 422); + assert_eq!(generation(&edge).await, "b"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn status_reports_health_per_host_and_upstream() { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(503, Ordering::SeqCst); + let closed = ianitor_testkit::upstream::closed_port(); + let plain = Echo::start("plain").await; + let edge = start(EdgeSpec { + hosts: vec![ + host_file( + "mixed.test", + &format!( + "upstreams = [\"{}\", \"{}\", \"http://127.0.0.1:{closed}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n", + good.url(), + sick.url() + ), + ), + host_file("plain.test", &format!("upstreams = [\"{}\"]\n", plain.url())), + ], + ..Default::default() + }); + tokio::time::sleep(Duration::from_millis(2500)).await; + let s = edge.admin("GET", "/v1/status", None).await; + assert_eq!(s.status, 200, "{}", s.text); + let hosts = s.json["hosts"].as_array().unwrap(); + let mixed = hosts.iter().find(|h| h["hostname"] == "mixed.test").unwrap(); + assert_eq!(mixed["health_check"], true); + let ups = mixed["upstreams"].as_array().unwrap(); + assert_eq!(ups.len(), 3); + assert_eq!(ups[0]["healthy"], true, "{}", s.text); + assert_eq!(ups[1]["healthy"], false); + assert_eq!(ups[2]["healthy"], false); + let last = |u: &serde_json::Value| u["checks"].as_array().unwrap().last().unwrap().clone(); + assert_eq!(last(&ups[0])["ok"], true); + assert!(last(&ups[0])["latency_ms"].is_u64()); + assert_eq!(last(&ups[1])["kind"], "server_error"); + assert_eq!(last(&ups[1])["status"], 503); + assert_eq!(last(&ups[2])["kind"], "refused"); + assert!(ups[0]["checks"].as_array().unwrap().len() <= 5); + assert!(mixed["certificate"]["state"] == "ok"); + let plain_h = hosts.iter().find(|h| h["hostname"] == "plain.test").unwrap(); + assert_eq!(plain_h["health_check"], false); + assert!(plain_h["upstreams"][0]["checks"].as_array().unwrap().is_empty()); + + // During a trial, watched hosts without a health check get `GET /` probes; any answer + // below 500 counts as alive. Hosts with one are checked at least every `every_secs`. + std::fs::write(edge.trial_path(), &edge.config_text).unwrap(); + let r = edge + .admin( + "POST", + "/v1/trial", + Some(json!({ "confirm_within_secs": 30, "watch_hosts": ["plain.test"], "watch_every_secs": 1 })), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + tokio::time::sleep(Duration::from_millis(2500)).await; + let s = edge.admin("GET", "/v1/status", None).await; + let plain_h = s.json["hosts"] + .as_array() + .unwrap() + .iter() + .find(|h| h["hostname"] == "plain.test") + .unwrap() + .clone(); + let checks = plain_h["upstreams"][0]["checks"].as_array().unwrap(); + assert!(!checks.is_empty(), "{}", s.text); + assert_eq!(checks.last().unwrap()["ok"], true); + assert_eq!(checks.last().unwrap()["source"], "watch"); + assert!(plain.requests().iter().any(|r| r.path == "/" + && r.header("host") == Some(b"plain.test".as_slice()))); + edge.admin("POST", "/v1/abort", None).await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn the_admin_socket_is_private() { + use std::os::unix::fs::{FileTypeExt, PermissionsExt}; + let echo = Echo::start("app").await; + let edge = start(EdgeSpec { + hosts: gen_host(&echo, "a"), + ..Default::default() + }); + let meta = std::fs::metadata(edge.admin_socket()).unwrap(); + assert!(meta.file_type().is_socket()); + assert_eq!(meta.permissions().mode() & 0o007, 0, "no access for others"); + // Unknown paths and bad bodies get typed errors, not a crash. + assert_eq!(edge.admin("GET", "/v1/nope", None).await.status, 404); + let r = edge + .admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 2, "extra": 1 }))) + .await; + assert_eq!(r.status, 400, "{}", r.text); + let r = edge + .admin("POST", "/v1/trial", Some(json!({ "confirm_within_secs": 0 }))) + .await; + assert_eq!(r.status, 400, "{}", r.text); + assert_eq!(generation(&edge).await, "a"); + } +} diff --git a/crates/edge/tests/share_links.rs b/crates/edge/tests/share_links.rs new file mode 100644 index 0000000..8fe5711 --- /dev/null +++ b/crates/edge/tests/share_links.rs @@ -0,0 +1,413 @@ +// 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/. + +//! Share links in edge (ROADMAP §6 phase 2, tests first): a valid link lets the visitor in on +//! its host and prefix only, without forward-auth; the token travels in the URL once and is +//! then a path-scoped cookie; it never reaches the upstream or a log; expired, altered, +//! wrong-host, wrong-path, stopped and password-less tokens are refused; wrong passwords are +//! throttled; no path trick escapes the prefix. + +#![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 (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + use crate::common::{Edge, EdgeSpec, SHARE_KEY, host_file, start}; + use ianitor_core::share::{LinkSpec, ShareId, ShareKey, mint}; + use ianitor_testkit::authelia::MockAuthelia; + use ianitor_testkit::client::{self, Req, Resp}; + use ianitor_testkit::more::https_raw; + use ianitor_testkit::upstream::Echo; + + const HOST: &str = "share.test"; + + fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() + } + + fn key() -> ShareKey { + ShareKey::new(SHARE_KEY).unwrap() + } + + fn link(host: &str, id: u8, prefix: &str, expires_at: u64, password: Option<&str>) -> String { + mint( + &key(), + host, + &LinkSpec { + id: ShareId([id; 16]), + epoch: 0, + expires_at, + prefix, + password, + }, + ) + .unwrap() + } + + struct Env { + edge: Edge, + echo: Echo, + auth: MockAuthelia, + } + + async fn env() -> Env { + let auth = MockAuthelia::start().await; + let echo = Echo::start("app").await; + let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url()); + let edge = start(EdgeSpec { + site: &site, + hosts: vec![ + host_file( + HOST, + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = true\naccess_log = \"truncated\"\n", + echo.url() + ), + ), + host_file( + "closed.test", + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = false\n", + echo.url() + ), + ), + ], + log_level: "debug", + ..Default::default() + }); + Env { edge, echo, auth } + } + + impl Env { + async fn get(&self, host: &str, path: &str, cookie: Option<&str>) -> Resp { + let mut req = Req::get(host, path); + if let Some(c) = cookie { + req = req.header("cookie", c); + } + client::https(self.edge.https, host, self.edge.roots(), &req) + .await + .unwrap() + } + + async fn post_password(&self, token: &str, password: &str) -> Resp { + let body = format!( + "t={}&password={}", + urlencode(token), + urlencode(password) + ); + let req = Req::new("POST", HOST, "/.well-known/ianitor/share") + .header("content-type", "application/x-www-form-urlencoded") + .body(body.as_bytes()); + client::https(self.edge.https, HOST, self.edge.roots(), &req) + .await + .unwrap() + } + + /// Requests the upstream saw (health checks excluded). + fn upstream_paths(&self) -> Vec { + self.echo.proxied().iter().map(|r| r.path.clone()).collect() + } + } + + fn urlencode(s: &str) -> String { + s.bytes() + .map(|b| { + if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { + (b as char).to_string() + } else { + format!("%{b:02X}") + } + }) + .collect() + } + + /// The `name=value` part of the share cookie a response sets. + fn share_cookie(r: &Resp) -> String { + let sc = r + .header_all("set-cookie") + .into_iter() + .find(|c| c.starts_with("__Secure-ianitor-share=")) + .unwrap_or_else(|| panic!("no share cookie in {:?}", r.headers)); + sc.split(';').next().unwrap().to_owned() + } + + fn assert_visitor_page(r: &Resp, status: u16, heading: &str) { + assert_eq!(r.status, status, "{}", r.text()); + assert!(r.text().contains(heading), "{heading}: {}", r.text()); + assert_eq!(r.header("cache-control"), Some("no-store")); + assert_eq!(r.header("referrer-policy"), Some("no-referrer")); + assert!( + r.header("content-security-policy") + .is_some_and(|c| c.contains("default-src 'none'")) + ); + assert!(r.header("content-type").unwrap().starts_with("text/html")); + assert!(!r.text().contains("")); + assert!(e.upstream_paths().is_empty()); + + // A `share` parameter that is not ours is left alone (goes to the normal sign-in). + let r = e.get(HOST, "/?share=holiday", None).await; + assert_eq!(r.status, 302, "forward-auth portal redirect"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_link_outside_its_prefix_falls_back_to_sign_in_and_never_leaks() { + let e = env().await; + let t = link(HOST, 6, "/albums", now() + 3600, None); + let r = e.get(HOST, &format!("/private?share={t}"), None).await; + assert_eq!(r.status, 302, "normal sign-in: {}", r.text()); + // Signed in, the request goes through, but the token is not passed on. + let r = e + .get( + HOST, + &format!("/private?a=1&share={t}"), + Some("authelia_session=good"), + ) + .await; + assert_eq!(r.status, 200); + let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap(); + assert_eq!(body["query"], "a=1", "token stripped before the upstream"); + + // On a host without share links the token gives nothing. + let t2 = link("closed.test", 7, "/", now() + 3600, None); + let r = e.get("closed.test", &format!("/?share={t2}"), None).await; + assert_eq!(r.status, 302); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_password_link_asks_checks_and_throttles() { + let e = env().await; + let t = link(HOST, 8, "/docs", now() + 3600, Some("correct horse")); + + let r = e.get(HOST, &format!("/docs/a?share={t}"), None).await; + assert_visitor_page(&r, 401, "This link is protected"); + assert!(r.text().contains("share.test")); + assert!(r.text().contains("action=\"/.well-known/ianitor/share\"")); + assert!(r.text().contains("name=\"password\"")); + assert!(r.text().contains("The link works until")); + assert!(share_cookie_absent(&r)); + + let r = e.post_password(&t, "wrong password").await; + assert_visitor_page(&r, 401, "That password is not right"); + assert!(share_cookie_absent(&r)); + + let r = e.post_password(&t, "correct horse").await; + assert_eq!(r.status, 303, "{}", r.text()); + assert_eq!(r.header("location"), Some("/docs")); + let cookie = share_cookie(&r); + assert_eq!(e.get(HOST, "/docs/a", Some(&cookie)).await.status, 200); + + // The cookie of a password link cannot be turned into a link that skips the password. + let v = cookie.split_once('=').unwrap().1.to_owned(); + let r = e + .get(HOST, &format!("/docs?share={}", v.replacen("iss1.", "ish1.", 1)), None) + .await; + assert_ne!(r.status, 303); + + // Five wrong tries a minute, then a pause (the right password too). + let t2 = link(HOST, 9, "/docs", now() + 3600, Some("correct horse")); + for _ in 0..5 { + assert_eq!(e.post_password(&t2, "nope nope").await.status, 401); + } + let r = e.post_password(&t2, "nope nope").await; + assert_visitor_page(&r, 429, "Too many tries"); + let r = e.post_password(&t2, "correct horse").await; + assert_eq!(r.status, 429); + // Other links are not affected. + let t3 = link(HOST, 10, "/docs", now() + 3600, Some("correct horse")); + assert_eq!(e.post_password(&t3, "correct horse").await.status, 303); + // The password never reaches a log. + assert!(!e.edge.all_output().contains("correct horse")); + } + + fn share_cookie_absent(r: &Resp) -> bool { + !r.header_all("set-cookie") + .iter() + .any(|c| c.starts_with("__Secure-ianitor-share=")) + } + + #[tokio::test(flavor = "multi_thread")] + async fn no_path_trick_escapes_the_cookie_prefix() { + let e = env().await; + let t = link(HOST, 11, "/a", now() + 3600, None); + let r = e.get(HOST, &format!("/a?share={t}"), None).await; + let cookie = share_cookie(&r); + let before = e.upstream_paths().len(); + for path in [ + "/ab", + "/A", + "/A/x", + "/b", + "/a/../b", + "/a/%2e%2e/b", + "/a/%2E%2E/b", + "/a/%252e%252e/b", + "/a%2f..%2fb", + "/a//b", + "//a/b", + "/a/..;/b", + "/a/\\..\\b", + "/a\\..\\b", + ] { + let raw = format!( + "GET {path} HTTP/1.1\r\nHost: {HOST}\r\nCookie: {cookie}\r\nConnection: close\r\n\r\n" + ); + let r = https_raw(e.edge.https, HOST, e.edge.roots(), raw.as_bytes()) + .await + .unwrap(); + assert_ne!(r.status, 200, "{path} got through: {}", r.text()); + } + assert_eq!( + e.upstream_paths().len(), + before, + "no escaped request reached the upstream: {:?}", + e.upstream_paths() + ); + } + + #[tokio::test(flavor = "multi_thread")] + async fn stopped_links_and_stop_all_take_effect_at_once() { + let e = env().await; + let t = link(HOST, 12, "/", now() + 3600, None); + let keep = link(HOST, 13, "/", now() + 3600, None); + let cookie = share_cookie(&e.get(HOST, &format!("/?share={t}"), None).await); + let keep_cookie = share_cookie(&e.get(HOST, &format!("/?share={keep}"), None).await); + assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200); + + e.edge.write_revocations(0, &[ShareId([12; 16]).to_hex()]); + let r = e.edge.admin("POST", "/v1/share-revocations/reload", None).await; + assert_eq!(r.status, 200, "{}", r.text); + assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 302, "back to sign-in"); + let r = e.get(HOST, &format!("/?share={t}"), None).await; + assert_visitor_page(&r, 403, "This link no longer works"); + assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200); + + // Stop all: a new epoch ends every older link. + e.edge.write_revocations(1, &[]); + e.edge.admin("POST", "/v1/share-revocations/reload", None).await; + assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302); + + // Without the admin call, edge notices a changed file within 5 s. + e.edge.write_revocations(0, &[]); + tokio::time::sleep(Duration::from_secs(6)).await; + assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200); + + // A broken file keeps the last good state; a missing one stops all share access. + std::fs::write(e.edge.revocations_path(), "{ broken").unwrap(); + let r = e.edge.admin("POST", "/v1/share-revocations/reload", None).await; + assert_eq!(r.status, 422); + assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200); + std::fs::remove_file(e.edge.revocations_path()).unwrap(); + e.edge.admin("POST", "/v1/share-revocations/reload", None).await; + assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302); + } +} diff --git a/tests/support/src/lib.rs b/tests/support/src/lib.rs index 6035ef3..35ad953 100644 --- a/tests/support/src/lib.rs +++ b/tests/support/src/lib.rs @@ -9,6 +9,7 @@ pub mod authelia; pub mod client; +pub mod more; pub mod proc; pub mod raw; pub mod tls; diff --git a/tests/support/src/more.rs b/tests/support/src/more.rs new file mode 100644 index 0000000..19af3d4 --- /dev/null +++ b/tests/support/src/more.rs @@ -0,0 +1,274 @@ +// 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/. + +//! Clients the phase 2 tests need: raw request bytes over TLS (for paths a URI type refuses, +//! like backslashes), a keep-alive HTTP/1.1 connection that is reused across requests, and +//! JSON over a Unix socket (edge's admin socket) or loopback TCP (the control API). + +use std::io; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper_util::rt::TokioIo; +use rustls::RootCertStore; +use rustls_pki_types::ServerName; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; + +use crate::client::{Req, Resp, tls_connector}; + +const TIMEOUT: Duration = Duration::from_secs(15); + +fn other(e: impl std::fmt::Display) -> io::Error { + io::Error::other(e.to_string()) +} + +/// Parse a complete HTTP/1.1 response (Content-Length, chunked or read-to-close). +pub fn parse_response(raw: &[u8]) -> io::Result { + let end = raw + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or_else(|| other("no complete response head"))?; + let head = String::from_utf8_lossy(&raw[..end]).into_owned(); + let mut lines = head.split("\r\n"); + let status_line = lines.next().unwrap_or_default(); + let status: u16 = status_line + .split(' ') + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or_else(|| other(format!("bad status line {status_line:?}")))?; + let headers: Vec<(String, String)> = lines + .filter_map(|l| l.split_once(':')) + .map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().to_owned())) + .collect(); + let mut body = raw[end + 4..].to_vec(); + if headers + .iter() + .any(|(n, v)| n == "transfer-encoding" && v.eq_ignore_ascii_case("chunked")) + { + let mut out = Vec::new(); + let mut rest = &body[..]; + loop { + let Some(p) = rest.windows(2).position(|w| w == b"\r\n") else { + break; + }; + let size = usize::from_str_radix( + String::from_utf8_lossy(&rest[..p]).split(';').next().unwrap_or("0").trim(), + 16, + ) + .map_err(other)?; + rest = &rest[p + 2..]; + if size == 0 || rest.len() < size { + break; + } + out.extend_from_slice(&rest[..size]); + rest = &rest[(size + 2).min(rest.len())..]; + } + body = out; + } else if let Some(len) = headers + .iter() + .find(|(n, _)| n == "content-length") + .and_then(|(_, v)| v.parse::().ok()) + { + body.truncate(len); + } + Ok(Resp { + status, + headers, + body, + }) +} + +/// Send `request` (complete raw bytes, which should ask for `Connection: close`) over a fresh +/// TLS connection and read until the server closes. +pub async fn https_raw( + addr: SocketAddr, + sni: &str, + roots: Arc, + request: &[u8], +) -> io::Result { + tokio::time::timeout(TIMEOUT, async { + let tcp = TcpStream::connect(addr).await?; + let name = ServerName::try_from(sni.to_owned()).map_err(other)?; + let mut s = tls_connector(roots).connect(name, tcp).await?; + s.write_all(request).await?; + let mut buf = Vec::new(); + // A close_notify-less close is fine here. + let _ = s.read_to_end(&mut buf).await; + parse_response(&buf) + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? +} + +/// One HTTP/1.1 connection over TLS, reused for every request until it fails. +pub struct KeepAlive { + sender: hyper::client::conn::http1::SendRequest>, +} + +impl KeepAlive { + pub async fn connect( + addr: SocketAddr, + sni: &str, + roots: Arc, + ) -> io::Result { + let tcp = TcpStream::connect(addr).await?; + tcp.set_nodelay(true)?; + let name = ServerName::try_from(sni.to_owned()).map_err(other)?; + let s = tls_connector(roots).connect(name, tcp).await?; + let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(s)) + .await + .map_err(other)?; + tokio::spawn(async move { + let _ = conn.await; + }); + Ok(KeepAlive { sender }) + } + + /// Send one request on this connection. An `Err` means the connection is gone. + pub async fn send(&mut self, req: &Req) -> io::Result { + self.sender.ready().await.map_err(other)?; + let mut b = hyper::Request::builder() + .method(req.method.as_str()) + .uri(req.path.as_str()); + for (n, v) in &req.headers { + b = b.header(n.as_str(), v.as_str()); + } + let request = b + .body(Full::new(Bytes::from(req.body.clone()))) + .map_err(other)?; + let resp = tokio::time::timeout(TIMEOUT, self.sender.send_request(request)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? + .map_err(other)?; + let status = resp.status().as_u16(); + let headers = resp + .headers() + .iter() + .map(|(n, v)| { + ( + n.as_str().to_owned(), + String::from_utf8_lossy(v.as_bytes()).into_owned(), + ) + }) + .collect(); + let body = resp + .into_body() + .collect() + .await + .map_err(other)? + .to_bytes() + .to_vec(); + Ok(Resp { + status, + headers, + body, + }) + } +} + +/// A JSON answer: status and parsed body (`Null` when the body is empty or not JSON). +#[derive(Debug, Clone)] +pub struct JsonResp { + pub status: u16, + pub headers: Vec<(String, String)>, + pub json: serde_json::Value, + pub text: String, +} + +impl JsonResp { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } +} + +fn json_resp(r: Resp) -> JsonResp { + let text = String::from_utf8_lossy(&r.body).into_owned(); + JsonResp { + status: r.status, + headers: r.headers, + json: serde_json::from_str(&text).unwrap_or(serde_json::Value::Null), + text, + } +} + +fn raw_request( + method: &str, + path: &str, + host: &str, + headers: &[(&str, &str)], + body: Option<&serde_json::Value>, +) -> Vec { + let body = body.map(|b| b.to_string()).unwrap_or_default(); + let mut out = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n"); + for (n, v) in headers { + out.push_str(&format!("{n}: {v}\r\n")); + } + if !body.is_empty() || method != "GET" { + out.push_str("Content-Type: application/json\r\n"); + out.push_str(&format!("Content-Length: {}\r\n", body.len())); + } + out.push_str("\r\n"); + out.push_str(&body); + out.into_bytes() +} + +/// A request over a Unix socket (edge's admin socket). +#[cfg(unix)] +pub async fn unix_json( + socket: &std::path::Path, + method: &str, + path: &str, + body: Option<&serde_json::Value>, +) -> io::Result { + tokio::time::timeout(TIMEOUT, async { + let mut s = tokio::net::UnixStream::connect(socket).await?; + s.write_all(&raw_request(method, path, "localhost", &[], body)) + .await?; + let mut buf = Vec::new(); + s.read_to_end(&mut buf).await?; + parse_response(&buf).map(json_resp) + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? +} + +/// A request over plain TCP (the control API on loopback), with extra headers. +pub async fn tcp_json( + addr: SocketAddr, + method: &str, + path: &str, + headers: &[(&str, &str)], + body: Option<&serde_json::Value>, +) -> io::Result { + tokio::time::timeout(Duration::from_secs(120), async { + let mut s = TcpStream::connect(addr).await?; + s.write_all(&raw_request(method, path, &addr.to_string(), headers, body)) + .await?; + let mut buf = Vec::new(); + s.read_to_end(&mut buf).await?; + parse_response(&buf).map(json_resp) + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? +} + +/// Send raw bytes over plain TCP and parse the answer (for malformed requests). +pub async fn tcp_raw(addr: SocketAddr, request: &[u8]) -> io::Result { + tokio::time::timeout(TIMEOUT, async { + let mut s = TcpStream::connect(addr).await?; + s.write_all(request).await?; + let mut buf = Vec::new(); + s.read_to_end(&mut buf).await?; + parse_response(&buf) + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? +} From 6ce1fe9d2bc9ac8a653058710c172f5839c5a100 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 17:49:53 +0100 Subject: [PATCH 06/38] [edge] Reload and share links: in-process config swap with self-reverting trials, admin socket with health and certificate status, share-link cookies, visitor pages and throttle --- Cargo.lock | 4 + crates/edge/Cargo.toml | 5 + crates/edge/src/acme.rs | 120 ++++++--- crates/edge/src/admin.rs | 326 +++++++++++++++++++++++ crates/edge/src/health.rs | 237 +++++++++++++---- crates/edge/src/http_app.rs | 11 +- crates/edge/src/lib.rs | 95 +++++-- crates/edge/src/main.rs | 15 +- crates/edge/src/pages.rs | 211 +++++++++++++++ crates/edge/src/proxy.rs | 56 +++- crates/edge/src/runtime.rs | 181 +++++++++++-- crates/edge/src/share.rs | 428 +++++++++++++++++++++++++++++++ crates/edge/src/shared.rs | 403 +++++++++++++++++++++++++++++ crates/edge/src/tls.rs | 15 +- crates/edge/tests/reload.rs | 111 ++++++-- crates/edge/tests/share_links.rs | 86 +++++-- tests/diff/src/lib.rs | 8 +- tests/support/src/more.rs | 11 +- 18 files changed, 2137 insertions(+), 186 deletions(-) create mode 100644 crates/edge/src/admin.rs create mode 100644 crates/edge/src/pages.rs create mode 100644 crates/edge/src/share.rs create mode 100644 crates/edge/src/shared.rs diff --git a/Cargo.lock b/Cargo.lock index cdd8120..baa1c57 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1038,7 +1038,11 @@ dependencies = [ "arc-swap", "async-trait", "bytes", + "form_urlencoded", "http", + "http-body-util", + "hyper", + "hyper-util", "ianitor-core", "ianitor-testkit", "instant-acme", diff --git a/crates/edge/Cargo.toml b/crates/edge/Cargo.toml index 3eb54e9..2b7e192 100644 --- a/crates/edge/Cargo.toml +++ b/crates/edge/Cargo.toml @@ -27,6 +27,11 @@ arc-swap = "1.7" instant-acme = { version = "0.8.5", default-features = false, features = ["ring", "hyper-rustls", "rcgen"] } x509-parser = "0.18" thiserror.workspace = true +ring.workspace = true +hyper.workspace = true +hyper-util.workspace = true +http-body-util.workspace = true +form_urlencoded = "1.2" [dev-dependencies] ianitor-testkit.workspace = true diff --git a/crates/edge/src/acme.rs b/crates/edge/src/acme.rs index 1febc10..580b9c4 100644 --- a/crates/edge/src/acme.rs +++ b/crates/edge/src/acme.rs @@ -21,13 +21,14 @@ use pingora::server::ShutdownWatch; use pingora::services::background::BackgroundService; use crate::logging::now_secs; -use crate::runtime::Runtime; -use crate::tls::{CertStore, certified_key, not_after}; +use crate::shared::{CertState, Shared}; +use crate::tls::{certified_key, not_after}; const RENEW_BEFORE_SECS: f64 = 30.0 * 86_400.0; const CHECK_EVERY: Duration = Duration::from_secs(12 * 3600); const FIRST_RETRY: Duration = Duration::from_secs(30); const MAX_RETRY: Duration = Duration::from_secs(3600); +const MIN_GAP: Duration = Duration::from_secs(5); /// HTTP-01 tokens → key authorizations, shared with the HTTP listener. #[derive(Default)] @@ -52,8 +53,7 @@ impl Challenges { } pub struct AcmeService { - pub rt: Arc, - pub certs: Arc, + pub shared: Arc, pub challenges: Arc, /// Extra trust root for the ACME directory (tests against Pebble only). pub ca_root: Option, @@ -84,7 +84,7 @@ fn fnv(data: &[u8]) -> String { impl AcmeService { fn dir(&self) -> PathBuf { - self.rt.acme_dir() + self.shared.current().acme_dir() } fn paths(&self, host: &str) -> (PathBuf, PathBuf) { @@ -102,7 +102,8 @@ impl AcmeService { let expiry = not_after(&cert_pem)?; match certified_key(&cert_pem, &key_pem) { Ok(ck) => { - self.certs.insert(host, ck); + self.shared.certs.insert(host, ck); + self.ok(host, expiry); Some(expiry) } Err(e) => { @@ -207,18 +208,30 @@ impl AcmeService { let (crt, key) = self.paths(host); write_private(&key, key_pem.as_bytes())?; write_private(&crt, chain_pem.as_bytes())?; - self.certs.insert(host, ck); + self.shared.certs.insert(host, ck); + self.ok(host, expiry); log::info!(target: "ianitor::acme", "{host}: certificate issued, valid until {expiry}"); Ok(expiry) } /// One pass over every ACME host. Returns false if any host failed. + fn ok(&self, host: &str, expiry: i64) { + self.shared.set_cert_state( + host, + CertState { + state: "ok", + not_after: Some(expiry), + error: None, + }, + ); + } + async fn round(&self, expiries: &mut HashMap) -> bool { - let Some(acme) = &self.rt.cfg.acme else { + let rt = self.shared.current(); + let Some(acme) = &rt.cfg.acme else { return true; }; - let due: Vec = self - .rt + let due: Vec = rt .acme_hosts() .into_iter() .filter(|h| { @@ -230,10 +243,25 @@ impl AcmeService { if due.is_empty() { return true; } + for h in &due { + if !expiries.contains_key(h) { + self.shared.set_cert_state( + h, + CertState { + state: "pending", + not_after: None, + error: None, + }, + ); + } + } let account = match self.account(&acme.directory, acme.email.as_deref()).await { Ok(a) => a, Err(e) => { log::error!(target: "ianitor::acme", "{e}"); + for h in &due { + self.failed(h, expiries.get(h).copied(), &e); + } return false; } }; @@ -245,43 +273,73 @@ impl AcmeService { } Err(e) => { log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}"); + self.failed(&host, expiries.get(&host).copied(), &e); ok = false; } } } ok } + + /// A host that still has a valid certificate stays `ok` while renewal retries. + fn failed(&self, host: &str, expiry: Option, error: &str) { + let still_valid = expiry.is_some_and(|e| (e as f64) > now_secs()); + self.shared.set_cert_state( + host, + CertState { + state: if still_valid { "ok" } else { "failed" }, + not_after: expiry, + error: Some(error.chars().take(300).collect()), + }, + ); + } } #[async_trait] impl BackgroundService for AcmeService { async fn start(&self, mut shutdown: ShutdownWatch) { - if self.rt.acme_hosts().is_empty() { - return; - } - let dir = self.dir(); - if let Err(e) = std::fs::create_dir_all(&dir) { - log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display()); - return; - } let mut expiries = HashMap::new(); - for h in self.rt.acme_hosts() { - if let Some(e) = self.load_stored(&h) { - expiries.insert(h, e); - } - } let mut retry = FIRST_RETRY; + let mut last: Option = None; loop { - let wait = if self.round(&mut expiries).await { - retry = FIRST_RETRY; - CHECK_EVERY - } else { - let w = retry; - retry = (retry * 2).min(MAX_RETRY); - w - }; + // Reloads can come many times a second; ACME rounds at most every 5 s. + if let Some(l) = last + && l.elapsed() < MIN_GAP + { + tokio::select! { + _ = tokio::time::sleep(MIN_GAP - l.elapsed()) => {} + _ = shutdown.changed() => return, + } + } + last = Some(std::time::Instant::now()); + let hosts = self.shared.current().acme_hosts(); + let mut wait = CHECK_EVERY; + if !hosts.is_empty() { + let dir = self.dir(); + if let Err(e) = std::fs::create_dir_all(&dir) { + log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display()); + } else { + for h in hosts { + if !expiries.contains_key(&h) + && let Some(e) = self.load_stored(&h) + { + expiries.insert(h, e); + } + } + wait = if self.round(&mut expiries).await { + retry = FIRST_RETRY; + CHECK_EVERY + } else { + let w = retry; + retry = (retry * 2).min(MAX_RETRY); + w + }; + } + } + // Woken early by a reload (new hosts) or a "try again" from control. tokio::select! { _ = tokio::time::sleep(wait) => {} + _ = self.shared.acme_wake.notified() => {} _ = shutdown.changed() => return, } } diff --git a/crates/edge/src/admin.rs b/crates/edge/src/admin.rs new file mode 100644 index 0000000..09fa478 --- /dev/null +++ b/crates/edge/src/admin.rs @@ -0,0 +1,326 @@ +// 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 admin socket: a Unix socket (mode 0660, so only edge's user and group, i.e. control, +//! can connect; never a TCP port) speaking small JSON over HTTP/1.1. +//! +//! | Request | Does | +//! |:--|:--| +//! | `GET /v1/status` | config hash, trial, revocations, health per host and upstream, certificates | +//! | `POST /v1/reload` | reload the config file (refused while a trial runs) | +//! | `POST /v1/trial {confirm_within_secs, watch_hosts?, watch_every_secs?}` | serve the trial file until confirmed | +//! | `POST /v1/confirm {config_sha256}` | keep the running trial | +//! | `POST /v1/abort` | back to the config before the trial (idempotent) | +//! | `POST /v1/share-revocations/reload` | re-read the share-link revocation file | +//! | `POST /v1/acme/retry` | try Let's Encrypt again now | +//! +//! Bodies are at most 4 KiB with no unknown fields. Answers never carry a secret. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use bytes::Bytes; +use http_body_util::{BodyExt, Full, Limited}; +use hyper::body::Incoming; +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper::{Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use pingora::server::ShutdownWatch; +use pingora::services::background::BackgroundService; +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::shared::{AdminError, Shared, WatchSpec}; + +const MAX_BODY: usize = 4096; +/// Longest trial the admin socket accepts. +const MAX_TRIAL_SECS: u64 = 3600; + +pub struct AdminSocket { + pub shared: Arc, + pub path: PathBuf, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct TrialBody { + confirm_within_secs: u64, + #[serde(default)] + watch_hosts: Vec, + watch_every_secs: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ConfirmBody { + config_sha256: String, +} + +type Resp = Response>; + +fn reply(status: StatusCode, v: Value) -> Resp { + let mut r = Response::new(Full::new(Bytes::from(v.to_string()))); + *r.status_mut() = status; + r.headers_mut().insert( + http::header::CONTENT_TYPE, + http::HeaderValue::from_static("application/json"), + ); + r +} + +fn error(status: StatusCode, message: impl std::fmt::Display) -> Resp { + reply(status, json!({ "error": message.to_string() })) +} + +fn admin_error(e: AdminError) -> Resp { + match e { + AdminError::Refused(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e), + AdminError::Conflict(m) => error(StatusCode::CONFLICT, m), + } +} + +/// The status document. +pub fn status(shared: &Shared) -> Value { + let rt = shared.current(); + let mut hosts: Vec<&String> = rt.hosts.keys().collect(); + hosts.sort(); + let hosts: Vec = hosts + .into_iter() + .filter_map(|name| rt.hosts.get(name)) + .map(|h| { + let name = &h.cfg.hostname; + let cert = match &h.cfg.tls { + ianitor_core::edge_config::EdgeTls::Files { .. } => json!({ + "state": "ok", + "not_after": rt.file_cert_expiry.get(name), + "error": null, + }), + ianitor_core::edge_config::EdgeTls::Acme => match shared.cert_state(name) { + Some(c) => { + json!({ "state": c.state, "not_after": c.not_after, "error": c.error }) + } + None => json!({ "state": "pending", "not_after": null, "error": null }), + }, + }; + json!({ + "hostname": name, + "health_check": h.cfg.health_check.is_some(), + "upstreams": h.upstreams.iter().map(|u| json!({ + "address": u.authority, + "healthy": u.healthy.load(std::sync::atomic::Ordering::Relaxed), + "checks": u.health.checks(), + })).collect::>(), + "certificate": cert, + }) + }) + .collect(); + let rev = shared.revocations(); + json!({ + "generation": shared.generation(), + "config_sha256": rt.sha256, + "started_at": shared.started_at, + "trial": shared.trial_info().map(|(sha, left, prev)| json!({ + "config_sha256": sha, + "seconds_left": left, + "previous_sha256": prev, + })), + "share_revocations": { + "loaded": rev.loaded, + "epoch": rev.revocations.epoch, + "stopped": rev.revocations.deny.len(), + "error": rev.error, + }, + "hosts": hosts, + }) +} + +async fn body Deserialize<'de>>( + req: Request, +) -> Result, Box> { + let bytes = Limited::new(req.into_body(), MAX_BODY) + .collect() + .await + .map_err(|_| { + error( + StatusCode::PAYLOAD_TOO_LARGE, + "the body is larger than 4 KiB", + ) + })? + .to_bytes(); + if bytes.is_empty() { + return Ok(None); + } + serde_json::from_slice(&bytes) + .map(Some) + .map_err(|e| Box::new(error(StatusCode::BAD_REQUEST, format!("bad body: {e}")))) +} + +async fn handle(shared: Arc, req: Request) -> Resp { + let method = req.method().clone(); + let path = req.uri().path().to_owned(); + match (method.as_str(), path.as_str()) { + ("GET", "/v1/status") => reply(StatusCode::OK, status(&shared)), + ("POST", "/v1/reload") => { + let r = tokio::task::spawn_blocking({ + let s = shared.clone(); + move || s.reload() + }) + .await; + match r { + Ok(Ok(rt)) => reply( + StatusCode::OK, + json!({ "config_sha256": rt.sha256, "generation": shared.generation() }), + ), + Ok(Err(e)) => admin_error(e), + Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e), + } + } + ("POST", "/v1/trial") => { + let b: TrialBody = match body(req).await { + Ok(Some(b)) => b, + Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"), + Err(r) => return *r, + }; + if !(1..=MAX_TRIAL_SECS).contains(&b.confirm_within_secs) { + return error( + StatusCode::BAD_REQUEST, + "confirm_within_secs must be between 1 and 3600", + ); + } + let every = b.watch_every_secs.unwrap_or(5); + if !(1..=60).contains(&every) || b.watch_hosts.len() > 1000 { + return error(StatusCode::BAD_REQUEST, "watch_every_secs must be 1 to 60"); + } + let watch = (!b.watch_hosts.is_empty()).then(|| WatchSpec { + hosts: b.watch_hosts, + every: Duration::from_secs(every), + }); + let within = Duration::from_secs(b.confirm_within_secs); + let r = tokio::task::spawn_blocking({ + let s = shared.clone(); + move || s.start_trial(within, watch) + }) + .await; + match r { + Ok(Ok((id, rt))) => { + let s = shared.clone(); + tokio::spawn(async move { + if let Some(deadline) = s.trial_deadline(id) { + tokio::time::sleep_until(deadline.into()).await; + s.expire_trial(id); + } + }); + reply( + StatusCode::OK, + json!({ "config_sha256": rt.sha256, "generation": shared.generation() }), + ) + } + Ok(Err(e)) => admin_error(e), + Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e), + } + } + ("POST", "/v1/confirm") => { + let b: ConfirmBody = match body(req).await { + Ok(Some(b)) => b, + Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"), + Err(r) => return *r, + }; + match shared.confirm(&b.config_sha256) { + Ok(()) => reply(StatusCode::OK, json!({ "confirmed": true })), + Err(e) => admin_error(e), + } + } + ("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })), + ("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() { + Ok(()) => { + let r = shared.revocations(); + reply( + StatusCode::OK, + json!({ "epoch": r.revocations.epoch, "stopped": r.revocations.deny.len() }), + ) + } + Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e), + }, + ("POST", "/v1/acme/retry") => { + shared.acme_wake.notify_one(); + reply(StatusCode::OK, json!({ "retrying": true })) + } + (_, "/v1/status" | "/v1/reload" | "/v1/trial" | "/v1/confirm" | "/v1/abort") => { + error(StatusCode::METHOD_NOT_ALLOWED, "method not allowed") + } + _ => error(StatusCode::NOT_FOUND, "no such admin request"), + } +} + +fn bind(path: &Path) -> std::io::Result { + use std::os::unix::fs::{FileTypeExt, PermissionsExt}; + // A socket left over from a previous run is removed; anything else at the path is not. + if let Ok(meta) = std::fs::symlink_metadata(path) { + if meta.file_type().is_socket() { + std::fs::remove_file(path)?; + } else { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + format!("{} exists and is not a socket", path.display()), + )); + } + } + let l = tokio::net::UnixListener::bind(path)?; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660))?; + Ok(l) +} + +#[async_trait] +impl BackgroundService for AdminSocket { + async fn start(&self, mut shutdown: ShutdownWatch) { + let listener = match bind(&self.path) { + Ok(l) => l, + Err(e) => { + log::error!(target: "ianitor::admin", "cannot listen on {}: {e}; control cannot reach edge", self.path.display()); + return; + } + }; + log::info!(target: "ianitor::admin", "admin socket at {}", self.path.display()); + loop { + tokio::select! { + _ = shutdown.changed() => break, + a = listener.accept() => { + let Ok((stream, _)) = a else { continue }; + let shared = self.shared.clone(); + tokio::spawn(async move { + let svc = service_fn(move |req| { + let shared = shared.clone(); + async move { Ok::<_, std::convert::Infallible>(handle(shared, req).await) } + }); + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(stream), svc) + .await; + }); + } + } + } + let _ = std::fs::remove_file(&self.path); + } +} + +/// Re-reads the share-link revocation file when it changes (every 5 s), so a stopped link +/// stops even if control's reload request was lost. +pub struct RevocationPoller { + pub shared: Arc, +} + +#[async_trait] +impl BackgroundService for RevocationPoller { + async fn start(&self, mut shutdown: ShutdownWatch) { + loop { + tokio::select! { + _ = shutdown.changed() => return, + _ = tokio::time::sleep(Duration::from_secs(5)) => self.shared.poll_revocations(), + } + } + } +} diff --git a/crates/edge/src/health.rs b/crates/edge/src/health.rs index 0195d99..bba150d 100644 --- a/crates/edge/src/health.rs +++ b/crates/edge/src/health.rs @@ -4,57 +4,153 @@ //! Active health checks, like Caddy's `health_checks.active`: `GET ` with the upstream //! address as Host, healthy on 2xx, 5 s timeout, one result flips the state. The first round -//! runs at startup; upstreams start healthy. +//! runs when a config is loaded; upstreams start healthy. +//! +//! Every result is also recorded (time, latency, why it failed) for the admin socket. +//! During a trial, the watched hosts are probed at least every `every` seconds; a watched +//! host without a health check gets `GET /` with its own hostname as Host, and any answer +//! below 500 counts as alive (docs/ui-api.md G3). Those watch probes never change routing. use std::sync::Arc; use std::sync::atomic::Ordering; -use std::time::Duration; +use std::time::{Duration, Instant}; use async_trait::async_trait; use pingora::connectors::http::Connector; use pingora::http::RequestHeader; use pingora::server::ShutdownWatch; use pingora::services::background::BackgroundService; +use pingora::{Error, ErrorType}; use crate::fetch::fetch; -use crate::runtime::{HostRt, Runtime, UpstreamRt}; +use crate::logging::now_secs; +use crate::runtime::{Check, HostRt, UpstreamRt}; +use crate::shared::Shared; const TIMEOUT: Duration = Duration::from_secs(5); pub struct HealthChecks { - pub rt: Arc, + pub shared: Arc, } -async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool { - let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else { - return false; +/// Why a probe failed, in the words of docs/ui-api.md §3.3. +pub fn failure_kind(e: &Error) -> &'static str { + match e.etype() { + ErrorType::ConnectRefused | ErrorType::ConnectError | ErrorType::ConnectionClosed => { + "refused" + } + ErrorType::ConnectTimedout + | ErrorType::ReadTimedout + | ErrorType::WriteTimedout + | ErrorType::TLSHandshakeTimedout => "timeout", + ErrorType::ConnectNoRoute => "name", + ErrorType::TLSHandshakeFailure | ErrorType::InvalidCert | ErrorType::HandshakeError => { + "tls" + } + _ => "bad_answer", + } +} + +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", + } +} + +/// One probe. `watch` probes count any answer below 500 as alive. +async fn probe( + connector: &Connector, + u: &UpstreamRt, + path: &str, + host: &str, + watch: bool, +) -> Check { + let started = Instant::now(); + let at = now_secs() as u64; + let source = if watch { "watch" } else { "health_check" }; + let fail = |kind: &'static str, status: Option, latency: Option| Check { + seq: 0, + at, + ok: false, + source, + kind: Some(kind), + status, + latency_ms: latency, }; - if req - .insert_header(http::header::HOST, u.authority.as_str()) - .is_err() - { - return false; + let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else { + return fail("bad_answer", None, None); + }; + if req.insert_header(http::header::HOST, host).is_err() { + return fail("bad_answer", None, None); } match fetch(connector, u, req, 64 * 1024, TIMEOUT).await { - Ok(f) => f.header.status.is_success(), - Err(_) => false, + Ok(f) => { + let status = f.header.status.as_u16(); + let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + let ok = if watch { + (100..500).contains(&status) + } else { + f.header.status.is_success() + }; + if ok { + Check { + seq: 0, + at, + ok: true, + source, + kind: None, + status: Some(status), + latency_ms: Some(latency), + } + } else { + fail(status_kind(status), Some(status), Some(latency)) + } + } + Err(e) => fail(failure_kind(&e), None, None), } } /// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a /// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of /// ending health checks. -async fn round(host: &Arc, path: &str, connector: &Arc) { +async fn round(host: &Arc, path: &str, connector: &Arc, watch: bool) { for i in 0..host.upstreams.len() { let (h, p, c) = (host.clone(), path.to_owned(), connector.clone()); - let ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await { - Ok(ok) => ok, + let probe_host = if watch { + host.cfg.hostname.clone() + } else { + host.upstreams[i].authority.clone() + }; + let check = match tokio::spawn(async move { + probe(&c, &h.upstreams[i], &p, &probe_host, watch).await + }) + .await + { + Ok(c) => c, Err(e) => { log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority); - false + Check { + seq: 0, + at: now_secs() as u64, + ok: false, + source: if watch { "watch" } else { "health_check" }, + kind: Some("bad_answer"), + status: None, + latency_ms: None, + } } }; let u = &host.upstreams[i]; + let ok = check.ok; + u.health.record(check); + if watch { + // Watch probes only report; routing follows the host's own health check. + continue; + } if u.healthy.swap(ok, Ordering::Relaxed) != ok { if ok { log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority); @@ -65,50 +161,93 @@ async fn round(host: &Arc, path: &str, connector: &Arc) { } } -async fn watch(host: Arc, path: String, every: Duration) { +async fn watcher(host: Arc, path: String, every: Duration, watch: bool) { let connector = Arc::new(Connector::new(None)); loop { - round(&host, &path, &connector).await; + round(&host, &path, &connector, watch).await; tokio::time::sleep(every).await; } } +struct Job { + host: Arc, + path: String, + every: Duration, + watch: bool, +} + +fn jobs(shared: &Shared) -> Vec { + let rt = shared.current(); + let spec = shared.watch_spec(); + let watched = |h: &str| { + spec.as_ref() + .is_some_and(|s| s.hosts.iter().any(|w| w == h)) + }; + let every = spec.as_ref().map(|s| s.every); + let mut out = Vec::new(); + for h in rt.hosts.values() { + let name = &h.cfg.hostname; + match &h.cfg.health_check { + Some(hc) => { + let mut interval = Duration::from_secs(u64::from(hc.interval_secs.max(1))); + if watched(name) + && let Some(e) = every + { + interval = interval.min(e); + } + out.push(Job { + host: h.clone(), + path: hc.path.clone(), + every: interval, + watch: false, + }); + } + None if watched(name) => out.push(Job { + host: h.clone(), + path: "/".into(), + every: every.unwrap_or(Duration::from_secs(5)), + watch: true, + }), + None => {} + } + } + out +} + #[async_trait] impl BackgroundService for HealthChecks { async fn start(&self, mut shutdown: ShutdownWatch) { - let checked: Vec<(Arc, String, Duration)> = self - .rt - .hosts - .values() - .filter_map(|h| { - h.cfg.health_check.as_ref().map(|hc| { - ( - h.clone(), - hc.path.clone(), - Duration::from_secs(u64::from(hc.interval_secs.max(1))), - ) - }) - }) - .collect(); - let mut tasks = tokio::task::JoinSet::new(); - let mut which = std::collections::HashMap::new(); - for (i, (h, p, every)) in checked.iter().enumerate() { - which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); - } - // A watcher never returns; if one ends anyway, say so and start it again. + let mut changes = self.shared.subscribe(); loop { - tokio::select! { - _ = shutdown.changed() => break, - Some(done) = tasks.join_next_with_id() => { - let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() }; - if let Some(i) = which.remove(&id) { - let (h, p, every) = &checked[i]; - log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname); - which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); + let jobs = jobs(&self.shared); + let mut tasks = tokio::task::JoinSet::new(); + let mut which = std::collections::HashMap::new(); + for (i, j) in jobs.iter().enumerate() { + let id = tasks + .spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch)) + .id(); + which.insert(id, i); + } + // Run until the config or the watch changes; a watcher never returns, and if one + // ends anyway, say so and start it again. + let stop = loop { + tokio::select! { + _ = shutdown.changed() => break true, + r = changes.changed() => break r.is_err(), + Some(done) = tasks.join_next_with_id() => { + let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() }; + if let Some(i) = which.remove(&id) { + let j = &jobs[i]; + log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", j.host.cfg.hostname); + which.insert(tasks.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch)).id(), i); + } } } + }; + tasks.abort_all(); + if stop { + return; } } - tasks.abort_all(); } } diff --git a/crates/edge/src/http_app.rs b/crates/edge/src/http_app.rs index 82c0492..5b83bbf 100644 --- a/crates/edge/src/http_app.rs +++ b/crates/edge/src/http_app.rs @@ -19,10 +19,10 @@ use pingora::server::ShutdownWatch; use crate::acme::Challenges; use crate::logging::{AccessRecord, now_secs, truncate_ip}; use crate::proxy::{host_header, hostname}; -use crate::runtime::Runtime; +use crate::shared::Shared; pub struct HttpApp { - pub rt: Arc, + pub shared: Arc, pub challenges: Arc, } @@ -75,6 +75,7 @@ impl HttpServerApp for HttpApp { impl HttpApp { async fn response(&self, session: &mut ServerSession) -> Response> { let start = Instant::now(); + let rt = self.shared.current(); let req = session.req_header(); let hh = host_header(req); let name = hostname(&hh); @@ -92,11 +93,11 @@ impl HttpApp { return r; } - let Some(host) = self.rt.host(&name) else { + let Some(host) = rt.host(&name) else { return empty(StatusCode::NOT_FOUND); }; let uri = req.uri.path_and_query().map_or("/", |p| p.as_str()); - let port = self.rt.cfg.https_port; + let port = rt.cfg.https_port; let location = if port == 443 { format!("https://{name}{uri}") } else { @@ -110,7 +111,7 @@ impl HttpApp { Err(_) => return empty(StatusCode::BAD_REQUEST), } if host.cfg.access_log - && let Some(log) = &self.rt.access_log + && let Some(log) = &rt.access_log { log.write(&AccessRecord { ts: now_secs(), diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 1b42089..23a3ee5 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -5,23 +5,29 @@ //! Ianitor edge: the Pingora data plane. It reads the config compiled by `ianitor-core` //! and serves it; it never decides policy. //! -//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, websockets, header rules, -//! round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and redirects), -//! health checks, ACME issuance and renewal. +//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, share links, websockets, +//! header rules, round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and +//! redirects), health checks, ACME issuance and renewal, and the admin socket through which +//! control reloads the config in process (see `shared`). pub mod acme; +#[cfg(unix)] +pub mod admin; pub mod error; pub mod fetch; pub mod forward_auth; pub mod health; pub mod http_app; pub mod logging; +pub mod pages; pub mod proxy; pub mod runtime; pub mod secrets; +pub mod share; +pub mod shared; pub mod tls; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use pingora::connectors::http::Connector; @@ -34,24 +40,63 @@ use pingora::services::listening::Service; pub use error::EdgeError; pub use runtime::Runtime; +pub use shared::Shared; #[derive(Debug, Clone, Default)] pub struct Options { /// The compiled edge config (`ianitor-core` edge compiler output). pub config: PathBuf, + /// The trial config control writes before an apply; default `.trial`. + pub trial_config: Option, + /// Admin socket for control (Unix only); none when `None`. + pub admin_socket: Option, + /// The share-link revocation file control writes; without it, share links are refused. + pub share_revocations: Option, /// Extra trust root for the ACME directory's TLS (Pebble in tests). pub acme_root: Option, } +impl Options { + pub fn trial_path(&self) -> PathBuf { + self.trial_config + .clone() + .unwrap_or_else(|| default_trial_path(&self.config)) + } +} + +/// `.trial`, next to the config. +pub fn default_trial_path(config: &Path) -> PathBuf { + let mut name = config.file_name().unwrap_or_default().to_os_string(); + name.push(".trial"); + config.with_file_name(name) +} + +fn credentials_dir() -> Option { + std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from) +} + /// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates. -pub fn prepare(opts: &Options) -> Result, EdgeError> { - let cfg = runtime::read_config(&opts.config)?; - let creds = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from); - runtime::build(cfg, creds.as_deref()).map(Arc::new) +pub fn prepare(opts: &Options) -> Result, EdgeError> { + let creds = credentials_dir(); + let rt = runtime::build_file(&opts.config, creds.as_deref())?; + Ok(shared_for(rt, opts)) +} + +/// Wrap an already built runtime (tests run edge in process this way). +pub fn shared_for(rt: Runtime, opts: &Options) -> Arc { + Shared::new( + rt, + shared::Paths { + config: opts.config.clone(), + trial: opts.trial_path(), + revocations: opts.share_revocations.clone(), + }, + credentials_dir(), + ) } /// Assemble the Pingora server with all services. Listeners bind when it runs. -pub fn server(rt: Arc, opts: &Options) -> Result { +pub fn server(shared: Arc, opts: &Options) -> Result { pingora::tls::install_default_crypto_provider(); let conf = ServerConf { threads: 2, @@ -63,11 +108,12 @@ pub fn server(rt: Arc, opts: &Options) -> Result { server.bootstrap(); let challenges = Arc::new(acme::Challenges::default()); + let rt = shared.current(); let mut https = http_proxy_service( &server.configuration, proxy::EdgeProxy { - rt: rt.clone(), + shared: shared.clone(), connector: Connector::new(None), }, ); @@ -75,14 +121,14 @@ pub fn server(rt: Arc, opts: &Options) -> Result { address: rt.cfg.https_listen.clone(), reason: e.to_string(), })?; - tls.set_cert_resolver(rt.certs.clone()); + tls.set_cert_resolver(shared.certs.clone()); tls.enable_h2(); https.add_tls_with_settings(&rt.cfg.https_listen, None, tls); let mut http = Service::new( "ianitor http".to_owned(), http_app::HttpApp { - rt: rt.clone(), + shared: shared.clone(), challenges: challenges.clone(), }, ); @@ -92,17 +138,36 @@ pub fn server(rt: Arc, opts: &Options) -> Result { server.add_service(http); server.add_service(background_service( "ianitor health checks", - health::HealthChecks { rt: rt.clone() }, + health::HealthChecks { + shared: shared.clone(), + }, )); server.add_service(background_service( "ianitor acme", acme::AcmeService { - rt: rt.clone(), - certs: rt.certs.clone(), + shared: shared.clone(), challenges, ca_root: opts.acme_root.clone(), }, )); + #[cfg(unix)] + { + server.add_service(background_service( + "ianitor share revocations", + admin::RevocationPoller { + shared: shared.clone(), + }, + )); + if let Some(path) = &opts.admin_socket { + server.add_service(background_service( + "ianitor admin socket", + admin::AdminSocket { + shared: shared.clone(), + path: path.clone(), + }, + )); + } + } Ok(server) } diff --git a/crates/edge/src/main.rs b/crates/edge/src/main.rs index 08210f3..e65a403 100644 --- a/crates/edge/src/main.rs +++ b/crates/edge/src/main.rs @@ -2,7 +2,8 @@ // 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/. -//! `ianitor-edge --config [--check] [--acme-root ]` +//! `ianitor-edge --config [--check] [--admin-socket ] [--trial-config ] +//! [--share-revocations ] [--acme-root ]` //! //! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG` //! (error, warn, info, debug, trace; libraries are capped at info). @@ -21,10 +22,14 @@ fn parse_args() -> Result<(Options, bool), EdgeError> { match a.to_str() { Some("--config") => config = args.next().map(PathBuf::from), Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from), + Some("--admin-socket") => opts.admin_socket = args.next().map(PathBuf::from), + Some("--trial-config") => opts.trial_config = args.next().map(PathBuf::from), + Some("--share-revocations") => opts.share_revocations = args.next().map(PathBuf::from), Some("--check") => check = true, Some("--help" | "-h") => { println!( - "usage: ianitor-edge --config [--check] [--acme-root ]" + "usage: ianitor-edge --config [--check] [--admin-socket ] \ + [--trial-config ] [--share-revocations ] [--acme-root ]" ); std::process::exit(0); } @@ -44,12 +49,12 @@ fn parse_args() -> Result<(Options, bool), EdgeError> { fn main() -> ExitCode { ianitor_edge::logging::init(std::env::var("IANITOR_LOG").ok().as_deref()); let started = parse_args().and_then(|(opts, check)| { - let rt = ianitor_edge::prepare(&opts)?; - log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), rt.hosts.len()); + let shared = ianitor_edge::prepare(&opts)?; + log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), shared.current().hosts.len()); if check { return Ok(None); } - ianitor_edge::server(rt, &opts).map(Some) + ianitor_edge::server(shared, &opts).map(Some) }); match started { Ok(None) => ExitCode::SUCCESS, diff --git a/crates/edge/src/pages.rs b/crates/edge/src/pages.rs new file mode 100644 index 0000000..484f927 --- /dev/null +++ b/crates/edge/src/pages.rs @@ -0,0 +1,211 @@ +// 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 share-link visitor pages (docs/ui-api.md §4): one self-contained HTML page each, inline +//! CSS, no JavaScript, no external requests, under 8 KB. Only the hostname and a date come +//! from the request side, both escaped; the token is echoed only into the password form's +//! hidden field (it is already in the visitor's address bar at that point), escaped too. + +use ianitor_core::share::PASSWORD_PATH; +use ianitor_core::time::long_date; + +pub enum Problem { + WrongPassword, + TooMany, +} + +pub enum Page<'a> { + Password { + host: &'a str, + token: &'a str, + until: u64, + problem: Option, + }, + Expired { + host: &'a str, + until: u64, + }, + Invalid { + host: &'a str, + }, +} + +impl Page<'_> { + pub fn status(&self) -> u16 { + match self { + Page::Password { + problem: Some(Problem::TooMany), + .. + } => 429, + Page::Password { .. } => 401, + Page::Expired { .. } => 410, + Page::Invalid { .. } => 403, + } + } +} + +pub fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c if c.is_control() => {} + c => out.push(c), + } + } + out +} + +const STYLE: &str = "\ +*{box-sizing:border-box}\ +body{margin:0;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;\ +background:#0c0b0f;color:#f1edf3;font-family:system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;padding:16px}\ +.card{width:100%;max-width:420px;padding:32px;background:#18151d;border:1px solid #3c3445;border-radius:18px}\ +@media (max-width:480px){.card{padding:24px}}\ +.host{color:#cfc6d4;font-size:.95rem;font-weight:600;margin:0 0 16px;overflow-wrap:anywhere}\ +svg{display:block;margin:0 0 12px}\ +h1{font-size:1.5rem;font-weight:700;color:#f1edf3;margin:0 0 8px}\ +p{font-size:1rem;line-height:1.5;color:#cfc6d4;margin:0 0 16px}\ +label{display:block;color:#cfc6d4;font-size:.9rem;margin:0 0 6px}\ +input[type=password]{width:100%;height:48px;background:#0c0b0f;border:1px solid #7d7189;border-radius:10px;\ +color:#f1edf3;font-size:1rem;padding:0 12px}\ +input[type=password]:focus{outline:none;border-color:#e0a3dc;box-shadow:0 0 0 4px rgba(224,163,220,.16)}\ +.err{color:#e2683a;font-size:.92rem;margin:8px 0 0;display:flex;gap:6px;align-items:center}\ +button{margin-top:16px;width:100%;height:48px;border-radius:12px;border:1px solid #c77cc1;color:#fff;font-weight:700;\ +font-size:1rem;background:linear-gradient(#8d3b89,#76306f 55%,#5c2257)}\ +button:focus{outline:2px solid #f2c9ee;outline-offset:2px}\ +button:disabled{opacity:.5}\ +.small{font-size:.92rem;margin:16px 0 0}\ +a{color:#e0a3dc;display:inline-flex;align-items:center;min-height:44px}\ +footer{color:#a99eb1;font-size:.72rem;letter-spacing:.2em;text-transform:uppercase;margin-top:16px}"; + +fn icon(kind: &str) -> String { + let (colour, body) = match kind { + // lock + "lock" => ( + "#e0a3dc", + "", + ), + // clock + "clock" => ( + "#d99a35", + "", + ), + // broken link + _ => ( + "#d99a35", + "", + ), + }; + format!( + "{body}" + ) +} + +const RING: &str = ""; + +fn shell(host: &str, inner: &str, title: &str) -> String { + format!( + "\ + \ + \ + {title}
\ +

{}

{inner}
Ianitor Domi
", + escape(host) + ) +} + +pub fn render(p: &Page<'_>) -> String { + match p { + Page::Password { + host, + token, + until, + problem, + } => { + let h = escape(host); + let (msg, disabled) = match problem { + Some(Problem::WrongPassword) => ( + format!( + "

{RING}That password is not right. Check it with the person who sent the link.

" + ), + "", + ), + Some(Problem::TooMany) => ( + format!( + "

{RING}Too many tries. Wait a minute, then try again.

" + ), + " disabled", + ), + None => (String::new(), ""), + }; + let inner = format!( + "{}

This link is protected

\ +

Someone shared {h} with you. Enter the password they gave you.

\ +
\ + \ + \ + \ + {msg}
\ +

The link works until {}.

", + icon("lock"), + escape(token), + long_date(*until) + ); + shell(host, &inner, "This link is protected") + } + Page::Expired { host, until } => { + let inner = format!( + "{}

This link has expired

\ +

It worked until {}. Ask the person who sent it for a new one.

\ + Have an account? Sign in", + icon("clock"), + long_date(*until) + ); + shell(host, &inner, "This link has expired") + } + Page::Invalid { host } => { + let inner = format!( + "{}

This link no longer works

\ +

It may have been stopped, or not copied in full. Ask the person who sent it for a new one.

\ + Have an account? Sign in", + icon("broken") + ); + shell(host, &inner, "This link no longer works") + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pages_are_small_and_escaped() { + for p in [ + Page::Password { + host: "x", + token: "\">