Compare commits
132 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 67888aa791 | |||
| 6956f23cb2 | |||
| 2aa8d66127 | |||
| 695ed178a5 | |||
| defd722cc2 | |||
| d5d522fe4b | |||
| 49c05e2523 | |||
| 09f6b12676 | |||
| 4e3c721ef5 | |||
| dced199132 | |||
| 51a95e4f75 | |||
| 5e273241e4 | |||
| acf69a8ed2 | |||
| fc9e16f1b2 | |||
| 83270e0746 | |||
| 00b506670f | |||
| d4da521a91 | |||
| 1cc3599f10 | |||
| 8e3a3c01e4 | |||
| 0e9c2a7bc9 | |||
| dcdff4d414 | |||
| b9ab5006a8 | |||
| 7a32eeb411 | |||
| c2c6454302 | |||
| d035fd3165 | |||
| 7b906de79f | |||
| 6ba3fa4b17 | |||
| 5df34bfae6 | |||
| 7322bbd856 | |||
| 0213021bb1 | |||
| c45dafa2a3 | |||
| 4d87537a76 | |||
| 09b8313a04 | |||
| 057abbc954 | |||
| 457aea86ca | |||
| 23a283ece9 | |||
| ba3a060b2e | |||
| 503916492d | |||
| b24ffdf9db | |||
| 3bf5fa0e1a | |||
| bc336d1188 | |||
| e84eb1ba74 | |||
| 0749119f19 | |||
| e2a777882c | |||
| b85c38f615 | |||
| ca9bf3fdd4 | |||
| a61dfd854f | |||
| 9933f55242 | |||
| 3e326e85a0 | |||
| aed5fbfcff | |||
| f9dd2247f8 | |||
| 6237e721d6 | |||
| 12886a1d31 | |||
| c18ae154ad | |||
| 211b851c3e | |||
| a5190acc3b | |||
| 3d8f524d00 | |||
| 4054427b62 | |||
| 18da3f5d5a | |||
| dc23bfe842 | |||
| cde0c3ea3b | |||
| 7cb5715580 | |||
| cb04bff74e | |||
| 24009414de | |||
| 1adfa05640 | |||
| 83a857ad80 | |||
| afc3477b5c | |||
| 7863202e3a | |||
| 443d7457d2 | |||
| 432ae0f803 | |||
| 83b7b3b7d6 | |||
| cbb3e41ca7 | |||
| 17f26f94a3 | |||
| e28b084a19 | |||
| 421800ec18 | |||
| 85edfa7128 | |||
| 60fb4b63ee | |||
| 7d3af00720 | |||
| 43918943da | |||
| dd10557b87 | |||
| 339882ec96 | |||
| 00f8dffc6a | |||
| 99b2a3a1a5 | |||
| f382fe2f76 | |||
| 54574702ea | |||
| 2b66729f1b | |||
| 4448527b16 | |||
| b9e14c6aee | |||
| 98dad246d3 | |||
| fee35830d1 | |||
| c5380c65a6 | |||
| 7cc92ec42d | |||
| 2c06efead1 | |||
| 56982fc6b7 | |||
| aa0f66b5ac | |||
| 56209cc595 | |||
| 74d1bc02da | |||
| 6ce1fe9d2b | |||
| c0ed9c65c5 | |||
| 7c81945771 | |||
| 94ba18d38b | |||
| 73a9f3da45 | |||
| 027bf3a553 | |||
| db43af24a6 | |||
| cee64dd462 | |||
| 0c42138d74 | |||
| 27b0a165b2 | |||
| 8c04b0f4bd | |||
| ee8c304740 | |||
| ed2a166165 | |||
| 2dfb0b8ecc | |||
| ecdba7775f | |||
| a052c32b77 | |||
| bcf94928c9 | |||
| a272e476b7 | |||
| 60aee5d78a | |||
| 58d0397875 | |||
| d42c178a13 | |||
| fd4b4a7775 | |||
| c50fcd5a5a | |||
| 6a7aafc859 | |||
| e7fa5f57ec | |||
| c14fb2dea6 | |||
| 17e1df8320 | |||
| 4fe041082d | |||
| a94a242c79 | |||
| a5823ba33d | |||
| ff087a14dd | |||
| 9176cc63a4 | |||
| c1abe88688 | |||
| 8f79ce042c | |||
| 7e557f47ae |
@@ -0,0 +1,9 @@
|
|||||||
|
target
|
||||||
|
**/node_modules
|
||||||
|
**/dist
|
||||||
|
.git
|
||||||
|
.fabrica
|
||||||
|
bench
|
||||||
|
*.log
|
||||||
|
result
|
||||||
|
result-*
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# Local Fabrica runs: records, logs and artifacts (Fabrica core docs/FORMATS.md)
|
||||||
|
runs/
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Ianitor Domi declares itself to Fabrica (Fabrica core docs/FORMATS.md, "Fabrica: the app"): a server part only,
|
||||||
|
# the reverse proxy with its control plane and web UI, deployed by .fabrica/artifex/deploy.yaml through the server's
|
||||||
|
# fabrica-deploy@ianitor. Fabrica's Apps screen shows one card for it: Deploy, then the Custos card. The colour is
|
||||||
|
# the murex accent (packages/ui/src/tokens.css, --accent).
|
||||||
|
name: Ianitor
|
||||||
|
icon: globe
|
||||||
|
color: "#e0a3dc"
|
||||||
|
parts:
|
||||||
|
server:
|
||||||
|
pipeline: deploy
|
||||||
|
input: ianitor
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Ianitor Domi onto the server (Fabrica docs/04_deploy.md): `fabrica deploy ianitor`, or Fabrica's Apps → Ianitor →
|
||||||
|
# Deploy. The NixOS runner starts fabrica-deploy@ianitor: the server's clone is fast-forwarded, the flake input
|
||||||
|
# `ianitor` updated (inputs.ianitor.nixosModules.ianitor, docs/deploy/configuration-server.patch), the system
|
||||||
|
# switched, the health check asked, and the switch rolled back if it does not answer. After a deploy run
|
||||||
|
# deploy/test-access.sh from a LAN machine (CLAUDE.md).
|
||||||
|
name: deploy
|
||||||
|
on:
|
||||||
|
manual: true
|
||||||
|
runner: nixos
|
||||||
|
steps:
|
||||||
|
- id: approve
|
||||||
|
approve: "Deploy Ianitor ${{ commit }} to the server?"
|
||||||
|
- id: switch
|
||||||
|
needs: [approve]
|
||||||
|
deploy: ianitor
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# Ianitor Domi: the Gitea release of a v* tag (docs/release.md). Since 0.2.0 (T4) a release carries the programs:
|
||||||
|
# the Linux tarball and its one-line installer (systemd), the Windows Server zip (Caddy mode), next to the notes and
|
||||||
|
# screenshots of the web UI, all under a SHA256SUMS signed by domi-release through Custos. The Docker image is built
|
||||||
|
# from the same Dockerfile; it is not pushed to a registry yet (docs/deploy/anywhere.md).
|
||||||
|
# The Windows runner (the Fabrica app on Mark's PC) runs it: `fabrica`, node, pnpm, cargo and Docker Desktop are on
|
||||||
|
# every step's PATH; the Linux parts build inside Docker (deploy/docker/Dockerfile), never on the host.
|
||||||
|
# No Gitea webhook to the hub yet: a pushed tag is started on demand (the hub's POST /api/runs, ref v<version>).
|
||||||
|
# `notes` is Fabrica's release notes since the previous v* tag (Fabrica docs/12_release_kit.md); `shots` takes the
|
||||||
|
# same files as `fabrica aula shots` (core docs/FORMATS.md, "Fabrica: the Aula page") from the built web UI against
|
||||||
|
# the demo control plane with invented data, in headless Edge. No landing page while app.yaml has no `aula: true`.
|
||||||
|
name: release
|
||||||
|
on:
|
||||||
|
tag: "v*"
|
||||||
|
manual: true
|
||||||
|
runner: windows
|
||||||
|
steps:
|
||||||
|
- id: version
|
||||||
|
run: node scripts/check-version.mjs ${{ version }}
|
||||||
|
- id: install
|
||||||
|
run: pnpm install --frozen-lockfile
|
||||||
|
- id: check
|
||||||
|
needs: [install]
|
||||||
|
run: pnpm --filter web check
|
||||||
|
- id: test
|
||||||
|
needs: [install]
|
||||||
|
run: pnpm --filter web test
|
||||||
|
# The whole Rust workspace on Linux (the differential suite against Caddy, Pebble ACME, the edge suites), in the CI
|
||||||
|
# image; two jobs, so Docker Desktop's memory holds.
|
||||||
|
- id: linux-tests
|
||||||
|
needs: [version]
|
||||||
|
run: docker build --load -f deploy/docker/Dockerfile --target ci -t ianitor-ci:${{ version }} . && docker run --rm --memory 6g ianitor-ci:${{ version }} cargo test --workspace --locked -j 2
|
||||||
|
# Windows: the Caddy-mode tests and the differential suite with Windows paths (Pingora against Windows Caddy;
|
||||||
|
# IANITOR_CADDY_BIN names caddy.exe on the runner).
|
||||||
|
- id: windows-tests
|
||||||
|
needs: [version]
|
||||||
|
run: cargo test --workspace --locked
|
||||||
|
- id: windows
|
||||||
|
needs: [check, test, windows-tests]
|
||||||
|
run: cargo build --release --locked -p ianitor-control --no-default-features && pnpm --filter web build && node scripts/package-windows.mjs
|
||||||
|
artifacts: ["target/dist/ianitor-*-windows-x86_64.zip"]
|
||||||
|
- id: linux
|
||||||
|
needs: [linux-tests]
|
||||||
|
run: docker build -f deploy/docker/Dockerfile --target dist --output type=local,dest=target/dist .
|
||||||
|
artifacts: ["target/dist/ianitor-*-linux-x86_64.tar.gz", "target/dist/install.sh"]
|
||||||
|
- id: image
|
||||||
|
needs: [linux-tests]
|
||||||
|
run: docker build --load -f deploy/docker/Dockerfile -t ianitor:${{ version }} .
|
||||||
|
- id: notes
|
||||||
|
run: fabrica notes
|
||||||
|
artifacts: ["target/notes/release-notes.md", "target/notes/release-notes.json"]
|
||||||
|
- id: shots
|
||||||
|
needs: [check, test]
|
||||||
|
run: node apps/web/scripts/shots.mjs
|
||||||
|
artifacts: ["target/aula/aula-*.png", "target/aula/aula.json"]
|
||||||
|
- id: approve
|
||||||
|
needs: [version, notes, shots, windows, linux, image]
|
||||||
|
approve: "Publish Ianitor ${{ tag }}: the Linux tarball, the Windows Server zip, notes and screenshots?"
|
||||||
|
- id: publish
|
||||||
|
needs: [approve]
|
||||||
|
publish:
|
||||||
|
gitea-release: true
|
||||||
|
files:
|
||||||
|
- "**/ianitor-*-linux-x86_64.tar.gz"
|
||||||
|
- "**/install.sh"
|
||||||
|
- "**/ianitor-*-windows-x86_64.zip"
|
||||||
|
- "**/release-notes.md"
|
||||||
|
- "**/release-notes.json"
|
||||||
|
- "**/aula-*.png"
|
||||||
|
- "**/aula.json"
|
||||||
|
sums: domi-release
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
The first release of Ianitor Domi: a reverse proxy for a home server, built on Cloudflare's Pingora, with Caddy as a
|
||||||
|
tested fallback, a small Domi certificate authority, and a web UI where every change takes three clicks or fewer.
|
||||||
|
|
||||||
|
- **Hosts in plain words.** Add a host, say where its traffic goes, pick a Domi or Let's Encrypt certificate and
|
||||||
|
whether visitors sign in first (Authelia forward-auth). Each host is checked for health and shows healthy,
|
||||||
|
degraded or down.
|
||||||
|
- **Changes that undo themselves.** Every change is compiled, tried, and watched for 60 seconds; if a host stops
|
||||||
|
answering, it is reverted on its own. Routes live in a git repository, one file per host, with Undo and a
|
||||||
|
history you can restore any kept version from.
|
||||||
|
- **Two engines.** Pingora serves; Caddy is built from the same routes, compared host by host, and can take over at
|
||||||
|
runtime in about two seconds.
|
||||||
|
- **The Domi CA.** Certificates for hosts reached only from home, and device certificates (mTLS) for phones,
|
||||||
|
computers and Domi apps, from an intermediate whose root stays offline.
|
||||||
|
- **Share links**, signed and time-limited, for a single host.
|
||||||
|
- **NixOS-native.** A flake with the module and VM tests; deployed through Fabrica.
|
||||||
|
|
||||||
|
The changes below are the merges since the first commit; PR 3 to 5 are the control plane (phase 2), the decisions
|
||||||
|
on the open points, and the web UI, the Domi CA and the NixOS module (phase 3).
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
Ianitor Domi now runs for any small team, not only on a NixOS server, and gives Fabrica a preview address for
|
||||||
|
every branch.
|
||||||
|
|
||||||
|
- **Install anywhere.** A one-line installer for Linux with systemd, a Docker image with a compose file, and
|
||||||
|
Windows Server, where Ianitor runs with Caddy as its engine (same screens, same route files; Pingora's Windows
|
||||||
|
support is still preliminary). The NixOS module stays.
|
||||||
|
- **Branch previews.** Fabrica asks for `<branch>--<project>.<your preview domain>` and gets it, with a certificate
|
||||||
|
from the Domi CA or Let's Encrypt; it closes when the branch is merged or its time runs out. Any branch name works:
|
||||||
|
unusual characters, dots and long names all become a safe address, and two branches never share one.
|
||||||
|
- **A token that can only do previews.** Fabrica's token opens and closes previews and nothing else, and previews
|
||||||
|
may only point where you allow, never at Ianitor's own admin ports.
|
||||||
|
- **Your team, without Authelia.** The installer prints a sign-in link for the first admin; admins invite the rest
|
||||||
|
with a link. Members change hosts and previews; admins also manage people, tokens, the engine and certificates.
|
||||||
|
Authelia still works where you have it.
|
||||||
|
- **Previews screen.** See every open preview in one click, close one in two.
|
||||||
|
- **Routes on any git host.** Push the routes repository to Gitea, GitHub or GitLab.
|
||||||
|
- **Tested on Windows too.** The comparison of Pingora and Caddy now also runs on Windows, with Windows paths.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
*.png binary
|
||||||
|
*.ico binary
|
||||||
Executable
+175
@@ -0,0 +1,175 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
#
|
||||||
|
# Ianitor pre-commit hook. Rejects staged files that must never be in git:
|
||||||
|
# - binaries: any NUL byte anywhere in the staged blob (git attributes do not matter)
|
||||||
|
# - private keys: PEM/PKCS#8/OpenSSH/PGP blocks, SSH2 (RFC 4716) keys, PuTTY .ppk,
|
||||||
|
# age secret keys, JWK private keys (an object with "kty" RSA/EC/OKP and "d"),
|
||||||
|
# WireGuard private keys (wg-quick `PrivateKey =` or YAML `private_key:`), and
|
||||||
|
# key-store file names
|
||||||
|
# - files over 5 MB (5,000,000 bytes, as CLAUDE.md says)
|
||||||
|
# - build output and dependencies: target/, node_modules/, dist/, .svelte-kit/ anywhere;
|
||||||
|
# build/ at the repository root, in apps/<app>/, or next to a package.json
|
||||||
|
# Name checks are case-insensitive. Paths are read NUL-separated, so quotes, tabs,
|
||||||
|
# backslashes or newlines in file names cannot slip past. A staged file that cannot be read,
|
||||||
|
# or any git command that fails, blocks the commit.
|
||||||
|
#
|
||||||
|
# Contents are checked in a few batch passes over the index (one `git cat-file`, two
|
||||||
|
# `git grep`), not with processes per file.
|
||||||
|
#
|
||||||
|
# Enable once per clone: git config core.hooksPath .githooks
|
||||||
|
# Test it: bash .githooks/test-pre-commit.sh
|
||||||
|
|
||||||
|
if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
|
||||||
|
echo "pre-commit: needs bash 4 or newer (this is ${BASH_VERSION:-not bash}); commit blocked." >&2
|
||||||
|
echo "pre-commit: use Git Bash on Windows, any Linux, or a newer bash on macOS." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
set -u
|
||||||
|
LIMIT=5000000
|
||||||
|
|
||||||
|
# Patterns are written so that this file does not match them itself. They are matched
|
||||||
|
# case-insensitively.
|
||||||
|
KEY_PATTERNS=(
|
||||||
|
'-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----'
|
||||||
|
'---- BEGIN SSH2 ENCRYPTED PRIVATE KEY[ ]----'
|
||||||
|
'---- BEGIN SSH2 PRIVATE KEY[ ]----'
|
||||||
|
'PuTTY-User-Key-File-[0-9]+:'
|
||||||
|
'AGE-SECRET-KEY-[1][0-9A-Z]+'
|
||||||
|
'^[[:space:]]*(-[[:space:]]*)?["'\'']?private_?key["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9+/]{42,43}=?["'\'']?[[:space:]]*,?[[:space:]]*$'
|
||||||
|
)
|
||||||
|
# One flat JSON object (JWK members are flat) holding a private-key parameter set.
|
||||||
|
JWK_OBJECT='\{[^{}]*\}'
|
||||||
|
JWK_KTY='"kt[y]"[[:space:]]*:[[:space:]]*"(RSA|EC|OKP)"'
|
||||||
|
JWK_D='"[d]"[[:space:]]*:[[:space:]]*"'
|
||||||
|
|
||||||
|
failed=0
|
||||||
|
reject() {
|
||||||
|
# %q keeps odd characters in names visible and harmless.
|
||||||
|
printf 'pre-commit: rejected %q: %s\n' "$1" "$2" >&2
|
||||||
|
failed=1
|
||||||
|
}
|
||||||
|
die() {
|
||||||
|
echo "pre-commit: $1; commit blocked." >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
tmp=$(mktemp -d 2>/dev/null || { d="${TMPDIR:-/tmp}/ianitor-pre-commit.$$"; mkdir -p "$d" && echo "$d"; }) ||
|
||||||
|
die "cannot create a temporary directory"
|
||||||
|
trap 'rm -rf "$tmp"' EXIT
|
||||||
|
|
||||||
|
git diff --cached --raw -z --no-abbrev --no-renames --diff-filter=ACMT >"$tmp/list" ||
|
||||||
|
die "cannot list the staged files"
|
||||||
|
git ls-files -z -- ':(glob)**/package.json' >"$tmp/packages" ||
|
||||||
|
die "cannot list package.json files"
|
||||||
|
|
||||||
|
declare -A staged=() pkgdir=()
|
||||||
|
paths=() shas=()
|
||||||
|
|
||||||
|
while IFS= read -r -d '' p; do
|
||||||
|
d=${p%package.json}
|
||||||
|
d=${d%/}
|
||||||
|
# The root package.json needs no entry: build/ at the root is always output.
|
||||||
|
[ -n "$d" ] && pkgdir[${d,,}]=1
|
||||||
|
done <"$tmp/packages"
|
||||||
|
|
||||||
|
# build/ is output only at the root, in apps/<app>/ or beside a package.json.
|
||||||
|
is_build_output() {
|
||||||
|
local lower=$1 prefix=
|
||||||
|
[[ $lower == build/* || $lower =~ ^apps/[^/]+/build/ ]] && return 0
|
||||||
|
local rest=$lower part
|
||||||
|
while [[ $rest == */* ]]; do
|
||||||
|
part=${rest%%/*}
|
||||||
|
rest=${rest#*/}
|
||||||
|
if [[ $part == build && -n $prefix && -n ${pkgdir[${prefix%/}]+x} ]]; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
prefix+="$part/"
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --raw -z gives ":<old mode> <new mode> <old sha> <new sha> <status>" NUL "<path>" NUL.
|
||||||
|
while IFS= read -r -d '' meta && IFS= read -r -d '' path; do
|
||||||
|
read -r -a f <<<"${meta#:}"
|
||||||
|
mode=${f[1]} sha=${f[3]}
|
||||||
|
lower=${path,,}
|
||||||
|
|
||||||
|
case "/$lower" in
|
||||||
|
*/target/*|*/node_modules/*|*/dist/*|*/.svelte-kit/*)
|
||||||
|
reject "$path" "build output or dependency directory" ;;
|
||||||
|
esac
|
||||||
|
if is_build_output "$lower"; then
|
||||||
|
reject "$path" "build output directory"
|
||||||
|
fi
|
||||||
|
|
||||||
|
base=${lower##*/}
|
||||||
|
case "$base" in
|
||||||
|
*.pub) ;;
|
||||||
|
*.key|*.p12|*.pfx|*.jks|*.keystore|*.ppk|id_rsa|id_dsa|id_ecdsa|id_ed25519|id_rsa.*|id_dsa.*|id_ecdsa.*|id_ed25519.*)
|
||||||
|
reject "$path" "private key file name" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# Submodule entries have no blob to inspect.
|
||||||
|
[ "$mode" = 160000 ] && continue
|
||||||
|
staged[$path]=$sha
|
||||||
|
paths+=("$path")
|
||||||
|
shas+=("$sha")
|
||||||
|
done <"$tmp/list"
|
||||||
|
|
||||||
|
if [ "${#paths[@]}" -gt 0 ]; then
|
||||||
|
# Sizes: one batch for every blob, in order.
|
||||||
|
printf '%s\n' "${shas[@]}" | git cat-file --batch-check='%(objectname) %(objecttype) %(objectsize)' >"$tmp/sizes" ||
|
||||||
|
die "cannot read the staged blobs"
|
||||||
|
i=0
|
||||||
|
while read -r _ type size; do
|
||||||
|
p=${paths[$i]}
|
||||||
|
if [ "$type" != blob ] || ! [[ $size =~ ^[0-9]+$ ]]; then
|
||||||
|
reject "$p" "the staged content cannot be read"
|
||||||
|
elif (( size > LIMIT )); then
|
||||||
|
reject "$p" "$size bytes is over the 5 MB limit (5,000,000 bytes)"
|
||||||
|
fi
|
||||||
|
i=$((i + 1))
|
||||||
|
done <"$tmp/sizes"
|
||||||
|
[ "$i" -eq "${#paths[@]}" ] || die "cannot read the size of every staged blob"
|
||||||
|
|
||||||
|
# Contents: git grep over the index, every file read as text (-a), names NUL-separated,
|
||||||
|
# then kept only when staged. Exit 1 means no match; anything above blocks the commit.
|
||||||
|
search() {
|
||||||
|
local out=$1 rc
|
||||||
|
shift
|
||||||
|
git -c grep.fullName=true -c color.grep=never grep --cached --no-recurse-submodules \
|
||||||
|
-a -l -z "$@" >"$out"
|
||||||
|
rc=$?
|
||||||
|
[ "$rc" -le 1 ] || die "git grep failed (exit $rc)"
|
||||||
|
}
|
||||||
|
|
||||||
|
search "$tmp/nul" -P '\x00'
|
||||||
|
while IFS= read -r -d '' p; do
|
||||||
|
[ -n "${staged[$p]+x}" ] && reject "$p" "binary file (contains NUL bytes)"
|
||||||
|
done <"$tmp/nul"
|
||||||
|
|
||||||
|
args=()
|
||||||
|
for pattern in "${KEY_PATTERNS[@]}"; do args+=(-e "$pattern"); done
|
||||||
|
search "$tmp/keys" -i -E "${args[@]}"
|
||||||
|
while IFS= read -r -d '' p; do
|
||||||
|
[ -n "${staged[$p]+x}" ] && reject "$p" "contains a private key"
|
||||||
|
done <"$tmp/keys"
|
||||||
|
|
||||||
|
# JWK members may span lines, so candidates are flattened and split into objects.
|
||||||
|
search "$tmp/jwk" -F -e '"kt''y"'
|
||||||
|
while IFS= read -r -d '' p; do
|
||||||
|
[ -n "${staged[$p]+x}" ] || continue
|
||||||
|
if git cat-file blob "${staged[$p]}" | tr '\r\n\t' ' ' | grep -a -o -E "$JWK_OBJECT" |
|
||||||
|
grep -a -E "$JWK_KTY" | grep -a -q -E "$JWK_D"; then
|
||||||
|
reject "$p" "contains a JWK private key"
|
||||||
|
fi
|
||||||
|
done <"$tmp/jwk"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$failed" -ne 0 ]; then
|
||||||
|
echo 'pre-commit: commit blocked. Unstage the files above (git rm --cached <file>).' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
exit 0
|
||||||
Executable
+255
@@ -0,0 +1,255 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-License-Identifier: MPL-2.0
|
||||||
|
#
|
||||||
|
# Self-test for .githooks/pre-commit. Creates a throw-away repository, points it at the
|
||||||
|
# hook and checks that every forbidden case is rejected and normal files are accepted.
|
||||||
|
# Includes every bypass QC found (odd file names, attributes, NULs late in a file, 5 MB
|
||||||
|
# boundary, other key formats). Usage: bash .githooks/test-pre-commit.sh (Git Bash or Linux)
|
||||||
|
|
||||||
|
set -u
|
||||||
|
HOOKS=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
WORK=$(mktemp -d 2>/dev/null || mktemp -d -t ianitor-hook)
|
||||||
|
trap 'rm -rf "$WORK"' EXIT INT TERM
|
||||||
|
|
||||||
|
cd "$WORK" || exit 2
|
||||||
|
git init -q .
|
||||||
|
git config user.name hook-test
|
||||||
|
git config user.email hook-test@invalid
|
||||||
|
git config core.hooksPath "$HOOKS"
|
||||||
|
git config core.autocrlf false
|
||||||
|
# Allow index entries Windows cannot check out ("quotes", tabs, backslashes) so the hook
|
||||||
|
# itself is what rejects them.
|
||||||
|
git config core.protectNTFS false
|
||||||
|
git commit -q --allow-empty -m base --no-gpg-sign
|
||||||
|
|
||||||
|
pass=0
|
||||||
|
fail=0
|
||||||
|
|
||||||
|
commit_and_check() {
|
||||||
|
local want=$1 what=$2 got
|
||||||
|
if git commit -q -m "$what" --no-gpg-sign >/dev/null 2>"$WORK/.err"; then
|
||||||
|
got=accept
|
||||||
|
elif grep -q 'pre-commit: rejected' "$WORK/.err"; then
|
||||||
|
got=reject
|
||||||
|
else
|
||||||
|
got="error ($(head -c 200 "$WORK/.err"))" # failed, but not because of the hook
|
||||||
|
fi
|
||||||
|
if [ "$got" = "$want" ]; then
|
||||||
|
pass=$((pass + 1)); printf 'ok %-7s %s\n' "$want" "$what"
|
||||||
|
else
|
||||||
|
fail=$((fail + 1)); printf 'FAIL wanted %s, got %s: %s\n' "$want" "$got" "$what"; cat "$WORK/.err"
|
||||||
|
fi
|
||||||
|
git reset -q --hard HEAD >/dev/null 2>&1
|
||||||
|
git clean -q -fdx -e .err >/dev/null 2>&1
|
||||||
|
}
|
||||||
|
|
||||||
|
# expect <accept|reject> <description> <path> (file must exist in the work tree)
|
||||||
|
expect() {
|
||||||
|
git add -f -- "$3"
|
||||||
|
commit_and_check "$1" "$2"
|
||||||
|
}
|
||||||
|
|
||||||
|
# expect_staged <accept|reject> <description> <path> <content file>
|
||||||
|
# Stages content under a path that may be impossible to create on this file system
|
||||||
|
# (quotes, tabs or backslashes in names on Windows).
|
||||||
|
expect_staged() {
|
||||||
|
local sha
|
||||||
|
sha=$(git hash-object -w -- "$4")
|
||||||
|
if ! git update-index --add --cacheinfo "100644,$sha,$3"; then
|
||||||
|
fail=$((fail + 1)); printf 'FAIL could not stage the test path: %s
|
||||||
|
' "$2"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
commit_and_check "$1" "$2"
|
||||||
|
}
|
||||||
|
|
||||||
|
B='-----BEGIN'
|
||||||
|
E='-----END'
|
||||||
|
# An absolute path next to $WORK (not "$WORK/..", which no longer resolves once $WORK is gone),
|
||||||
|
# removed first.
|
||||||
|
SRC="$(dirname "$WORK")/ianitor-hook-src.$$"
|
||||||
|
mkdir -p "$SRC" || exit 2
|
||||||
|
trap 'rm -rf "$SRC" "$WORK"' EXIT INT TERM
|
||||||
|
printf '%s RSA PRIVATE KEY-----\nMIIBOgIBAAJBAK\n%s RSA PRIVATE KEY-----\n' "$B" "$E" > "$SRC/pem"
|
||||||
|
head -c 6291456 /dev/zero | tr '\000' 'a' > "$SRC/six-mb"
|
||||||
|
|
||||||
|
printf 'hello\n' > readme.txt
|
||||||
|
expect accept "plain text file" readme.txt
|
||||||
|
|
||||||
|
printf 'fn main() {}\n' > main.rs
|
||||||
|
expect accept "source file" main.rs
|
||||||
|
|
||||||
|
printf '\000\001\002\003binary\000' > blob.bin
|
||||||
|
expect reject "binary file" blob.bin
|
||||||
|
|
||||||
|
{ head -c 10000 /dev/zero | tr '\000' 'a'; printf '\000tail'; } > late-nul.txt
|
||||||
|
expect reject "NUL byte after the first 8000 bytes" late-nul.txt
|
||||||
|
|
||||||
|
printf '*.dat diff\n' > .gitattributes
|
||||||
|
expect accept ".gitattributes marking *.dat as text" .gitattributes
|
||||||
|
printf 'abc\000def' > forced.dat
|
||||||
|
expect reject "binary file that .gitattributes calls text" forced.dat
|
||||||
|
|
||||||
|
cp "$SRC/pem" notes.txt
|
||||||
|
expect reject "PEM RSA private key in a .txt file" notes.txt
|
||||||
|
|
||||||
|
printf '%s PRIVATE KEY-----\nMIGHAgEAMBMG\n%s PRIVATE KEY-----\n' "$B" "$E" > pkcs8.pem
|
||||||
|
expect reject "PKCS#8 private key" pkcs8.pem
|
||||||
|
|
||||||
|
printf '%s ENCRYPTED PRIVATE KEY-----\nMIIFHDBOBgkq\n%s ENCRYPTED PRIVATE KEY-----\n' "$B" "$E" > enc.pem
|
||||||
|
expect reject "encrypted PKCS#8 private key" enc.pem
|
||||||
|
|
||||||
|
printf '%s EC PRIVATE KEY-----\nMHcCAQEEI\n%s EC PRIVATE KEY-----\n' "$B" "$E" > ec.txt
|
||||||
|
expect reject "EC private key" ec.txt
|
||||||
|
|
||||||
|
printf '%s OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA\n%s OPENSSH PRIVATE KEY-----\n' "$B" "$E" > deploy
|
||||||
|
expect reject "OpenSSH private key" deploy
|
||||||
|
|
||||||
|
printf -- '---- BEGIN SSH2 ENCRYPTED PRIVATE %s ----\nP2/56wAAA\n' KEY > ssh2.txt
|
||||||
|
expect reject "SSH2 (RFC 4716) encrypted private key" ssh2.txt
|
||||||
|
|
||||||
|
printf 'PuTTY-User-Key-File-%s: ssh-ed25519\nEncryption: none\n' 3 > putty.txt
|
||||||
|
expect reject "PuTTY private key content" putty.txt
|
||||||
|
|
||||||
|
printf 'not really a key\n' > me.ppk
|
||||||
|
expect reject "*.ppk file name" me.ppk
|
||||||
|
|
||||||
|
printf '# created: 2026\nage-secret-key-%s\n' 1qyz8xrfk3w6j9p2m4n5l7kxqzj5s8tvh3r2w6y9 > lower.txt
|
||||||
|
expect reject "age secret key in lower case" lower.txt
|
||||||
|
|
||||||
|
printf '# created: 2026\nAGE-SECRET-KEY-%s\n' 1QYZ8XRFK3W6J9P2M4N5L7KXQZJ5S8TVH3R2W6Y9 > identity.txt
|
||||||
|
expect reject "age secret key" identity.txt
|
||||||
|
|
||||||
|
printf '{"k%s":"EC","crv":"P-256","x":"f83O","y":"x_FE","d":"jpsQ"}\n' ty > key.json
|
||||||
|
expect reject "JWK private key" key.json
|
||||||
|
|
||||||
|
printf '{"k%s":"EC","crv":"P-256","x":"f83O","y":"x_FE"}\n' ty > pub.json
|
||||||
|
expect accept "JWK public key" pub.json
|
||||||
|
|
||||||
|
printf '{\n "k%s"\n : "RSA",\n "n": "0vx7",\n "e": "AQAB",\n "d"\n :\n "X4cT"\n}\n' ty > rsa.json
|
||||||
|
expect reject "JWK private key across lines, newline before the colon" rsa.json
|
||||||
|
|
||||||
|
printf '{"keys":[{"k%s":"OKP","crv":"Ed25519","x":"11qY","d":"nWGx"}]}\n' ty > jwks.json
|
||||||
|
expect reject "OKP private key inside a JWKS" jwks.json
|
||||||
|
|
||||||
|
printf '{"jwk":{"k%s":"EC","x":"f83O","y":"x_FE"},"meta":{"d":"2026-11-07"}}\n' ty > mixed.json
|
||||||
|
expect accept "JWK public key with an unrelated \"d\" in another object" mixed.json
|
||||||
|
|
||||||
|
printf '{"k%s":"oct","k":"GawgguFy","d":"not a private-key parameter"}\n' ty > oct.json
|
||||||
|
expect accept "\"d\" with kty oct is not an RSA/EC/OKP private key" oct.json
|
||||||
|
|
||||||
|
printf '[Interface]\nPrivate%s = %s\nAddress = 10.0.0.2/32\n' Key yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= > wg0.conf
|
||||||
|
expect reject "WireGuard private key" wg0.conf
|
||||||
|
|
||||||
|
printf 'wireguard:\n interface:\n private_%s: yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\n' key > wg.yaml
|
||||||
|
expect reject "WireGuard private_key in YAML" wg.yaml
|
||||||
|
|
||||||
|
printf 'peers:\n - private_%s: "yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk="\n' key > wg2.yml
|
||||||
|
expect reject "WireGuard private_key in a YAML list, quoted" wg2.yml
|
||||||
|
|
||||||
|
printf 'private_%s_file: /run/secrets/wg\n' key > wg3.yaml
|
||||||
|
expect accept "WireGuard private_key_file path (no key)" wg3.yaml
|
||||||
|
|
||||||
|
printf '*.txt binary\n' > .gitattributes && cp "$SRC/pem" attr.txt && git add .gitattributes
|
||||||
|
expect reject "PEM key in a file .gitattributes marks binary" attr.txt
|
||||||
|
|
||||||
|
printf 'not really a key\n' > server.key
|
||||||
|
expect reject "*.key file name" server.key
|
||||||
|
|
||||||
|
printf 'not really a key\n' > SERVER.KEY
|
||||||
|
expect reject "*.KEY file name in upper case" SERVER.KEY
|
||||||
|
|
||||||
|
printf 'not really a key\n' > id_ed25519
|
||||||
|
expect reject "id_ed25519 file name" id_ed25519
|
||||||
|
|
||||||
|
printf 'ssh-ed25519 AAAAC3Nza test\n' > id_ed25519.pub
|
||||||
|
expect accept "public key id_ed25519.pub" id_ed25519.pub
|
||||||
|
|
||||||
|
printf '%s CERTIFICATE-----\nMIIBszCCAVmg\n%s CERTIFICATE-----\n' "$B" "$E" > cert.pem
|
||||||
|
expect accept "certificate (public) PEM" cert.pem
|
||||||
|
|
||||||
|
cp "$SRC/six-mb" big.txt
|
||||||
|
expect reject "6 MB text file" big.txt
|
||||||
|
|
||||||
|
head -c 5000001 /dev/zero | tr '\000' 'a' > over.txt
|
||||||
|
expect reject "5,000,001 bytes" over.txt
|
||||||
|
|
||||||
|
head -c 5242880 /dev/zero | tr '\000' 'a' > mib.txt
|
||||||
|
expect reject "5 MiB (5,242,880 bytes)" mib.txt
|
||||||
|
|
||||||
|
head -c 5000000 /dev/zero | tr '\000' 'a' > exact.txt
|
||||||
|
expect accept "exactly 5,000,000 bytes" exact.txt
|
||||||
|
|
||||||
|
mkdir -p crates/x/target/debug && printf 'x\n' > crates/x/target/debug/out.txt
|
||||||
|
expect reject "file under target/" crates/x/target/debug/out.txt
|
||||||
|
|
||||||
|
mkdir -p TARGET && printf 'x\n' > TARGET/out.txt
|
||||||
|
expect reject "file under TARGET/ (upper case)" TARGET/out.txt
|
||||||
|
|
||||||
|
mkdir -p apps/web/node_modules/pkg && printf 'x\n' > apps/web/node_modules/pkg/index.js
|
||||||
|
expect reject "file under node_modules/" apps/web/node_modules/pkg/index.js
|
||||||
|
|
||||||
|
mkdir -p apps/web/dist && printf 'x\n' > apps/web/dist/index.html
|
||||||
|
expect reject "file under dist/" apps/web/dist/index.html
|
||||||
|
|
||||||
|
mkdir -p apps/web/build && printf 'x\n' > apps/web/build/index.html
|
||||||
|
expect reject "file under apps/<app>/build/" apps/web/build/index.html
|
||||||
|
|
||||||
|
mkdir -p build && printf 'x\n' > build/out.js
|
||||||
|
expect reject "file under build/ at the root" build/out.js
|
||||||
|
|
||||||
|
mkdir -p crates/x/src/build && printf 'pub mod x;\n' > crates/x/src/build/mod.rs
|
||||||
|
expect accept "source module named build (crates/x/src/build/mod.rs)" crates/x/src/build/mod.rs
|
||||||
|
|
||||||
|
mkdir -p apps/web/src/build && printf 'x\n' > apps/web/src/build/x.ts
|
||||||
|
expect accept "apps/web/src/build/ is not output" apps/web/src/build/x.ts
|
||||||
|
|
||||||
|
mkdir -p packages/ui/build && printf '{}\n' > packages/ui/package.json && printf 'x\n' > packages/ui/build/ui.js
|
||||||
|
git add packages/ui/package.json
|
||||||
|
expect reject "build/ next to a package.json" packages/ui/build/ui.js
|
||||||
|
|
||||||
|
mkdir -p docs/build && printf 'x\n' > docs/build/notes.md
|
||||||
|
expect accept "build/ with no package.json beside it" docs/build/notes.md
|
||||||
|
|
||||||
|
mkdir -p apps/web/.svelte-kit && printf 'x\n' > apps/web/.svelte-kit/env.js
|
||||||
|
expect reject "file under .svelte-kit/" apps/web/.svelte-kit/env.js
|
||||||
|
|
||||||
|
# Names git would C-quote: only reachable through the index on Windows.
|
||||||
|
expect_staged reject "PEM key in a file named with a double quote" 'a"b.txt' "$SRC/pem"
|
||||||
|
expect_staged reject "PEM key in a file named with a tab" "$(printf 'tab\tx.txt')" "$SRC/pem"
|
||||||
|
expect_staged reject "6 MB file named with a backslash" 'big\file.txt' "$SRC/six-mb"
|
||||||
|
expect_staged reject "*.key named with a backslash" 'srv\x.key' "$SRC/pem"
|
||||||
|
expect_staged reject "PEM key in a file named with a newline" "$(printf 'new\nline.txt')" "$SRC/pem"
|
||||||
|
printf 'fine\n' > "$SRC/fine"
|
||||||
|
expect_staged accept "harmless file named with a double quote" 'say"hi".txt' "$SRC/fine"
|
||||||
|
|
||||||
|
# Bash 3 or a POSIX sh: the hook refuses with a clear message. Only testable where sh is
|
||||||
|
# not bash (dash on Debian); Git Bash's sh is bash.
|
||||||
|
if [ -z "$(sh -c 'echo "${BASH_VERSION:-}"')" ]; then
|
||||||
|
printf 'x\n' > shtest.txt && git add shtest.txt
|
||||||
|
if sh "$HOOKS/pre-commit" 2>"$WORK/.err"; then
|
||||||
|
fail=$((fail + 1)); echo "FAIL the hook ran under a shell that is not bash 4"
|
||||||
|
elif grep -q 'needs bash 4' "$WORK/.err"; then
|
||||||
|
pass=$((pass + 1)); echo "ok reject run by sh (not bash): clear message"
|
||||||
|
else
|
||||||
|
fail=$((fail + 1)); echo "FAIL no clear message under sh:"; cat "$WORK/.err"
|
||||||
|
fi
|
||||||
|
git reset -q --hard HEAD; git clean -q -fdx -e .err
|
||||||
|
else
|
||||||
|
echo "skip sh is bash here; the bash-4 check is exercised where sh is dash"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Speed: 300 ordinary files in one commit.
|
||||||
|
mkdir -p many
|
||||||
|
for n in $(seq 1 300); do printf 'line %d\n' "$n" > "many/f$n.txt"; done
|
||||||
|
git add many
|
||||||
|
start=$(date +%s%N)
|
||||||
|
commit_and_check accept "300 ordinary files in one commit"
|
||||||
|
ms=$(( ($(date +%s%N) - start) / 1000000 ))
|
||||||
|
printf ' (300 files: %d ms)\n' "$ms"
|
||||||
|
if [ "$ms" -gt 10000 ]; then
|
||||||
|
fail=$((fail + 1)); echo "FAIL 300 files took over 10 s"
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '\nhook: %d passed, %d failed\n' "$pass" "$fail"
|
||||||
|
[ "$fail" -eq 0 ]
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
# Build output
|
||||||
|
target/
|
||||||
|
dist/
|
||||||
|
result
|
||||||
|
result-*
|
||||||
|
|
||||||
|
# JavaScript
|
||||||
|
node_modules/
|
||||||
|
.svelte-kit/
|
||||||
|
.pnpm-store/
|
||||||
|
|
||||||
|
# Private keys and key stores (never committed; the pre-commit hook also blocks them)
|
||||||
|
*.key
|
||||||
|
*.p12
|
||||||
|
*.pfx
|
||||||
|
*.jks
|
||||||
|
*.keystore
|
||||||
|
id_rsa*
|
||||||
|
id_ed25519*
|
||||||
|
id_ecdsa*
|
||||||
|
|
||||||
|
# Local secrets and state
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
credentials/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Editors and OS
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -4,34 +4,51 @@ Ianitor is a reverse proxy built on Cloudflare's Pingora, with a small Domi CA,
|
|||||||
NixOS-native, with Caddy as a tested fallback. MPL-2.0. Plan, decisions and status: docs/ROADMAP.md — read it first.
|
NixOS-native, with Caddy as a tested fallback. MPL-2.0. Plan, decisions and status: docs/ROADMAP.md — read it first.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
crates/core config model, schema, compilers (Pingora runtime + Caddy JSON), CA. Pure: no I/O, no network.
|
crates/core config model, schema, compilers (Pingora runtime + Caddy JSON), CA (Ianitor's view of the shared
|
||||||
|
crate domi-pki, pinned by tag). Pure: no I/O, no network.
|
||||||
crates/edge Pingora data plane. Reads compiled config, serves traffic. Never decides policy.
|
crates/edge Pingora data plane. Reads compiled config, serves traffic. Never decides policy.
|
||||||
crates/control API, git routes repo, apply/rollback, share links, PKI flows. Loopback only. Never serves public traffic.
|
crates/control API, git routes repo, apply/rollback, share links, PKI flows. Loopback only. Never serves public traffic.
|
||||||
apps/web Svelte 5 (runes, TypeScript strict). A client of the API; no logic.
|
apps/web Svelte 5 (runes, TypeScript strict). A client of the API; no logic.
|
||||||
packages/ui shared dark Domi theme.
|
packages/ui shared dark Domi theme, murex palette.
|
||||||
tests/diff same requests against Ianitor and Caddy, responses compared.
|
tests/diff same requests against Ianitor and Caddy, responses compared.
|
||||||
|
tests/support shared test fixtures (test CA, upstreams, mock Authelia, clients); test-only.
|
||||||
tests/fuzz cargo-fuzz targets.
|
tests/fuzz cargo-fuzz targets.
|
||||||
deploy/nixos NixOS module + VM tests.
|
deploy/nixos NixOS module + VM tests.
|
||||||
|
deploy/docker the image (edge + control), compose file, the Linux CI image (target ci). deploy/linux: installer,
|
||||||
|
systemd units. deploy/windows: Windows Server installer (Caddy mode). docs/deploy/anywhere.md.
|
||||||
|
scripts the release's version check. Releases (notes, screenshots): docs/release.md.
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
cargo test --workspace # quote test counts per crate; an exit code alone is not green
|
cargo test --workspace # quote test counts per crate; an exit code alone is not green
|
||||||
|
docker build --load -f deploy/docker/Dockerfile --target ci -t ianitor-ci . && docker run --rm --memory 6g ianitor-ci cargo test --workspace --locked -j 2 # Linux, all suites
|
||||||
cargo run -p ianitor-control -- --dev
|
cargo run -p ianitor-control -- --dev
|
||||||
pnpm --filter web dev # 127.0.0.1 only, never --host
|
pnpm --filter web dev # 127.0.0.1 only, never --host
|
||||||
|
node apps/web/scripts/shots.mjs # the release's screenshots (demo data, headless Edge) -> target/aula (docs/release.md)
|
||||||
|
node scripts/check-version.mjs X.Y.Z # Cargo.toml and both package.json carry the version
|
||||||
nix build .#ianitor
|
nix build .#ianitor
|
||||||
nix flake check # includes NixOS VM tests (Linux + KVM)
|
nix flake check # includes NixOS VM tests (Linux + KVM)
|
||||||
|
|
||||||
|
On Windows, build and test in WSL2 Debian (ROADMAP §8.3: Pingora's Windows support is best effort; edge, diff and
|
||||||
|
ACME tests are Linux-only). Use a Linux target dir, and put caddy, pebble and pebble-challtestsrv on PATH (`nix profile add nixpkgs#caddy nixpkgs#pebble`):
|
||||||
|
wsl -d Debian -- bash -lc 'cd /mnt/f/Akce/Ianitor && CARGO_TARGET_DIR=$HOME/ianitor-target cargo test --workspace'
|
||||||
|
One-time per clone: git config core.hooksPath .githooks (self-test: bash .githooks/test-pre-commit.sh)
|
||||||
|
|
||||||
## Rules
|
## Rules
|
||||||
- Commits: `[<crate|app>] <Feature>: <one line>`. No AI attribution, no trailers, ever.
|
- Commits: `[<crate|app>] <Feature>: <one line>`. No AI attribution, no trailers, ever.
|
||||||
- Never in git: target/, node_modules/, dist/, binaries, private keys, files over 5 MB. A pre-commit hook enforces it.
|
- Never in git: target/, node_modules/, dist/, binaries, private keys, files over 5 MB. A pre-commit hook enforces it.
|
||||||
- $GITEA_TOKEN never echoed or written anywhere. Secrets come only from Custos or systemd credentials, never the Nix store.
|
- $GITEA_TOKEN never echoed or written anywhere. Secrets come only from Custos or systemd credentials, never the Nix store.
|
||||||
- ianitor-control and every dev server listen on 127.0.0.1 only; only ianitor-edge binds public ports.
|
- ianitor-control and every dev server listen on 127.0.0.1 only; only ianitor-edge binds public ports.
|
||||||
|
- Disks (Mark's machine): never write, move or delete anything on C:, and nothing on D: either. Everything goes on F:
|
||||||
|
(build output, clones, caches, temp files, tools, WSL swap), under F:\C-Drive-Migration when it replaces a C: path.
|
||||||
|
The only file kept on C: is C:\Users\chode\.wslconfig (WSL reads it only there; it points swap to F:). Every agent's
|
||||||
|
brief repeats this rule.
|
||||||
- Route files, API bodies, CSRs, headers and share tokens are hostile input: typed Result, no unwrap() on input paths, no swallowed errors.
|
- Route files, API bodies, CSRs, headers and share tokens are hostile input: typed Result, no unwrap() on input paths, no swallowed errors.
|
||||||
- Every route change goes through the core compiler and the differential tests.
|
- Every route change goes through the core compiler and the differential tests.
|
||||||
- Tests first only where the risk is: parsing, CA, share tokens, forward-auth, apply/rollback, secret injection.
|
- Tests first only where the risk is: parsing, CA, share tokens, forward-auth, apply/rollback, secret injection.
|
||||||
- Workflow: branch → Gitea PR via API → short adversarial self-review in the PR body → merge --no-ff → push → verify hashes.
|
- Workflow: branch → Gitea PR via API → short adversarial self-review in the PR body → merge --no-ff → push → verify hashes.
|
||||||
- Server changes: prepare the Nix change and show the command; Mark runs nixos-rebuild himself. deploy/test-access.sh must pass.
|
- Server changes: prepare the Nix change and show the command; Mark runs nixos-rebuild himself. deploy/test-access.sh must pass.
|
||||||
- When reporting done, say which build is deployed and whether it changed visibly.
|
- When reporting done, say which build is deployed and whether it changed visibly.
|
||||||
- UI: dark Domi theme, every action ≤ 3 clicks, plain English; Latin only in the brand name.
|
- UI: dark Domi theme, murex palette; every action ≤ 3 clicks, plain English; Latin only in the brand name.
|
||||||
|
|
||||||
## Session end
|
## Session end
|
||||||
Update the Status table and the Handover section at the bottom of docs/ROADMAP.md. No separate handover file.
|
Update the Status table and the Handover section at the bottom of docs/ROADMAP.md. No separate handover file.
|
||||||
|
|||||||
Generated
+3896
File diff suppressed because it is too large
Load Diff
+51
@@ -0,0 +1,51 @@
|
|||||||
|
[workspace]
|
||||||
|
resolver = "3"
|
||||||
|
members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"]
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
version = "0.2.0"
|
||||||
|
edition = "2024"
|
||||||
|
rust-version = "1.89"
|
||||||
|
license = "MPL-2.0"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[workspace.dependencies]
|
||||||
|
ianitor-core = { path = "crates/core" }
|
||||||
|
ianitor-edge = { path = "crates/edge" }
|
||||||
|
ianitor-testkit = { path = "tests/support" }
|
||||||
|
# The Domi CA, shared with Fabrica (docs/32_coherence.md T3a); pinned by tag.
|
||||||
|
domi-pki = { git = "https://gitea.marek-novak.cz/mnovak/domi-pki", tag = "v1.0.0" }
|
||||||
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
|
serde_json = "1.0.145"
|
||||||
|
toml = "1.2.1"
|
||||||
|
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"
|
||||||
|
log = { version = "0.4.28", features = ["std"] }
|
||||||
|
async-trait = "0.1.89"
|
||||||
|
rustls = { version = "0.23.31", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||||
|
rustls-pki-types = "1.12"
|
||||||
|
tokio-rustls = { version = "0.26.4", default-features = false, features = ["ring", "tls12", "logging"] }
|
||||||
|
hyper = { version = "1.7", features = ["http1", "client", "server"] }
|
||||||
|
hyper-util = { version = "0.1.17", features = ["tokio"] }
|
||||||
|
http-body-util = "0.1.3"
|
||||||
|
rcgen = { version = "0.14.5", default-features = false, features = ["ring", "pem", "crypto"] }
|
||||||
|
tokio-tungstenite = "0.29.0"
|
||||||
|
futures-util = { version = "0.3.31", default-features = false, features = ["sink", "std"] }
|
||||||
|
|
||||||
|
[workspace.lints.rust]
|
||||||
|
unsafe_code = "forbid"
|
||||||
|
|
||||||
|
[workspace.lints.clippy]
|
||||||
|
# Hostile input never meets unwrap(): non-test code must handle every Result.
|
||||||
|
unwrap_used = "deny"
|
||||||
|
expect_used = "deny"
|
||||||
|
panic = "deny"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
lto = "thin"
|
||||||
|
codegen-units = 1
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
Mozilla Public License Version 2.0
|
||||||
|
==================================
|
||||||
|
|
||||||
|
1. Definitions
|
||||||
|
--------------
|
||||||
|
|
||||||
|
1.1. "Contributor"
|
||||||
|
means each individual or legal entity that creates, contributes to
|
||||||
|
the creation of, or owns Covered Software.
|
||||||
|
|
||||||
|
1.2. "Contributor Version"
|
||||||
|
means the combination of the Contributions of others (if any) used
|
||||||
|
by a Contributor and that particular Contributor's Contribution.
|
||||||
|
|
||||||
|
1.3. "Contribution"
|
||||||
|
means Covered Software of a particular Contributor.
|
||||||
|
|
||||||
|
1.4. "Covered Software"
|
||||||
|
means Source Code Form to which the initial Contributor has attached
|
||||||
|
the notice in Exhibit A, the Executable Form of such Source Code
|
||||||
|
Form, and Modifications of such Source Code Form, in each case
|
||||||
|
including portions thereof.
|
||||||
|
|
||||||
|
1.5. "Incompatible With Secondary Licenses"
|
||||||
|
means
|
||||||
|
|
||||||
|
(a) that the initial Contributor has attached the notice described
|
||||||
|
in Exhibit B to the Covered Software; or
|
||||||
|
|
||||||
|
(b) that the Covered Software was made available under the terms of
|
||||||
|
version 1.1 or earlier of the License, but not also under the
|
||||||
|
terms of a Secondary License.
|
||||||
|
|
||||||
|
1.6. "Executable Form"
|
||||||
|
means any form of the work other than Source Code Form.
|
||||||
|
|
||||||
|
1.7. "Larger Work"
|
||||||
|
means a work that combines Covered Software with other material, in
|
||||||
|
a separate file or files, that is not Covered Software.
|
||||||
|
|
||||||
|
1.8. "License"
|
||||||
|
means this document.
|
||||||
|
|
||||||
|
1.9. "Licensable"
|
||||||
|
means having the right to grant, to the maximum extent possible,
|
||||||
|
whether at the time of the initial grant or subsequently, any and
|
||||||
|
all of the rights conveyed by this License.
|
||||||
|
|
||||||
|
1.10. "Modifications"
|
||||||
|
means any of the following:
|
||||||
|
|
||||||
|
(a) any file in Source Code Form that results from an addition to,
|
||||||
|
deletion from, or modification of the contents of Covered
|
||||||
|
Software; or
|
||||||
|
|
||||||
|
(b) any new file in Source Code Form that contains any Covered
|
||||||
|
Software.
|
||||||
|
|
||||||
|
1.11. "Patent Claims" of a Contributor
|
||||||
|
means any patent claim(s), including without limitation, method,
|
||||||
|
process, and apparatus claims, in any patent Licensable by such
|
||||||
|
Contributor that would be infringed, but for the grant of the
|
||||||
|
License, by the making, using, selling, offering for sale, having
|
||||||
|
made, import, or transfer of either its Contributions or its
|
||||||
|
Contributor Version.
|
||||||
|
|
||||||
|
1.12. "Secondary License"
|
||||||
|
means either the GNU General Public License, Version 2.0, the GNU
|
||||||
|
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||||
|
Public License, Version 3.0, or any later versions of those
|
||||||
|
licenses.
|
||||||
|
|
||||||
|
1.13. "Source Code Form"
|
||||||
|
means the form of the work preferred for making modifications.
|
||||||
|
|
||||||
|
1.14. "You" (or "Your")
|
||||||
|
means an individual or a legal entity exercising rights under this
|
||||||
|
License. For legal entities, "You" includes any entity that
|
||||||
|
controls, is controlled by, or is under common control with You. For
|
||||||
|
purposes of this definition, "control" means (a) the power, direct
|
||||||
|
or indirect, to cause the direction or management of such entity,
|
||||||
|
whether by contract or otherwise, or (b) ownership of more than
|
||||||
|
fifty percent (50%) of the outstanding shares or beneficial
|
||||||
|
ownership of such entity.
|
||||||
|
|
||||||
|
2. License Grants and Conditions
|
||||||
|
--------------------------------
|
||||||
|
|
||||||
|
2.1. Grants
|
||||||
|
|
||||||
|
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||||
|
non-exclusive license:
|
||||||
|
|
||||||
|
(a) under intellectual property rights (other than patent or trademark)
|
||||||
|
Licensable by such Contributor to use, reproduce, make available,
|
||||||
|
modify, display, perform, distribute, and otherwise exploit its
|
||||||
|
Contributions, either on an unmodified basis, with Modifications, or
|
||||||
|
as part of a Larger Work; and
|
||||||
|
|
||||||
|
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||||
|
for sale, have made, import, and otherwise transfer either its
|
||||||
|
Contributions or its Contributor Version.
|
||||||
|
|
||||||
|
2.2. Effective Date
|
||||||
|
|
||||||
|
The licenses granted in Section 2.1 with respect to any Contribution
|
||||||
|
become effective for each Contribution on the date the Contributor first
|
||||||
|
distributes such Contribution.
|
||||||
|
|
||||||
|
2.3. Limitations on Grant Scope
|
||||||
|
|
||||||
|
The licenses granted in this Section 2 are the only rights granted under
|
||||||
|
this License. No additional rights or licenses will be implied from the
|
||||||
|
distribution or licensing of Covered Software under this License.
|
||||||
|
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||||
|
Contributor:
|
||||||
|
|
||||||
|
(a) for any code that a Contributor has removed from Covered Software;
|
||||||
|
or
|
||||||
|
|
||||||
|
(b) for infringements caused by: (i) Your and any other third party's
|
||||||
|
modifications of Covered Software, or (ii) the combination of its
|
||||||
|
Contributions with other software (except as part of its Contributor
|
||||||
|
Version); or
|
||||||
|
|
||||||
|
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||||
|
its Contributions.
|
||||||
|
|
||||||
|
This License does not grant any rights in the trademarks, service marks,
|
||||||
|
or logos of any Contributor (except as may be necessary to comply with
|
||||||
|
the notice requirements in Section 3.4).
|
||||||
|
|
||||||
|
2.4. Subsequent Licenses
|
||||||
|
|
||||||
|
No Contributor makes additional grants as a result of Your choice to
|
||||||
|
distribute the Covered Software under a subsequent version of this
|
||||||
|
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||||
|
permitted under the terms of Section 3.3).
|
||||||
|
|
||||||
|
2.5. Representation
|
||||||
|
|
||||||
|
Each Contributor represents that the Contributor believes its
|
||||||
|
Contributions are its original creation(s) or it has sufficient rights
|
||||||
|
to grant the rights to its Contributions conveyed by this License.
|
||||||
|
|
||||||
|
2.6. Fair Use
|
||||||
|
|
||||||
|
This License is not intended to limit any rights You have under
|
||||||
|
applicable copyright doctrines of fair use, fair dealing, or other
|
||||||
|
equivalents.
|
||||||
|
|
||||||
|
2.7. Conditions
|
||||||
|
|
||||||
|
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||||
|
in Section 2.1.
|
||||||
|
|
||||||
|
3. Responsibilities
|
||||||
|
-------------------
|
||||||
|
|
||||||
|
3.1. Distribution of Source Form
|
||||||
|
|
||||||
|
All distribution of Covered Software in Source Code Form, including any
|
||||||
|
Modifications that You create or to which You contribute, must be under
|
||||||
|
the terms of this License. You must inform recipients that the Source
|
||||||
|
Code Form of the Covered Software is governed by the terms of this
|
||||||
|
License, and how they can obtain a copy of this License. You may not
|
||||||
|
attempt to alter or restrict the recipients' rights in the Source Code
|
||||||
|
Form.
|
||||||
|
|
||||||
|
3.2. Distribution of Executable Form
|
||||||
|
|
||||||
|
If You distribute Covered Software in Executable Form then:
|
||||||
|
|
||||||
|
(a) such Covered Software must also be made available in Source Code
|
||||||
|
Form, as described in Section 3.1, and You must inform recipients of
|
||||||
|
the Executable Form how they can obtain a copy of such Source Code
|
||||||
|
Form by reasonable means in a timely manner, at a charge no more
|
||||||
|
than the cost of distribution to the recipient; and
|
||||||
|
|
||||||
|
(b) You may distribute such Executable Form under the terms of this
|
||||||
|
License, or sublicense it under different terms, provided that the
|
||||||
|
license for the Executable Form does not attempt to limit or alter
|
||||||
|
the recipients' rights in the Source Code Form under this License.
|
||||||
|
|
||||||
|
3.3. Distribution of a Larger Work
|
||||||
|
|
||||||
|
You may create and distribute a Larger Work under terms of Your choice,
|
||||||
|
provided that You also comply with the requirements of this License for
|
||||||
|
the Covered Software. If the Larger Work is a combination of Covered
|
||||||
|
Software with a work governed by one or more Secondary Licenses, and the
|
||||||
|
Covered Software is not Incompatible With Secondary Licenses, this
|
||||||
|
License permits You to additionally distribute such Covered Software
|
||||||
|
under the terms of such Secondary License(s), so that the recipient of
|
||||||
|
the Larger Work may, at their option, further distribute the Covered
|
||||||
|
Software under the terms of either this License or such Secondary
|
||||||
|
License(s).
|
||||||
|
|
||||||
|
3.4. Notices
|
||||||
|
|
||||||
|
You may not remove or alter the substance of any license notices
|
||||||
|
(including copyright notices, patent notices, disclaimers of warranty,
|
||||||
|
or limitations of liability) contained within the Source Code Form of
|
||||||
|
the Covered Software, except that You may alter any license notices to
|
||||||
|
the extent required to remedy known factual inaccuracies.
|
||||||
|
|
||||||
|
3.5. Application of Additional Terms
|
||||||
|
|
||||||
|
You may choose to offer, and to charge a fee for, warranty, support,
|
||||||
|
indemnity or liability obligations to one or more recipients of Covered
|
||||||
|
Software. However, You may do so only on Your own behalf, and not on
|
||||||
|
behalf of any Contributor. You must make it absolutely clear that any
|
||||||
|
such warranty, support, indemnity, or liability obligation is offered by
|
||||||
|
You alone, and You hereby agree to indemnify every Contributor for any
|
||||||
|
liability incurred by such Contributor as a result of warranty, support,
|
||||||
|
indemnity or liability terms You offer. You may include additional
|
||||||
|
disclaimers of warranty and limitations of liability specific to any
|
||||||
|
jurisdiction.
|
||||||
|
|
||||||
|
4. Inability to Comply Due to Statute or Regulation
|
||||||
|
---------------------------------------------------
|
||||||
|
|
||||||
|
If it is impossible for You to comply with any of the terms of this
|
||||||
|
License with respect to some or all of the Covered Software due to
|
||||||
|
statute, judicial order, or regulation then You must: (a) comply with
|
||||||
|
the terms of this License to the maximum extent possible; and (b)
|
||||||
|
describe the limitations and the code they affect. Such description must
|
||||||
|
be placed in a text file included with all distributions of the Covered
|
||||||
|
Software under this License. Except to the extent prohibited by statute
|
||||||
|
or regulation, such description must be sufficiently detailed for a
|
||||||
|
recipient of ordinary skill to be able to understand it.
|
||||||
|
|
||||||
|
5. Termination
|
||||||
|
--------------
|
||||||
|
|
||||||
|
5.1. The rights granted under this License will terminate automatically
|
||||||
|
if You fail to comply with any of its terms. However, if You become
|
||||||
|
compliant, then the rights granted under this License from a particular
|
||||||
|
Contributor are reinstated (a) provisionally, unless and until such
|
||||||
|
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||||
|
ongoing basis, if such Contributor fails to notify You of the
|
||||||
|
non-compliance by some reasonable means prior to 60 days after You have
|
||||||
|
come back into compliance. Moreover, Your grants from a particular
|
||||||
|
Contributor are reinstated on an ongoing basis if such Contributor
|
||||||
|
notifies You of the non-compliance by some reasonable means, this is the
|
||||||
|
first time You have received notice of non-compliance with this License
|
||||||
|
from such Contributor, and You become compliant prior to 30 days after
|
||||||
|
Your receipt of the notice.
|
||||||
|
|
||||||
|
5.2. If You initiate litigation against any entity by asserting a patent
|
||||||
|
infringement claim (excluding declaratory judgment actions,
|
||||||
|
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||||
|
directly or indirectly infringes any patent, then the rights granted to
|
||||||
|
You by any and all Contributors for the Covered Software under Section
|
||||||
|
2.1 of this License shall terminate.
|
||||||
|
|
||||||
|
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||||
|
end user license agreements (excluding distributors and resellers) which
|
||||||
|
have been validly granted by You or Your distributors under this License
|
||||||
|
prior to termination shall survive termination.
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 6. Disclaimer of Warranty *
|
||||||
|
* ------------------------- *
|
||||||
|
* *
|
||||||
|
* Covered Software is provided under this License on an "as is" *
|
||||||
|
* basis, without warranty of any kind, either expressed, implied, or *
|
||||||
|
* statutory, including, without limitation, warranties that the *
|
||||||
|
* Covered Software is free of defects, merchantable, fit for a *
|
||||||
|
* particular purpose or non-infringing. The entire risk as to the *
|
||||||
|
* quality and performance of the Covered Software is with You. *
|
||||||
|
* Should any Covered Software prove defective in any respect, You *
|
||||||
|
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||||
|
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||||
|
* essential part of this License. No use of any Covered Software is *
|
||||||
|
* authorized under this License except under this disclaimer. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 7. Limitation of Liability *
|
||||||
|
* -------------------------- *
|
||||||
|
* *
|
||||||
|
* Under no circumstances and under no legal theory, whether tort *
|
||||||
|
* (including negligence), contract, or otherwise, shall any *
|
||||||
|
* Contributor, or anyone who distributes Covered Software as *
|
||||||
|
* permitted above, be liable to You for any direct, indirect, *
|
||||||
|
* special, incidental, or consequential damages of any character *
|
||||||
|
* including, without limitation, damages for lost profits, loss of *
|
||||||
|
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||||
|
* and all other commercial damages or losses, even if such party *
|
||||||
|
* shall have been informed of the possibility of such damages. This *
|
||||||
|
* limitation of liability shall not apply to liability for death or *
|
||||||
|
* personal injury resulting from such party's negligence to the *
|
||||||
|
* extent applicable law prohibits such limitation. Some *
|
||||||
|
* jurisdictions do not allow the exclusion or limitation of *
|
||||||
|
* incidental or consequential damages, so this exclusion and *
|
||||||
|
* limitation may not apply to You. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
8. Litigation
|
||||||
|
-------------
|
||||||
|
|
||||||
|
Any litigation relating to this License may be brought only in the
|
||||||
|
courts of a jurisdiction where the defendant maintains its principal
|
||||||
|
place of business and such litigation shall be governed by laws of that
|
||||||
|
jurisdiction, without reference to its conflict-of-law provisions.
|
||||||
|
Nothing in this Section shall prevent a party's ability to bring
|
||||||
|
cross-claims or counter-claims.
|
||||||
|
|
||||||
|
9. Miscellaneous
|
||||||
|
----------------
|
||||||
|
|
||||||
|
This License represents the complete agreement concerning the subject
|
||||||
|
matter hereof. If any provision of this License is held to be
|
||||||
|
unenforceable, such provision shall be reformed only to the extent
|
||||||
|
necessary to make it enforceable. Any law or regulation which provides
|
||||||
|
that the language of a contract shall be construed against the drafter
|
||||||
|
shall not be used to construe this License against a Contributor.
|
||||||
|
|
||||||
|
10. Versions of the License
|
||||||
|
---------------------------
|
||||||
|
|
||||||
|
10.1. New Versions
|
||||||
|
|
||||||
|
Mozilla Foundation is the license steward. Except as provided in Section
|
||||||
|
10.3, no one other than the license steward has the right to modify or
|
||||||
|
publish new versions of this License. Each version will be given a
|
||||||
|
distinguishing version number.
|
||||||
|
|
||||||
|
10.2. Effect of New Versions
|
||||||
|
|
||||||
|
You may distribute the Covered Software under the terms of the version
|
||||||
|
of the License under which You originally received the Covered Software,
|
||||||
|
or under the terms of any subsequent version published by the license
|
||||||
|
steward.
|
||||||
|
|
||||||
|
10.3. Modified Versions
|
||||||
|
|
||||||
|
If you create software not governed by this License, and you want to
|
||||||
|
create a new license for such software, you may create and use a
|
||||||
|
modified version of this License if you rename the license and remove
|
||||||
|
any references to the name of the license steward (except to note that
|
||||||
|
such modified license differs from this License).
|
||||||
|
|
||||||
|
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||||
|
Licenses
|
||||||
|
|
||||||
|
If You choose to distribute Source Code Form that is Incompatible With
|
||||||
|
Secondary Licenses under the terms of this version of the License, the
|
||||||
|
notice described in Exhibit B of this License must be attached.
|
||||||
|
|
||||||
|
Exhibit A - Source Code Form License Notice
|
||||||
|
-------------------------------------------
|
||||||
|
|
||||||
|
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/.
|
||||||
|
|
||||||
|
If it is not possible or desirable to put the notice in a particular
|
||||||
|
file, then You may include the notice in a location (such as a LICENSE
|
||||||
|
file in a relevant directory) where a recipient would be likely to look
|
||||||
|
for such a notice.
|
||||||
|
|
||||||
|
You may add additional accurate notices of copyright ownership.
|
||||||
|
|
||||||
|
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||||
|
---------------------------------------------------------
|
||||||
|
|
||||||
|
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||||
|
defined by the Mozilla Public License, v. 2.0.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||||
|
<meta name="color-scheme" content="dark" />
|
||||||
|
<meta name="referrer" content="no-referrer" />
|
||||||
|
<title>Hosts — Ianitor Domi</title>
|
||||||
|
</head>
|
||||||
|
<body class="ia">
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"private": true,
|
||||||
|
"license": "MPL-2.0",
|
||||||
|
"description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
|
||||||
|
"test": "vitest run",
|
||||||
|
"shots": "node scripts/shots.mjs"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@ianitor/ui": "workspace:*"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@sveltejs/vite-plugin-svelte": "^5.0.3",
|
||||||
|
"@testing-library/svelte": "^5.2.6",
|
||||||
|
"@testing-library/user-event": "^14.6.1",
|
||||||
|
"@tsconfig/svelte": "^5.0.4",
|
||||||
|
"jsdom": "^26.0.0",
|
||||||
|
"svelte": "^5.20.0",
|
||||||
|
"svelte-check": "^4.1.4",
|
||||||
|
"typescript": "^5.7.3",
|
||||||
|
"vite": "^6.1.0",
|
||||||
|
"vitest": "^3.0.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,418 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// The release's screenshots of the web UI (docs/release.md):
|
||||||
|
// node apps/web/scripts/shots.mjs [--out <dir>] (default: <repo>/target/aula)
|
||||||
|
// Builds the UI, serves it on 127.0.0.1 with /api/v1 answered by the demo control plane
|
||||||
|
// (tests/demo.ts: invented data only), photographs each shot of demo.ts's SHOTS in headless Edge
|
||||||
|
// or Chrome over DevTools, and writes aula-<name>.png and aula.json in the format of Fabrica's
|
||||||
|
// core docs/FORMATS.md ("Fabrica: the Aula page"). On every way out the browser's process tree
|
||||||
|
// and the server are stopped and the temporary folder is removed.
|
||||||
|
// Exit codes: 0 done, 1 a problem, 130 cancelled.
|
||||||
|
|
||||||
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||||
|
import { createServer as createHttpServer } from "node:http";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { basename, delimiter, dirname, extname, join, normalize, resolve, sep } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { build, createServer as createViteServer } from "vite";
|
||||||
|
|
||||||
|
const web = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||||
|
const repo = resolve(web, "../..");
|
||||||
|
const WAIT_MS = 20_000;
|
||||||
|
|
||||||
|
function usage(msg) {
|
||||||
|
console.error(`shots: ${msg}\nusage: node apps/web/scripts/shots.mjs [--out <dir>]`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let out = join(repo, "target", "aula");
|
||||||
|
for (let i = 2; i < process.argv.length; i++) {
|
||||||
|
const a = process.argv[i];
|
||||||
|
if (a === "--out" && process.argv[i + 1]) out = resolve(process.argv[++i]);
|
||||||
|
else usage(`unknown argument ${a}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const log = (m) => console.log(`shots: ${m}`);
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
|
||||||
|
// ---------- cleanup on every way out ----------
|
||||||
|
|
||||||
|
const cleanups = [];
|
||||||
|
let cleaning = false;
|
||||||
|
async function cleanup() {
|
||||||
|
if (cleaning) return;
|
||||||
|
cleaning = true;
|
||||||
|
for (const f of cleanups.reverse()) {
|
||||||
|
try {
|
||||||
|
await f();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`shots: cleanup: ${e?.message ?? e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
process.on("SIGINT", () => void cleanup().then(() => process.exit(130)));
|
||||||
|
process.on("SIGTERM", () => void cleanup().then(() => process.exit(130)));
|
||||||
|
|
||||||
|
// ---------- the output folder ----------
|
||||||
|
|
||||||
|
function clearOutput() {
|
||||||
|
mkdirSync(out, { recursive: true });
|
||||||
|
for (const n of readdirSync(out)) {
|
||||||
|
if (n === "aula.json" || (n.startsWith("aula-") && n.endsWith(".png"))) rmSync(join(out, n), { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Width and height from the PNG's IHDR, not assumed. */
|
||||||
|
function pngSize(png) {
|
||||||
|
const sig = "89504e470d0a1a0a";
|
||||||
|
if (png.length < 24 || png.subarray(0, 8).toString("hex") !== sig || png.subarray(12, 16).toString("latin1") !== "IHDR") {
|
||||||
|
throw new Error("the browser's capture is not a PNG");
|
||||||
|
}
|
||||||
|
return { width: png.readUInt32BE(16), height: png.readUInt32BE(20) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- the demo control plane and the built UI on 127.0.0.1 ----------
|
||||||
|
|
||||||
|
const TYPES = {
|
||||||
|
".html": "text/html; charset=utf-8",
|
||||||
|
".js": "text/javascript; charset=utf-8",
|
||||||
|
".css": "text/css; charset=utf-8",
|
||||||
|
".json": "application/json",
|
||||||
|
".svg": "image/svg+xml",
|
||||||
|
".png": "image/png",
|
||||||
|
".ico": "image/x-icon",
|
||||||
|
".woff": "font/woff",
|
||||||
|
".woff2": "font/woff2",
|
||||||
|
".txt": "text/plain; charset=utf-8",
|
||||||
|
};
|
||||||
|
|
||||||
|
function serve(dist, api) {
|
||||||
|
const index = readFileSync(join(dist, "index.html"));
|
||||||
|
const server = createHttpServer((req, res) => {
|
||||||
|
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
||||||
|
if (url.pathname.startsWith("/api/v1/") || url.pathname === "/api/v1") {
|
||||||
|
const chunks = [];
|
||||||
|
req.on("data", (c) => chunks.push(c));
|
||||||
|
req.on("end", () => {
|
||||||
|
let body = {};
|
||||||
|
try {
|
||||||
|
body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {};
|
||||||
|
} catch {
|
||||||
|
body = {};
|
||||||
|
}
|
||||||
|
const a = api(req.method ?? "GET", url.pathname.slice("/api/v1".length) + url.search, body);
|
||||||
|
res.writeHead(a.status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
||||||
|
res.end(a.text ?? undefined);
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The built files; any other path is the app's own route, answered with index.html.
|
||||||
|
const file = normalize(join(dist, decodeURIComponent(url.pathname)));
|
||||||
|
if (file.startsWith(dist + sep) && existsSync(file) && statSync(file).isFile()) {
|
||||||
|
res.writeHead(200, { "Content-Type": TYPES[extname(file)] ?? "application/octet-stream" });
|
||||||
|
res.end(readFileSync(file));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.writeHead(200, { "Content-Type": TYPES[".html"], "Cache-Control": "no-store" });
|
||||||
|
res.end(index);
|
||||||
|
});
|
||||||
|
return new Promise((ok, fail) => {
|
||||||
|
server.once("error", fail);
|
||||||
|
server.listen(0, "127.0.0.1", () => ok(server));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- the browser ----------
|
||||||
|
|
||||||
|
function findBrowser() {
|
||||||
|
const named = process.env.IANITOR_SHOTS_BROWSER;
|
||||||
|
if (named) {
|
||||||
|
if (!existsSync(named)) throw new Error(`IANITOR_SHOTS_BROWSER: ${named} does not exist`);
|
||||||
|
return named;
|
||||||
|
}
|
||||||
|
const candidates = [];
|
||||||
|
if (process.platform === "win32") {
|
||||||
|
for (const base of [process.env["ProgramFiles(x86)"], process.env.ProgramFiles, process.env.LOCALAPPDATA].filter(Boolean)) {
|
||||||
|
candidates.push(join(base, "Microsoft", "Edge", "Application", "msedge.exe"), join(base, "Google", "Chrome", "Application", "chrome.exe"));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const dir of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {
|
||||||
|
for (const n of ["chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "microsoft-edge"]) candidates.push(join(dir, n));
|
||||||
|
}
|
||||||
|
candidates.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
|
||||||
|
}
|
||||||
|
const found = candidates.find((c) => existsSync(c));
|
||||||
|
if (!found) throw new Error("no Microsoft Edge or Chrome found; set IANITOR_SHOTS_BROWSER to a Chromium browser");
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Only what a program needs to run, the user folders in the temporary folder, nothing of the runner's. */
|
||||||
|
function cleanEnv(home) {
|
||||||
|
const keep = /^(SystemRoot|SystemDrive|windir|ComSpec|PATH|PATHEXT|OS|PROCESSOR_.*|NUMBER_OF_PROCESSORS|ProgramFiles.*|ProgramW6432|CommonProgramFiles.*|CommonProgramW6432|ProgramData|ALLUSERSPROFILE|PUBLIC|LANG|TZ)$/i;
|
||||||
|
const env = {};
|
||||||
|
for (const [k, v] of Object.entries(process.env)) if (keep.test(k) && v !== undefined) env[k] = v;
|
||||||
|
for (const d of ["home", "appdata", "local", "temp"]) mkdirSync(join(home, d), { recursive: true });
|
||||||
|
Object.assign(env, {
|
||||||
|
HOME: join(home, "home"),
|
||||||
|
USERPROFILE: join(home, "home"),
|
||||||
|
APPDATA: join(home, "appdata"),
|
||||||
|
LOCALAPPDATA: join(home, "local"),
|
||||||
|
TEMP: join(home, "temp"),
|
||||||
|
TMP: join(home, "temp"),
|
||||||
|
TMPDIR: join(home, "temp"),
|
||||||
|
});
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Edge may start its browser again as a new process, outside the tree: on Windows, anything still
|
||||||
|
* running with a profile in the temporary folder is stopped by its command line. */
|
||||||
|
function sweep(exe, tmp) {
|
||||||
|
if (process.platform !== "win32") return;
|
||||||
|
const script = "Get-CimInstance Win32_Process -Filter \"Name='$env:SHOTS_EXE'\" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($env:SHOTS_TMP) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }";
|
||||||
|
spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
|
||||||
|
stdio: "ignore",
|
||||||
|
windowsHide: true,
|
||||||
|
env: { ...cleanEnv(join(tmp, "sweep")), SHOTS_EXE: basename(exe), SHOTS_TMP: tmp },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function killTree(child) {
|
||||||
|
if (!child.pid || child.exitCode !== null) return;
|
||||||
|
if (process.platform === "win32") {
|
||||||
|
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
process.kill(-child.pid, "SIGKILL");
|
||||||
|
} catch {
|
||||||
|
child.kill("SIGKILL");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Starts the browser; one that has not opened DevTools after 20 s is killed and started again, twice. */
|
||||||
|
async function startBrowser(exe, tmp, size) {
|
||||||
|
for (let attempt = 1; ; attempt++) {
|
||||||
|
try {
|
||||||
|
return await launch(exe, join(tmp, `profile-${attempt}`), join(tmp, `user-${attempt}`), size);
|
||||||
|
} catch (e) {
|
||||||
|
if (attempt === 3 || e.fatal) throw e;
|
||||||
|
log(`${e.message}; starting it again`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function launch(exe, profile, user, size) {
|
||||||
|
mkdirSync(profile, { recursive: true });
|
||||||
|
const args = [
|
||||||
|
"--headless=new",
|
||||||
|
"--remote-debugging-port=0",
|
||||||
|
"--remote-debugging-address=127.0.0.1",
|
||||||
|
`--user-data-dir=${profile}`,
|
||||||
|
"--no-first-run",
|
||||||
|
"--no-default-browser-check",
|
||||||
|
"--disable-extensions",
|
||||||
|
"--disable-sync",
|
||||||
|
"--disable-background-networking",
|
||||||
|
"--disable-component-update",
|
||||||
|
"--disable-default-apps",
|
||||||
|
"--disable-features=Translate,OptimizationHints,MediaRouter,msSmartScreenProtection",
|
||||||
|
"--hide-scrollbars",
|
||||||
|
"--mute-audio",
|
||||||
|
"--force-color-profile=srgb",
|
||||||
|
"--force-device-scale-factor=1",
|
||||||
|
`--window-size=${size.width},${size.height}`,
|
||||||
|
"about:blank",
|
||||||
|
];
|
||||||
|
const child = spawn(exe, args, { env: cleanEnv(user), stdio: ["ignore", "ignore", "pipe"], windowsHide: true, detached: process.platform !== "win32" });
|
||||||
|
const stop = async () => {
|
||||||
|
killTree(child);
|
||||||
|
for (let i = 0; i < 50 && child.exitCode === null && child.signalCode === null; i++) await sleep(100);
|
||||||
|
};
|
||||||
|
cleanups.push(stop);
|
||||||
|
let stderr = "";
|
||||||
|
child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-2000)));
|
||||||
|
const fail = async (msg, fatal = false) => {
|
||||||
|
await stop();
|
||||||
|
const tail = stderr.trim().split(/\r?\n/).slice(-3).join(" | ");
|
||||||
|
throw Object.assign(new Error(`${msg}${tail ? `; it said: ${tail}` : ""}`), { fatal });
|
||||||
|
};
|
||||||
|
let exited = null;
|
||||||
|
child.on("exit", (code) => (exited = code ?? -1));
|
||||||
|
child.on("error", (e) => (exited = e.message));
|
||||||
|
|
||||||
|
const portFile = join(profile, "DevToolsActivePort");
|
||||||
|
const deadline = Date.now() + 20_000;
|
||||||
|
let seen = "no DevToolsActivePort yet";
|
||||||
|
for (;;) {
|
||||||
|
if (exited !== null) await fail(`the browser exited before it was ready (${exited})`, typeof exited === "string");
|
||||||
|
if (existsSync(portFile)) {
|
||||||
|
const port = Number(readFileSync(portFile, "utf8").split(/\r?\n/)[0]);
|
||||||
|
if (port > 0) {
|
||||||
|
try {
|
||||||
|
const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||||
|
const page = list.find((t) => t.type === "page" && t.webSocketDebuggerUrl);
|
||||||
|
if (page) return page.webSocketDebuggerUrl;
|
||||||
|
seen = `no page among ${list.length} targets on port ${port}`;
|
||||||
|
await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" }).catch(() => {});
|
||||||
|
} catch (e) {
|
||||||
|
seen = `port ${port}: ${e.cause?.message ?? e.message}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Date.now() > deadline) await fail(`the browser's DevTools did not answer within 20 s (${seen})`);
|
||||||
|
await sleep(200);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A minimal DevTools client over Node's WebSocket. */
|
||||||
|
async function devtools(url) {
|
||||||
|
const ws = new WebSocket(url);
|
||||||
|
await new Promise((ok, fail) => {
|
||||||
|
ws.onopen = ok;
|
||||||
|
ws.onerror = () => fail(new Error("cannot open the browser's DevTools socket"));
|
||||||
|
});
|
||||||
|
let id = 0;
|
||||||
|
const pending = new Map();
|
||||||
|
ws.onmessage = (m) => {
|
||||||
|
const msg = JSON.parse(String(m.data));
|
||||||
|
const p = msg.id !== undefined && pending.get(msg.id);
|
||||||
|
if (!p) return;
|
||||||
|
pending.delete(msg.id);
|
||||||
|
if (msg.error) p.fail(new Error(`${p.method}: ${msg.error.message}`));
|
||||||
|
else p.ok(msg.result);
|
||||||
|
};
|
||||||
|
ws.onclose = () => {
|
||||||
|
for (const p of pending.values()) p.fail(new Error("the browser closed its DevTools socket"));
|
||||||
|
pending.clear();
|
||||||
|
};
|
||||||
|
cleanups.push(() => ws.close());
|
||||||
|
const send = (method, params = {}) =>
|
||||||
|
new Promise((ok, fail) => {
|
||||||
|
const n = ++id;
|
||||||
|
pending.set(n, { ok, fail, method });
|
||||||
|
ws.send(JSON.stringify({ id: n, method, params }));
|
||||||
|
});
|
||||||
|
/** The value of an expression in the page; a page being replaced answers again later. */
|
||||||
|
const evaluate = async (expression) => {
|
||||||
|
const r = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
|
||||||
|
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
|
||||||
|
return r.result.value;
|
||||||
|
};
|
||||||
|
return { send, evaluate };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function until(what, test) {
|
||||||
|
const deadline = Date.now() + WAIT_MS;
|
||||||
|
let last = null;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
try {
|
||||||
|
if (await test()) return;
|
||||||
|
} catch (e) {
|
||||||
|
last = e;
|
||||||
|
}
|
||||||
|
await sleep(100);
|
||||||
|
}
|
||||||
|
throw new Error(`waited ${WAIT_MS / 1000} s for ${what}${last ? ` (${last.message})` : ""}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- the shots ----------
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
clearOutput();
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), "ianitor-shots-"));
|
||||||
|
cleanups.push(async () => {
|
||||||
|
for (let i = 0; i < 20; i++) {
|
||||||
|
try {
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
return;
|
||||||
|
} catch {
|
||||||
|
await sleep(250);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.error(`shots: could not remove ${tmp}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The demo's shots and answers, from the TypeScript the tests use.
|
||||||
|
const loader = await createViteServer({
|
||||||
|
root: web,
|
||||||
|
configFile: false,
|
||||||
|
logLevel: "error",
|
||||||
|
appType: "custom",
|
||||||
|
server: { middlewareMode: true, hmr: false, ws: false },
|
||||||
|
optimizeDeps: { noDiscovery: true, include: [] },
|
||||||
|
});
|
||||||
|
let demo;
|
||||||
|
try {
|
||||||
|
demo = await loader.ssrLoadModule("/tests/demo.ts");
|
||||||
|
} finally {
|
||||||
|
await loader.close();
|
||||||
|
}
|
||||||
|
const { SHOTS, SIZE, demoApi } = demo;
|
||||||
|
|
||||||
|
log("building the web UI");
|
||||||
|
const dist = join(tmp, "dist");
|
||||||
|
await build({ root: web, logLevel: "warn", build: { outDir: dist, emptyOutDir: true } });
|
||||||
|
|
||||||
|
const server = await serve(dist, demoApi());
|
||||||
|
cleanups.push(() => new Promise((r) => server.close(() => r())));
|
||||||
|
server.closeAllConnections && cleanups.push(() => server.closeAllConnections());
|
||||||
|
const base = `http://127.0.0.1:${server.address().port}`;
|
||||||
|
log(`demo control plane and UI on ${base}`);
|
||||||
|
|
||||||
|
const exe = findBrowser();
|
||||||
|
log(`browser: ${exe}`);
|
||||||
|
cleanups.push(() => sweep(exe, tmp));
|
||||||
|
const page = await devtools(await startBrowser(exe, tmp, SIZE));
|
||||||
|
await page.send("Page.enable");
|
||||||
|
await page.send("Emulation.setDeviceMetricsOverride", { width: SIZE.width, height: SIZE.height, deviceScaleFactor: 1, mobile: false });
|
||||||
|
|
||||||
|
const taken = [];
|
||||||
|
for (const shot of SHOTS) {
|
||||||
|
const url = base + shot.path;
|
||||||
|
try {
|
||||||
|
// A fresh load per shot: mark the old page, so a page that has not been replaced yet does not count.
|
||||||
|
await page.evaluate("window.__ianitorShotsOld = true").catch(() => {});
|
||||||
|
await page.send("Page.navigate", { url });
|
||||||
|
await until(`${url} to load`, () => page.evaluate("!window.__ianitorShotsOld && document.readyState === 'complete'"));
|
||||||
|
for (const sel of shot.click ?? []) {
|
||||||
|
const q = JSON.stringify(sel);
|
||||||
|
await until(`${sel} to click`, () => page.evaluate(`(() => { const e = document.querySelector(${q}); if (!e) return false; e.click(); return true; })()`));
|
||||||
|
}
|
||||||
|
const w = JSON.stringify(shot.wait);
|
||||||
|
await until(shot.wait, () => page.evaluate(`!!document.querySelector(${w})`));
|
||||||
|
await page.evaluate("document.fonts.ready.then(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true)))))");
|
||||||
|
await sleep(400);
|
||||||
|
} catch (e) {
|
||||||
|
try {
|
||||||
|
const failed = await page.send("Page.captureScreenshot", { format: "png" });
|
||||||
|
writeFileSync(join(out, `aula-${shot.name}-failed.png`), Buffer.from(failed.data, "base64"));
|
||||||
|
} catch {
|
||||||
|
/* nothing to save */
|
||||||
|
}
|
||||||
|
throw new Error(`shot ${shot.name}: ${e.message}; the page was ${url}; what it showed is aula-${shot.name}-failed.png`);
|
||||||
|
}
|
||||||
|
const png = Buffer.from((await page.send("Page.captureScreenshot", { format: "png" })).data, "base64");
|
||||||
|
const { width, height } = pngSize(png);
|
||||||
|
const file = `aula-${shot.name}.png`;
|
||||||
|
writeFileSync(join(out, file), png);
|
||||||
|
taken.push({ name: shot.name, title: shot.title, file, width, height, sha256: createHash("sha256").update(png).digest("hex") });
|
||||||
|
log(`${file} ${width}x${height}`);
|
||||||
|
}
|
||||||
|
writeFileSync(join(out, "aula.json"), `${JSON.stringify({ v: 1, shots: taken })}\n`);
|
||||||
|
log(`${taken.length} shots and aula.json in ${out}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let code = 0;
|
||||||
|
try {
|
||||||
|
await main();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`shots: ${e?.message ?? e}`);
|
||||||
|
code = 1;
|
||||||
|
} finally {
|
||||||
|
await cleanup();
|
||||||
|
}
|
||||||
|
process.exit(code);
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// The shell (handoff §2.16): sidebar on desktop, top and bottom bars on phone, the routes,
|
||||||
|
// the banners every screen starts with, toasts and the signed-out dialog (§10).
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { Button, Dialog, Icon } from "@ianitor/ui";
|
||||||
|
import type { IconName } from "@ianitor/ui";
|
||||||
|
import EngineChip from "./components/EngineChip.svelte";
|
||||||
|
import EnginePopover from "./components/EnginePopover.svelte";
|
||||||
|
import TopBanners from "./components/TopBanners.svelte";
|
||||||
|
import { app, navigate, refresh, startPolling } from "./lib/app.svelte";
|
||||||
|
import { remembered } from "./lib/applies";
|
||||||
|
import Certificates from "./views/Certificates.svelte";
|
||||||
|
import History from "./views/History.svelte";
|
||||||
|
import Hosts from "./views/Hosts.svelte";
|
||||||
|
import Previews from "./views/Previews.svelte";
|
||||||
|
import RenewByHand from "./views/RenewByHand.svelte";
|
||||||
|
import Settings from "./views/Settings.svelte";
|
||||||
|
import SignedIn from "./views/SignedIn.svelte";
|
||||||
|
|
||||||
|
const route = $derived.by(() => {
|
||||||
|
const u = new URL(app.path, "http://x");
|
||||||
|
const p = u.pathname.replace(/\/+$/, "") || "/";
|
||||||
|
const seg = p.split("/").filter(Boolean).map(decodeURIComponent);
|
||||||
|
if (p === "/signed-in") return { view: "signed-in" as const };
|
||||||
|
if (seg[0] === "previews") return { view: "previews" as const };
|
||||||
|
if (seg[0] === "history") return { view: "history" as const, host: u.searchParams.get("host") ?? undefined, pick: seg[1] };
|
||||||
|
if (seg[0] === "certificates") return { view: seg[1] === "renew-by-hand" ? ("renew" as const) : ("certs" as const), newDevice: seg[1] === "new" };
|
||||||
|
if (seg[0] === "settings") return { view: "settings" as const, tab: seg[1] ?? "general" };
|
||||||
|
return { view: "hosts" as const, newHost: seg[0] === "hosts" && seg[1] === "new", edit: seg[0] === "hosts" && seg[2] === "edit" ? seg[1] : undefined };
|
||||||
|
});
|
||||||
|
|
||||||
|
const NAV: { href: string; label: string; icon: IconName; views: string[] }[] = [
|
||||||
|
{ href: "/", label: "Hosts", icon: "building", views: ["hosts"] },
|
||||||
|
{ href: "/previews", label: "Previews", icon: "link", views: ["previews"] },
|
||||||
|
{ href: "/history", label: "History", icon: "history", views: ["history"] },
|
||||||
|
{ href: "/certificates", label: "Certificates", icon: "shield", views: ["certs", "renew"] },
|
||||||
|
{ href: "/settings/general", label: "Settings", icon: "gear", views: ["settings"] },
|
||||||
|
];
|
||||||
|
const TITLES: Record<string, string> = { hosts: "Hosts", history: "History", previews: "Previews", certs: "Certificates", renew: "Certificates", settings: "Settings", "signed-in": "Signed in" };
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
document.title = `${TITLES[route.view] ?? "Hosts"} — Ianitor Domi`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// A setup or invite link (`#signin=<code>`, crate::team): one click on the link signs in.
|
||||||
|
async function signInFromLink(): Promise<void> {
|
||||||
|
const m = /^#signin=([A-Za-z0-9_-]{8,100})$/.exec(location.hash);
|
||||||
|
if (!m) return;
|
||||||
|
history.replaceState(null, "", location.pathname + location.search);
|
||||||
|
try {
|
||||||
|
const r = await fetch("/api/v1/session", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", "X-Ianitor-UI": "1" },
|
||||||
|
body: JSON.stringify({ code: m[1], device: navigator.platform || "Browser" }),
|
||||||
|
credentials: "same-origin",
|
||||||
|
});
|
||||||
|
if (!r.ok) {
|
||||||
|
const j = await r.json().catch(() => null);
|
||||||
|
app.linkProblem = j?.error?.message ?? "This sign-in link does not work.";
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
app.linkProblem = "Ianitor did not answer the sign-in.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signOutSession() {
|
||||||
|
try {
|
||||||
|
await fetch("/api/v1/session/end", { method: "POST", headers: { "X-Ianitor-UI": "1" }, credentials: "same-origin" });
|
||||||
|
} finally {
|
||||||
|
location.href = "/";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
if (route.view === "signed-in") return;
|
||||||
|
if (location.hash.startsWith("#signin=")) {
|
||||||
|
void signInFromLink().then(() => refresh());
|
||||||
|
}
|
||||||
|
const stop = startPolling();
|
||||||
|
// Resume an apply this tab was watching before a reload or a sign-in (§3).
|
||||||
|
const id = remembered();
|
||||||
|
if (id && route.view === "hosts") app.panel = { kind: "host", resume: id };
|
||||||
|
let ch: BroadcastChannel | undefined;
|
||||||
|
try {
|
||||||
|
ch = new BroadcastChannel("ianitor-auth");
|
||||||
|
ch.onmessage = (m) => {
|
||||||
|
if (m.data === "signed-in") {
|
||||||
|
app.signedOut = false;
|
||||||
|
void refresh();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
/* no BroadcastChannel: "I have signed in" still works */
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
stop();
|
||||||
|
ch?.close();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
function go(e: MouseEvent, href: string) {
|
||||||
|
if (e.metaKey || e.ctrlKey || e.shiftKey) return;
|
||||||
|
e.preventDefault();
|
||||||
|
navigate(href);
|
||||||
|
}
|
||||||
|
|
||||||
|
function signIn() {
|
||||||
|
const w = window.open("/signed-in", "ianitor-sign-in");
|
||||||
|
if (!w) {
|
||||||
|
// The new tab was blocked: this tab goes to the sign-in, so an open form is saved first
|
||||||
|
// (sessionStorage, this tab only) and comes back after it (§10).
|
||||||
|
window.dispatchEvent(new Event("ianitor:save-draft"));
|
||||||
|
location.href = `/signed-in?back=${encodeURIComponent(app.path)}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signedInAgain() {
|
||||||
|
app.signedOut = false;
|
||||||
|
await refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
const viewer = $derived(app.overview?.viewer ?? null);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if route.view === "signed-in"}
|
||||||
|
<SignedIn />
|
||||||
|
{:else}
|
||||||
|
<a class="skip domi-btn" href="#main">Skip to content</a>
|
||||||
|
<div class="shell">
|
||||||
|
<nav class="sidebar" aria-label="Main">
|
||||||
|
<div class="ia-wordmark brand">IANITOR DOMI</div>
|
||||||
|
{#each NAV as n (n.href)}
|
||||||
|
<a href={n.href} class="nav" aria-current={n.views.includes(route.view) ? "page" : undefined} onclick={(e) => go(e, n.href)}><Icon name={n.icon} />{n.label}</a>
|
||||||
|
{/each}
|
||||||
|
<div class="foot ia-muted">
|
||||||
|
<p>{viewer?.via === "authelia" ? `Signed in as ${viewer.name} through Authelia` : viewer?.via === "session" ? `Signed in as ${viewer.name}` : viewer ? `Using the API token "${viewer.name}"` : "Not signed in"}</p>
|
||||||
|
{#if viewer?.via === "session"}<button type="button" class="domi-btn link" onclick={signOutSession}>Sign out</button>{/if}
|
||||||
|
<p>Control on 127.0.0.1 only</p>
|
||||||
|
{#if app.overview?.site?.auth_logout_url}<a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a>{/if}
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span>{#if app.phone}<EngineChip />{/if}</header>
|
||||||
|
<main id="main" tabindex="-1">
|
||||||
|
<TopBanners />
|
||||||
|
{#if app.linkProblem}<p class="domi-error" role="alert">{app.linkProblem}</p>{/if}
|
||||||
|
{#if route.view === "hosts"}
|
||||||
|
<Hosts route={{ newHost: route.newHost, edit: route.edit }} />
|
||||||
|
{:else if route.view === "previews"}
|
||||||
|
<Previews />
|
||||||
|
{:else if route.view === "history"}
|
||||||
|
{#key route.host}<History host={route.host} pick={route.pick} />{/key}
|
||||||
|
{:else if route.view === "certs"}
|
||||||
|
<Certificates newDevice={route.newDevice} />
|
||||||
|
{:else if route.view === "renew"}
|
||||||
|
<RenewByHand />
|
||||||
|
{:else if route.view === "settings"}
|
||||||
|
<Settings tab={route.tab} />
|
||||||
|
{/if}
|
||||||
|
</main>
|
||||||
|
<nav class="bottombar" aria-label="Main">
|
||||||
|
{#each NAV as n (n.href)}
|
||||||
|
<a href={n.href} aria-current={n.views.includes(route.view) ? "page" : undefined} onclick={(e) => go(e, n.href)}><Icon name={n.icon} /><span>{n.label}</span></a>
|
||||||
|
{/each}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if app.panel?.kind === "engine"}
|
||||||
|
<EnginePopover onclose={() => {
|
||||||
|
app.panel = null;
|
||||||
|
document.querySelector<HTMLElement>("[data-engine-chip]")?.focus();
|
||||||
|
}} />
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="ia-toasts" role="status" aria-live="polite">
|
||||||
|
{#each app.toasts as t (t.id)}<div class="ia-toast"><Icon name="check" />{t.text}</div>{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if app.signedOut}
|
||||||
|
<Dialog title="Your sign-in has ended" role="alertdialog" escape={false} closable={false} onclose={() => {}}>
|
||||||
|
<p>Sign in again; this page keeps what you typed. Without Authelia, open your sign-in link again or ask an admin of your team for a new one.</p>
|
||||||
|
{#snippet footer()}
|
||||||
|
<Button onclick={signedInAgain}>I have signed in</Button>
|
||||||
|
<Button variant="primary" onclick={signIn} data-autofocus>Sign in</Button>
|
||||||
|
{/snippet}
|
||||||
|
</Dialog>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.shell { display: grid; grid-template-columns: var(--sidebar-w) minmax(0, 1fr); min-height: 100dvh; }
|
||||||
|
.sidebar { background: var(--colonnade); border-right: 1px solid var(--hairline); padding: 22px 14px; display: flex; flex-direction: column; gap: 4px; position: sticky; top: 0; height: 100dvh; }
|
||||||
|
.brand { padding: 4px 10px 18px; }
|
||||||
|
.nav { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-nav); text-decoration: none; border: 1px solid transparent; }
|
||||||
|
.nav:hover { background: var(--surface); color: var(--text); }
|
||||||
|
.nav[aria-current="page"] { background: var(--surface-2); color: var(--text); box-shadow: var(--inset-lit); border-color: color-mix(in srgb, var(--accent) 30%, transparent); }
|
||||||
|
.nav[aria-current="page"] :global(svg) { color: var(--accent); }
|
||||||
|
.foot { margin-top: auto; font-size: 0.82rem; display: flex; flex-direction: column; gap: 4px; padding: 0 10px; }
|
||||||
|
main { padding: var(--main-pad); display: flex; flex-direction: column; gap: 18px; min-width: 0; outline: none; }
|
||||||
|
.topbar, .bottombar { display: none; }
|
||||||
|
@media (max-width: 719.98px) {
|
||||||
|
.shell { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.sidebar { display: none; }
|
||||||
|
.topbar { display: flex; align-items: center; justify-content: space-between; background: var(--colonnade); border-bottom: 1px solid var(--hairline); padding: 10px 16px; }
|
||||||
|
.topbar .ia-wordmark { font-size: 12px; letter-spacing: 0.26em; }
|
||||||
|
main { padding: 18px 16px calc(90px + env(safe-area-inset-bottom)); gap: 14px; }
|
||||||
|
.bottombar { display: grid; grid-template-columns: repeat(5, 1fr); position: fixed; left: 0; right: 0; bottom: 0; background: var(--colonnade); border-top: 1px solid var(--hairline); padding: 6px 8px calc(10px + env(safe-area-inset-bottom)); z-index: 40; }
|
||||||
|
.bottombar a { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: var(--phone-bar-h); border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-tab-phone); text-decoration: none; }
|
||||||
|
.bottombar a[aria-current="page"] { background: var(--surface-2); color: var(--text); }
|
||||||
|
.bottombar a[aria-current="page"] :global(svg) { color: var(--accent); }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §7.1: the apply checklist, its countdown and the queued state.
|
||||||
|
import { Button, Icon, Progress } from "@ianitor/ui";
|
||||||
|
import type { ApplyView } from "../lib/types";
|
||||||
|
import { app, secondsLeft } from "../lib/app.svelte";
|
||||||
|
|
||||||
|
let { apply, oncancel }: { apply: ApplyView; oncancel?: () => void } = $props();
|
||||||
|
|
||||||
|
const engine = $derived(app.overview?.engine.running === "caddy" ? "Caddy" : "Pingora");
|
||||||
|
const watchSeconds = $derived(app.overview?.site?.watch_seconds ?? 60);
|
||||||
|
const left = $derived(apply.watch ? secondsLeft(apply.watch.ends_at) : watchSeconds);
|
||||||
|
const st = (k: string) => apply.steps.find((s) => s.key === k)?.state ?? "pending";
|
||||||
|
const merged = (a: string, b: string) => {
|
||||||
|
const x = st(a);
|
||||||
|
const y = st(b);
|
||||||
|
if (x === "failed" || y === "failed") return "failed";
|
||||||
|
if (x === "running" || y === "running") return "running";
|
||||||
|
if (x === "done" && (y === "done" || y === "skipped")) return "done";
|
||||||
|
return x;
|
||||||
|
};
|
||||||
|
const noWatch = $derived(apply.reason?.code === "apply.kept.no_watch");
|
||||||
|
const rows = $derived([
|
||||||
|
{ s: st("validate"), t: { pending: "Check the host file", running: "Checking the host file", done: "Checked the host file", failed: "The host file did not pass the check", skipped: "Check the host file" } },
|
||||||
|
{ s: merged("compile", "write"), t: { pending: "Build the Pingora and Caddy settings", running: "Building the Pingora and Caddy settings", done: "Built the Pingora and Caddy settings", failed: "Could not build the settings", skipped: "Build the Pingora and Caddy settings" } },
|
||||||
|
{ s: st("reload"), t: { pending: `Reload ${engine}`, running: `Reloading ${engine}`, done: `Reloaded ${engine}, no connections dropped`, failed: `${engine} did not take the new settings`, skipped: `Reload ${engine}` } },
|
||||||
|
{
|
||||||
|
s: st("watch"),
|
||||||
|
t: noWatch
|
||||||
|
? { pending: "Check that it answers", running: `Checking that it answers: ${left} s left`, done: "It answers", failed: "Health checks failed", skipped: "Nothing to watch: the host is removed." }
|
||||||
|
: { pending: `Watch health checks for ${watchSeconds} s`, running: `Watching health checks: ${left} s left`, done: `Health checks passed for ${watchSeconds} s`, failed: "Health checks failed", skipped: "Nothing to watch: the host is removed." },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const prefix: Record<string, string> = { done: "Done:", running: "Now:", pending: "Next:", failed: "Failed:", skipped: "Skipped:" };
|
||||||
|
const final = $derived(["kept", "reverted", "failed", "needs_attention"].includes(apply.state));
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if apply.state === "queued"}
|
||||||
|
<p class="ia-status" data-s="running">
|
||||||
|
<Icon name="clock" />
|
||||||
|
<span>
|
||||||
|
Waiting for "{apply.queue?.waiting_for?.summary ?? "another change"}" to finish{apply.queue?.waiting_for?.seconds_left != null
|
||||||
|
? `, about ${apply.queue.waiting_for.seconds_left} s`
|
||||||
|
: ""}.
|
||||||
|
{#if (apply.queue?.position ?? 1) > 1}{(apply.queue?.position ?? 1) - 1} other changes are ahead of this one.{/if}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
{#if oncancel}<div><Button onclick={oncancel}>Cancel</Button></div>{/if}
|
||||||
|
{:else}
|
||||||
|
<ol class="steps">
|
||||||
|
{#each rows as r, i (i)}
|
||||||
|
<li class={r.s}>
|
||||||
|
{#if r.s === "done"}<Icon name="check" />{:else if r.s === "running"}<Icon name="clock" />{:else if r.s === "failed"}<Icon name="ring" />{:else}<span class="hollow" aria-hidden="true"></span>{/if}
|
||||||
|
<span><span class="sr-only">{prefix[r.s]}</span>{r.t[r.s as keyof typeof r.t]}</span>
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
{#if st("watch") === "failed" && !final}
|
||||||
|
<li class="running"><Icon name="clock" /><span><span class="sr-only">Now:</span>Undoing the change</span></li>
|
||||||
|
{/if}
|
||||||
|
</ol>
|
||||||
|
{#if apply.state === "watching"}
|
||||||
|
<Progress label="Health watch" max={watchSeconds} now={watchSeconds - left} text="{left} seconds left" />
|
||||||
|
<p class="ia-hint">You can leave this screen. Other changes wait their turn; only one apply runs at a time.</p>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.steps li { display: flex; gap: 10px; align-items: center; }
|
||||||
|
.steps li.pending { color: var(--muted); }
|
||||||
|
.steps li.running { color: var(--text); }
|
||||||
|
.steps li.running :global(svg) { color: var(--accent); }
|
||||||
|
.steps li.done { color: var(--text-2); }
|
||||||
|
.steps li.done :global(svg) { color: var(--kept); }
|
||||||
|
.steps li.failed :global(svg) { color: var(--down); }
|
||||||
|
.steps li.skipped { color: var(--muted); }
|
||||||
|
.hollow { width: 14px; height: 14px; border-radius: 50%; border: 2px solid var(--muted); margin: 2px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §7.4 and §7.5: the last-change bar with Undo (1 click), and the reverted / not
|
||||||
|
// applied banner that stands in for its first line.
|
||||||
|
import { Banner, Button, Details, Icon, Progress } from "@ianitor/ui";
|
||||||
|
import { ApiError, call, del, newKey, post, sentence } from "../lib/api";
|
||||||
|
import { app, refresh, secondsLeft, toast } from "../lib/app.svelte";
|
||||||
|
import { atTime, firstSentence, when } from "../lib/format";
|
||||||
|
import type { ApplyView } from "../lib/types";
|
||||||
|
|
||||||
|
let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props();
|
||||||
|
|
||||||
|
const o = $derived(app.overview);
|
||||||
|
const last = $derived(o?.last_apply ?? null);
|
||||||
|
const active = $derived(o?.active_apply ?? null);
|
||||||
|
const undo = $derived(o?.undo ?? null);
|
||||||
|
let moved = $state<string | null>(null);
|
||||||
|
let undoing = $state(false);
|
||||||
|
let pushing = $state(false);
|
||||||
|
const dismissKey = $derived(last ? `apply:${last.id}` : "");
|
||||||
|
|
||||||
|
function runningHeading(summary: string, a: { kind: string; hosts: string[]; summary: string } | null): string {
|
||||||
|
if (!a) return summary;
|
||||||
|
const h = a.hosts[0] ?? "";
|
||||||
|
switch (a.kind) {
|
||||||
|
case "add": return `Adding ${h}`;
|
||||||
|
case "remove": return `Removing ${h}`;
|
||||||
|
case "edit": return `Changing ${h}`;
|
||||||
|
case "share_links": return `Turning on share links for ${h}`;
|
||||||
|
case "undo": return `Undoing: ${a.summary.replace(/^Undid: /, "")}`;
|
||||||
|
case "restore": return a.summary.replace(/^Restored /, "Restoring ");
|
||||||
|
default: return summary;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doUndo() {
|
||||||
|
if (!undo?.target) return;
|
||||||
|
undoing = true;
|
||||||
|
moved = null;
|
||||||
|
try {
|
||||||
|
await post("/undo", { target_change_id: undo.target.change_id });
|
||||||
|
await refresh();
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError && e.code === "undo.target_moved") {
|
||||||
|
moved = e.body.message;
|
||||||
|
await refresh();
|
||||||
|
} else {
|
||||||
|
moved = sentence(e);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
undoing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pushNow() {
|
||||||
|
pushing = true;
|
||||||
|
try {
|
||||||
|
await call("POST", "/repo/push", {}, { idem: newKey() });
|
||||||
|
} catch {
|
||||||
|
/* the bar shows the push state on the next poll */
|
||||||
|
} finally {
|
||||||
|
pushing = false;
|
||||||
|
await refresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cancel(id: string) {
|
||||||
|
try {
|
||||||
|
await del(`/applies/${encodeURIComponent(id)}`);
|
||||||
|
toast("Cancelled before it started. Nothing changed.");
|
||||||
|
await refresh();
|
||||||
|
} catch (e) {
|
||||||
|
moved = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const keptLine = $derived.by(() => {
|
||||||
|
if (!last || last.state !== "kept") return "";
|
||||||
|
const t = when(last.finished_at ?? last.created_at, app.now);
|
||||||
|
const code = last.reason?.code ?? "";
|
||||||
|
if (code === "apply.kept.no_watch") return `${last.hosts[0] ?? ""} has no health check, so Ianitor only checked that it answers.`;
|
||||||
|
const what = code === "apply.kept.removed" ? "removed" : code === "apply.kept.no_edge" ? "saved, nothing checked (development mode)" : `health checks passed for ${o?.site?.watch_seconds ?? 60} s`;
|
||||||
|
const push = last.push?.state === "pushed" ? `pushed to Gitea as ${last.commit_short}` : last.push?.state === "pending" ? "sending to Gitea" : last.commit_short ? `saved as commit ${last.commit_short}` : "";
|
||||||
|
return [t, what, push].filter(Boolean).join(" · ");
|
||||||
|
});
|
||||||
|
const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed");
|
||||||
|
const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null);
|
||||||
|
// Ticks every second on the local clock (§7.2), not only on the 5 s poll.
|
||||||
|
const watchLeft = $derived(
|
||||||
|
active?.watch_ends_at ? secondsLeft(active.watch_ends_at) : active?.seconds_left != null ? active.seconds_left : null,
|
||||||
|
);
|
||||||
|
// The outcome's offer, by code (§7.5).
|
||||||
|
const offer = $derived.by(() => {
|
||||||
|
const c = last?.reason?.code ?? "";
|
||||||
|
if (/^apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
|
||||||
|
if (/^apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: last?.reason?.field ?? undefined };
|
||||||
|
if (/^apply\.failed\.(reload|build|edge_unreachable)$/.test(c)) return null;
|
||||||
|
if (last?.attempted_host) return { label: "Edit and try again", field: last?.reason?.field ?? undefined };
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
const pushLine = $derived.by(() => {
|
||||||
|
const p = last?.push;
|
||||||
|
const remote = "Gitea";
|
||||||
|
switch (p?.error_code) {
|
||||||
|
case "push.failed.rejected": return `Kept, but ${remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server.`;
|
||||||
|
case "push.failed.auth": return `Kept, but ${remote} refused Ianitor's access key. Check the key in Custos.`;
|
||||||
|
default: return `Kept, but not yet saved to ${remote}: ${remote} did not answer.${p?.next_try_at ? ` Ianitor tries again ${atTime(p.next_try_at, app.now)}.` : " Ianitor tries again by itself."}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const canPushNow = $derived(pushFailed && last?.push?.error_code !== "push.failed.rejected");
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)}
|
||||||
|
{@const parts = firstSentence(last.reason?.message ?? "")}
|
||||||
|
<Banner tone="notice" ondismiss={() => (app.dismissed = [...app.dismissed, dismissKey])}>
|
||||||
|
{#snippet title()}<span class="ia-status" data-s="reverted"><Icon name="undo" /><span class="word">{last.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
|
||||||
|
{#if parts[1]}Reason: {parts[1]}{/if}
|
||||||
|
{#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")}<Details detail={last.reason.detail} />{/if}
|
||||||
|
{#snippet actions()}
|
||||||
|
{#if offer}<Button variant="outline" onclick={() => onedit(last, offer?.field)}>{offer.label}</Button>{/if}
|
||||||
|
{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if last || active}
|
||||||
|
<section class="ia-bar" aria-label="Last change">
|
||||||
|
{#if active}
|
||||||
|
<div class="grow">
|
||||||
|
<div class="ia-status" data-s="running"><Icon name="clock" /><span class="word">{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"}</span>
|
||||||
|
<span>{runningHeading(active.summary, active.kind ? active : null)}</span></div>
|
||||||
|
<div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : active.state === "watching" ? `${watchLeft ?? 0} s left` : "Checking and loading the change"}</div>
|
||||||
|
{#if active.state === "watching" && watchLeft != null}
|
||||||
|
{@const total = o?.site?.watch_seconds ?? 60}
|
||||||
|
<Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{#if active.state === "queued"}<Button onclick={() => cancel(active.id)}>Cancel</Button>{:else}<button type="button" class="domi-btn link" onclick={() => onshowsteps(active.id)}>Show steps</button>{/if}
|
||||||
|
{:else if last}
|
||||||
|
<div class="grow">
|
||||||
|
{#if last.state === "kept"}
|
||||||
|
<div><span class="ia-status" data-s="kept"><Icon name="check" /><span class="word">kept</span></span> {last.summary}</div>
|
||||||
|
<div class="ia-sub" class:warn={pushFailed}>{pushFailed ? pushLine : keptLine}</div>
|
||||||
|
{:else if undo?.target}
|
||||||
|
<div>Undo: {undo.target.summary}</div>
|
||||||
|
{/if}
|
||||||
|
{#if undo?.effect && (last.state !== "kept" || undo?.target?.change_id !== last.change_id)}<div class="ia-sub">{undo.effect}</div>{/if}
|
||||||
|
{#if moved}<div class="ia-sub" role="status">{moved}</div>{/if}
|
||||||
|
{#if undoReason}<div class="ia-sub" id="undo-reason">{undoReason}</div>{/if}
|
||||||
|
{#if !undo?.target}<div class="ia-sub">Nothing to undo yet.</div>{/if}
|
||||||
|
</div>
|
||||||
|
{#if canPushNow}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if}
|
||||||
|
{#if undo?.target}
|
||||||
|
<Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available}
|
||||||
|
describedby={undoReason ? "undo-reason" : undefined}
|
||||||
|
label="Undo: {undo.target.summary}.{undo.effect ? ' ' + undo.effect + '.' : ''}">Undo</Button>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.warn { color: var(--degraded); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §2.4: the engine chip (click 1 of the switch). On the main screen's header on a
|
||||||
|
// desktop, in the top bar on a phone (§2.16).
|
||||||
|
import { Icon } from "@ianitor/ui";
|
||||||
|
import { app } from "../lib/app.svelte";
|
||||||
|
|
||||||
|
const o = $derived(app.overview);
|
||||||
|
const engineName = $derived(o?.engine.running === "caddy" ? "Caddy" : "Pingora");
|
||||||
|
const engineLabel = $derived(
|
||||||
|
o?.engine.state === "switching" ? "Engine: switching" : `Engine: ${engineName}${o?.engine.state === "stopped" ? ", not answering" : ""}. Change engine`,
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if o}
|
||||||
|
<button type="button" class="ia-engine" data-engine-chip aria-haspopup="dialog" aria-expanded={app.panel?.kind === "engine"} aria-label={engineLabel}
|
||||||
|
onclick={() => (app.panel = app.panel?.kind === "engine" ? null : { kind: "engine" })}>
|
||||||
|
{#if o.engine.state === "switching"}<Icon name="clock" /> Engine Switching…{:else}
|
||||||
|
<span class="ia-status" data-s={o.engine.state === "stopped" ? "down" : "healthy"}><span class="ia-dot"></span></span>
|
||||||
|
<small class="desktop">Engine</small> {engineName}{#if o.engine.running === "caddy"} <small>(fallback)</small>{/if}{/if}
|
||||||
|
<Icon name="chevron" />
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
@media (max-width: 719.98px) { .desktop { display: none; } }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §9: the engine popover. Click 1 is the chip, click 2 "Switch to Caddy" (the popover
|
||||||
|
// is the confirmation). The switch runs in control; this polls GET /engine until it ends.
|
||||||
|
import { onDestroy, onMount } from "svelte";
|
||||||
|
import { Banner, Button, Details, Dialog, Icon, Progress } from "@ianitor/ui";
|
||||||
|
import { call, get, newKey, sentence } from "../lib/api";
|
||||||
|
import { app, refresh } from "../lib/app.svelte";
|
||||||
|
import { whenInline } from "../lib/format";
|
||||||
|
import type { EngineView } from "../lib/types";
|
||||||
|
|
||||||
|
let { onclose }: { onclose: () => void } = $props();
|
||||||
|
|
||||||
|
const e = $derived(app.overview?.engine ?? null);
|
||||||
|
const running = $derived(e?.running ?? "pingora");
|
||||||
|
const name = $derived(running === "caddy" ? "Caddy" : "Pingora");
|
||||||
|
const other = $derived(running === "caddy" ? "Pingora" : "Caddy");
|
||||||
|
const target = $derived(running === "caddy" ? "pingora" : "caddy");
|
||||||
|
let switching = $state(false);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
onDestroy(() => clearTimeout(timer));
|
||||||
|
|
||||||
|
let activeLinks = $state(0);
|
||||||
|
onMount(async () => {
|
||||||
|
try {
|
||||||
|
const l = await get<{ items: { state: string }[] }>("/share-links", { quiet: true });
|
||||||
|
activeLinks = l.items.filter((x) => x.state === "active").length;
|
||||||
|
} catch {
|
||||||
|
/* the count is only a hint */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const fr = $derived(e?.fallback_ready ?? null);
|
||||||
|
const differs = $derived(fr ? fr.compared - fr.matched : 0);
|
||||||
|
const notReady = $derived(running === "pingora" && !e?.fallback_ready?.built_at);
|
||||||
|
const disabledReason = $derived(!e?.switchable ? "This server does not let Ianitor switch engines." : notReady ? "Caddy is not ready: its settings have not been built yet." : null);
|
||||||
|
|
||||||
|
async function doSwitch() {
|
||||||
|
problem = null;
|
||||||
|
switching = true;
|
||||||
|
const from = name;
|
||||||
|
const to = other;
|
||||||
|
try {
|
||||||
|
await call("POST", "/engine", { target }, { idem: newKey() });
|
||||||
|
const poll = async () => {
|
||||||
|
try {
|
||||||
|
const v = await get<EngineView>("/engine", { quiet: true });
|
||||||
|
if (v.state === "switching") {
|
||||||
|
timer = setTimeout(poll, 1000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
switching = false;
|
||||||
|
await refresh();
|
||||||
|
if (v.last_error) {
|
||||||
|
app.switchResult = { ok: false, title: `${to} did not start, so ${from} is serving again.`, text: "Visitors had a short break and nothing else changed.", detail: v.last_error.detail ?? null };
|
||||||
|
} else {
|
||||||
|
app.switchResult = { ok: true, title: `Now serving with ${to}.`, text: "Switch back from the engine chip at any time; it is the same 2 clicks." };
|
||||||
|
}
|
||||||
|
onclose();
|
||||||
|
} catch {
|
||||||
|
// Contact may drop for a few seconds while the engines change (§9.2).
|
||||||
|
timer = setTimeout(poll, 1000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
timer = setTimeout(poll, 500);
|
||||||
|
} catch (err) {
|
||||||
|
switching = false;
|
||||||
|
problem = sentence(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Dialog title={e?.state === "stopped" ? `${name} is not answering` : `Serving with ${name}`} kind="popover" modal={false} escape={!switching} toggle="[data-engine-chip]" {onclose}>
|
||||||
|
<p class="ia-label">Engine</p>
|
||||||
|
{#if e?.state === "stopped"}
|
||||||
|
<p>Visitors may not reach any host. Switching to {other} is the quickest way back.</p>
|
||||||
|
{:else}
|
||||||
|
<p class="ia-text2">
|
||||||
|
{#if e?.since}Since {whenInline(e.since, app.now)}. {/if}
|
||||||
|
{#if running === "pingora"}
|
||||||
|
{#if notReady}Caddy is not ready: its settings have not been built yet.{:else if differs > 0}Caddy was built {whenInline(fr?.built_at, app.now)} with the same routes, but {differs} of {fr?.compared} {fr?.compared === 1 ? "host" : "hosts"} {differs === 1 ? "behaves" : "behave"} differently on it.{:else}Caddy is ready with the same routes: built {whenInline(fr?.built_at, app.now)}{fr?.compared ? (fr.compared === 1 ? ", and the host behaves the same" : `, and all ${fr.compared} hosts behave the same`) : ""}.{/if}
|
||||||
|
{#if !notReady && !fr?.current} It is rebuilt from the current routes when you switch.{/if}
|
||||||
|
{:else}Pingora is ready with the same routes.{/if}
|
||||||
|
</p>
|
||||||
|
{#if running === "pingora" && !notReady && fr?.differences.length}
|
||||||
|
<Details detail={fr.differences.join("\n")} />
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
<div class="ia-card">
|
||||||
|
<p><strong>What happens</strong></p>
|
||||||
|
<ul>
|
||||||
|
<li>{name} stops and {other} starts. New visits reach {other} in about 2 seconds.</li>
|
||||||
|
<li>Open connections close; videos and uploads in progress restart.</li>
|
||||||
|
<li>Hosts and certificates stay the same.</li>
|
||||||
|
{#if running === "pingora"}
|
||||||
|
<li>Share links stop working while Caddy serves: visitors with a link get the normal sign-in. They work again when you switch back.{#if activeLinks}{" "}{activeLinks === 1 ? "1 share link is" : `${activeLinks} share links are`} active.{/if}</li>
|
||||||
|
<li>Changes keep working: Ianitor tries each one on Caddy and undoes it if a host stops answering.</li>
|
||||||
|
{:else}
|
||||||
|
<li>Share links work again.</li>
|
||||||
|
{/if}
|
||||||
|
<li>This page may lose contact for a few seconds.</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{#if switching}
|
||||||
|
<p class="ia-status" data-s="running" role="status"><Icon name="clock" /><strong>Switching to {other}</strong></p>
|
||||||
|
<Progress label="Switching engine" max={1} now={0} text="{name} stopping, starting {other}" />
|
||||||
|
{/if}
|
||||||
|
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||||
|
{#if disabledReason}<p class="ia-hint" id="switch-reason">{disabledReason}</p>{/if}
|
||||||
|
{#snippet footer()}
|
||||||
|
<Button onclick={onclose}>Cancel</Button>
|
||||||
|
<Button variant={e?.state === "stopped" ? "primary" : "outline"} icon="swap" onclick={doSwitch} pending={switching}
|
||||||
|
disabled={!!disabledReason} describedby={disabledReason ? "switch-reason" : undefined}>Switch to {other}</Button>
|
||||||
|
{/snippet}
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
ul { margin: 6px 0 0; padding-left: 1.1rem; color: var(--text-2); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §2.5 and §5.1: the host list, sorted down, degraded, pending, unknown, healthy.
|
||||||
|
import { Status } from "@ianitor/ui";
|
||||||
|
import type { StatusKind } from "@ianitor/ui";
|
||||||
|
import HostMenu from "./HostMenu.svelte";
|
||||||
|
import { app, changesBlocked } from "../lib/app.svelte";
|
||||||
|
import { ago, duration } from "../lib/format";
|
||||||
|
import type { HostRow } from "../lib/types";
|
||||||
|
|
||||||
|
let {
|
||||||
|
hosts,
|
||||||
|
onedit,
|
||||||
|
onremove,
|
||||||
|
onshare,
|
||||||
|
onhistory,
|
||||||
|
onretry,
|
||||||
|
}: {
|
||||||
|
hosts: HostRow[];
|
||||||
|
onedit: (h: string) => void;
|
||||||
|
onremove: (h: string) => void;
|
||||||
|
onshare: (h: string) => void;
|
||||||
|
onhistory: (h: string) => void;
|
||||||
|
onretry: (h: string) => void;
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
const ORDER: Record<string, number> = { down: 0, degraded: 1, pending: 2, unknown: 3, healthy: 4 };
|
||||||
|
const sorted = $derived([...hosts].sort((a, b) => (ORDER[a.health.state] ?? 5) - (ORDER[b.health.state] ?? 5) || a.hostname.localeCompare(b.hostname)));
|
||||||
|
const running = $derived(app.overview?.active_apply ? (app.overview.last_apply?.hosts ?? []) : []);
|
||||||
|
const underCaddy = $derived(app.overview?.engine.running === "caddy");
|
||||||
|
|
||||||
|
function kind(h: HostRow): [StatusKind, string] {
|
||||||
|
switch (h.health.state) {
|
||||||
|
case "healthy": return ["healthy", "healthy"];
|
||||||
|
case "degraded": return ["degraded", "degraded"];
|
||||||
|
case "down": return ["down", "down"];
|
||||||
|
case "pending": return ["unknown", "waiting"];
|
||||||
|
default: return ["unknown", "not checked"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function since(h: HostRow): string {
|
||||||
|
return h.health.since ? duration((app.now - Date.parse(h.health.since)) / 1000) : "a while";
|
||||||
|
}
|
||||||
|
|
||||||
|
function sub(h: HostRow): { text: string; problem: boolean } {
|
||||||
|
const f = h.health.failure;
|
||||||
|
const visitors = 'Visitors get an error page.';
|
||||||
|
switch (h.health.state) {
|
||||||
|
case "healthy": {
|
||||||
|
const added = h.added_at && app.now - Date.parse(h.added_at) < 86_400_000 ? "Added today · c" : "C";
|
||||||
|
const lat = h.health.latency_ms != null && !underCaddy ? ` · ${h.health.latency_ms} ms` : "";
|
||||||
|
return { text: `${added}hecked ${ago(h.health.last_check_at, app.now)}${lat}`, problem: false };
|
||||||
|
}
|
||||||
|
case "degraded": {
|
||||||
|
const ok = h.health.upstreams.filter((u) => u.state === "healthy").length;
|
||||||
|
const m = h.health.upstreams.length;
|
||||||
|
if (m > 1) return { text: `${ok} of ${m} addresses answer. Visitors are sent to the ones that do.`, problem: true };
|
||||||
|
return { text: `Answering only some checks.`, problem: true };
|
||||||
|
}
|
||||||
|
case "down":
|
||||||
|
if (f?.kind === "refused") return { text: `Connection refused for ${since(h)}. ${visitors}`, problem: true };
|
||||||
|
if (f?.kind === "timeout") return { text: `Not answering for ${since(h)}. ${visitors}`, problem: true };
|
||||||
|
if (f?.kind === "name") return { text: `The name ${f.upstream ?? ""} cannot be found. ${visitors}`, problem: true };
|
||||||
|
if (f?.kind === "tls") return { text: `The certificate of ${f.upstream ?? ""} cannot be checked.`, problem: true };
|
||||||
|
return { text: `Answering with an error page for ${since(h)}.`, problem: true };
|
||||||
|
case "pending": return { text: "Waiting for the first check.", problem: false };
|
||||||
|
default: return { text: "No health check set for this host.", problem: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function phoneDetail(h: HostRow): string {
|
||||||
|
if (h.health.state === "healthy" && h.health.latency_ms != null) return `${h.health.latency_ms} ms`;
|
||||||
|
if (h.health.state === "down" && h.health.failure?.kind === "refused") return `refused for ${since(h)}`;
|
||||||
|
if (h.health.state === "unknown") return "no health check";
|
||||||
|
if (h.added_at && app.now - Date.parse(h.added_at) < 86_400_000) return "added today";
|
||||||
|
return h.share_links ? "share links on" : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function chips(h: HostRow): string[] {
|
||||||
|
const c = [h.tls === "domi" ? "Domi certificate" : "Let's Encrypt"];
|
||||||
|
c.push(h.auth === "forward-auth" ? "Sign-in first" : "Open to anyone");
|
||||||
|
if (h.share_links) c.push("Share links on");
|
||||||
|
if (h.device_certs) c.push("Device certificate needed");
|
||||||
|
if (!h.websockets) c.push("No websockets");
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
const blocked = $derived(changesBlocked());
|
||||||
|
const shareReason = $derived(!app.overview?.site?.share_links_available ? (underCaddy ? "Share links are off while Caddy serves." : "Share links are not set up on this server.") : null);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="ia-list" role="table" aria-label="Hosts">
|
||||||
|
<div class="ia-row head" role="row">
|
||||||
|
<span class="ia-label col-status" role="columnheader">Status</span>
|
||||||
|
<span class="ia-label" role="columnheader">Host</span>
|
||||||
|
<span class="ia-label desktop" role="columnheader">Sends traffic to</span>
|
||||||
|
<span role="columnheader"><span class="sr-only">More</span></span>
|
||||||
|
</div>
|
||||||
|
{#each sorted as h (h.hostname)}
|
||||||
|
{@const [k, w] = kind(h)}
|
||||||
|
{@const s = sub(h)}
|
||||||
|
<div class="ia-row" role="row">
|
||||||
|
<span class="col-status" role="cell"><Status kind={k} word={w} /></span>
|
||||||
|
<span role="cell">
|
||||||
|
<span class="phone-dot"><Status kind={k} word="" /></span>
|
||||||
|
<span class="ia-host">{h.hostname}</span>
|
||||||
|
<span class="ia-chips desktop">{#each chips(h) as c (c)}<span class="ia-chip">{c}</span>{/each}</span>
|
||||||
|
<span class="ia-sub phone">{w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}</span>
|
||||||
|
</span>
|
||||||
|
<span role="cell" class="desktop">
|
||||||
|
<span>{h.upstreams[0] ?? ""}</span>{#if h.upstreams.length > 1}{" "}<span class="ia-muted">+{h.upstreams.length - 1} more</span>{/if}
|
||||||
|
<span class="ia-sub" class:problem={s.problem} style="display:block">{running.includes(h.hostname) ? "Changing now · " : ""}{s.text}</span>
|
||||||
|
{#if h.certificate.state === "pending"}<span class="ia-sub" style="display:block">Waiting for Let's Encrypt to issue the certificate.</span>{/if}
|
||||||
|
{#if h.certificate.state === "failed"}
|
||||||
|
<span class="ia-sub" style="display:block;color:var(--down)">Let's Encrypt could not confirm <strong>{h.hostname}</strong>. The name must point to this server, and port 80 must be open from the internet.
|
||||||
|
<button type="button" class="domi-btn link" onclick={() => onretry(h.hostname)}>Try again</button></span>
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
<span role="cell">
|
||||||
|
<HostMenu hostname={h.hostname} items={[
|
||||||
|
{ label: "Share link", icon: "link", reason: shareReason, run: () => onshare(h.hostname) },
|
||||||
|
{ label: "Edit host", icon: "pencil", reason: blocked, run: () => onedit(h.hostname) },
|
||||||
|
{ label: "Show in history", icon: "history", run: () => onhistory(h.hostname) },
|
||||||
|
{ label: "Remove host", icon: "trash", danger: true, divider: true, reason: blocked, run: () => onremove(h.hostname) },
|
||||||
|
]} />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.phone, .phone-dot { display: none; }
|
||||||
|
.problem { color: var(--text-2) !important; }
|
||||||
|
@media (max-width: 719.98px) {
|
||||||
|
.desktop { display: none !important; }
|
||||||
|
.phone { display: block; padding-left: 22px; }
|
||||||
|
.phone-dot { display: inline; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts" module>
|
||||||
|
import type { IconName } from "@ianitor/ui";
|
||||||
|
export interface Item {
|
||||||
|
label: string;
|
||||||
|
icon: IconName;
|
||||||
|
danger?: boolean;
|
||||||
|
reason?: string | null;
|
||||||
|
divider?: boolean;
|
||||||
|
run: () => void;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §2.6: the row's ⋯ menu (WAI-ARIA menu button).
|
||||||
|
import { tick } from "svelte";
|
||||||
|
import { Icon } from "@ianitor/ui";
|
||||||
|
|
||||||
|
let { hostname, items }: { hostname: string; items: Item[] } = $props();
|
||||||
|
|
||||||
|
let open = $state(false);
|
||||||
|
let btn: HTMLButtonElement | undefined = $state();
|
||||||
|
let list: HTMLUListElement | undefined = $state();
|
||||||
|
const id = "menu-" + Math.random().toString(36).slice(2, 9);
|
||||||
|
|
||||||
|
const nodes = () => Array.from(list?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? []);
|
||||||
|
|
||||||
|
async function show(focus: "first" | "last" = "first") {
|
||||||
|
open = true;
|
||||||
|
await tick();
|
||||||
|
const n = nodes();
|
||||||
|
(focus === "first" ? n[0] : n[n.length - 1])?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
function close(back = true) {
|
||||||
|
open = false;
|
||||||
|
if (back) btn?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
function key(e: KeyboardEvent) {
|
||||||
|
const n = nodes();
|
||||||
|
const i = n.indexOf(document.activeElement as HTMLElement);
|
||||||
|
if (e.key === "ArrowDown") { e.preventDefault(); n[(i + 1) % n.length]?.focus(); }
|
||||||
|
else if (e.key === "ArrowUp") { e.preventDefault(); n[(i - 1 + n.length) % n.length]?.focus(); }
|
||||||
|
else if (e.key === "Home") { e.preventDefault(); n[0]?.focus(); }
|
||||||
|
else if (e.key === "End") { e.preventDefault(); n[n.length - 1]?.focus(); }
|
||||||
|
else if (e.key === "Escape") { e.preventDefault(); close(); }
|
||||||
|
else if (e.key === "Tab") close(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pick(it: Item) {
|
||||||
|
if (it.reason) return;
|
||||||
|
// Focus back on More first: a dialog the item opens returns focus there when it closes
|
||||||
|
// (§2.9), not to a menu item that no longer exists.
|
||||||
|
close(true);
|
||||||
|
it.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
function outside(e: MouseEvent) {
|
||||||
|
if (open && !(e.target instanceof Node && (list?.contains(e.target) || btn?.contains(e.target)))) close(false);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:window onclick={outside} />
|
||||||
|
|
||||||
|
<div class="ia-menu-wrap">
|
||||||
|
<button bind:this={btn} type="button" class="ia-icon-btn" aria-label="More for {hostname}" aria-haspopup="menu"
|
||||||
|
aria-expanded={open} aria-controls={id}
|
||||||
|
onclick={() => (open ? close() : show())}
|
||||||
|
onkeydown={(e) => { if (e.key === "ArrowDown") { e.preventDefault(); show("first"); } else if (e.key === "ArrowUp") { e.preventDefault(); show("last"); } }}>
|
||||||
|
<Icon name="dots" />
|
||||||
|
</button>
|
||||||
|
{#if open}
|
||||||
|
<ul bind:this={list} class="ia-menu" role="menu" id={id} aria-label={hostname} tabindex="-1" onkeydown={key}>
|
||||||
|
{#each items as it (it.label)}
|
||||||
|
{#if it.divider}<li role="separator"><hr /></li>{/if}
|
||||||
|
<li role="none">
|
||||||
|
<button type="button" role="menuitem" tabindex="-1" class:danger={it.danger} aria-disabled={it.reason ? "true" : undefined} onclick={() => pick(it)}>
|
||||||
|
<Icon name={it.icon} />{it.label}
|
||||||
|
{#if it.reason}<span class="reason">{it.reason}</span>{/if}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,538 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §6 and §7: the add/edit panel, its validation on blur, Apply, and the progress and
|
||||||
|
// outcome of the apply it starts. Every decision comes from control; the form only carries it.
|
||||||
|
import { onDestroy, onMount } from "svelte";
|
||||||
|
import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui";
|
||||||
|
import ApplyProgress from "./ApplyProgress.svelte";
|
||||||
|
import { ApiError, call, del, get, newKey, sentence } from "../lib/api";
|
||||||
|
import { app, changesBlocked, refresh, restoreLastKept, toast } from "../lib/app.svelte";
|
||||||
|
import { FINAL, follow } from "../lib/applies";
|
||||||
|
import { firstSentence } from "../lib/format";
|
||||||
|
import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types";
|
||||||
|
|
||||||
|
let {
|
||||||
|
hostname,
|
||||||
|
resume,
|
||||||
|
prefill,
|
||||||
|
focusField,
|
||||||
|
onclose,
|
||||||
|
}: {
|
||||||
|
hostname?: string;
|
||||||
|
resume?: string;
|
||||||
|
prefill?: HostSpec | null;
|
||||||
|
focusField?: string;
|
||||||
|
onclose: () => void;
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
const site = $derived(app.overview?.site ?? null);
|
||||||
|
const signinOk = $derived(site?.forward_auth_configured ?? false);
|
||||||
|
|
||||||
|
// ---- the form
|
||||||
|
type Rule = { action: "set" | "remove"; name: string; kind: "value" | "secret"; value: string; secret: string };
|
||||||
|
let host = $state({
|
||||||
|
hostname: "",
|
||||||
|
upstreams: [""],
|
||||||
|
tls: "domi" as "domi" | "letsencrypt",
|
||||||
|
auth: "forward-auth" as "forward-auth" | "none",
|
||||||
|
websockets: true,
|
||||||
|
share_links: false,
|
||||||
|
device_certs: false,
|
||||||
|
access_log: "off" as "off" | "truncated",
|
||||||
|
hc: false,
|
||||||
|
hcPath: "/",
|
||||||
|
hcEvery: 30,
|
||||||
|
req: [] as Rule[],
|
||||||
|
resp: [] as Rule[],
|
||||||
|
});
|
||||||
|
let rev = $state<string | null>(null);
|
||||||
|
let more = $state(false);
|
||||||
|
let loading = $state(true);
|
||||||
|
let notFound = $state<string | null>(null);
|
||||||
|
let errors = $state<Record<string, ErrorBody>>({});
|
||||||
|
let touched = $state<Record<string, boolean>>({});
|
||||||
|
let summary = $state("");
|
||||||
|
let underFooter = $state("");
|
||||||
|
let conflict = $state<ErrorBody | null>(null);
|
||||||
|
let topError = $state<ApiError | null>(null);
|
||||||
|
let idem = newKey();
|
||||||
|
let lastBody = "";
|
||||||
|
|
||||||
|
// ---- the apply
|
||||||
|
let apply = $state<ApplyView | null>(null);
|
||||||
|
let restoring = $state(false);
|
||||||
|
let restoreProblem = $state<string | null>(null);
|
||||||
|
let phase = $state<"form" | "progress">("form");
|
||||||
|
let stop: (() => void) | undefined;
|
||||||
|
let closeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
||||||
|
function fromSpec(s: HostSpec) {
|
||||||
|
host.hostname = s.hostname;
|
||||||
|
host.upstreams = s.upstreams.length ? [...s.upstreams] : [""];
|
||||||
|
host.tls = s.tls;
|
||||||
|
host.auth = s.auth;
|
||||||
|
host.websockets = s.websockets;
|
||||||
|
host.share_links = s.share_links;
|
||||||
|
host.device_certs = !!s.device_certs;
|
||||||
|
host.access_log = s.access_log;
|
||||||
|
host.hc = !!s.health_check;
|
||||||
|
host.hcPath = s.health_check?.path ?? "/";
|
||||||
|
host.hcEvery = s.health_check?.interval_secs ?? 30;
|
||||||
|
const rule = (r: HeaderRule): Rule => ({ action: r.action, name: r.name, kind: r.secret ? "secret" : "value", value: r.value ?? "", secret: r.secret ?? "" });
|
||||||
|
host.req = (s.request_headers ?? []).map(rule);
|
||||||
|
host.resp = (s.response_headers ?? []).map(rule);
|
||||||
|
if (host.hc || host.req.length || host.resp.length || !host.websockets || host.share_links || host.access_log !== "off" || host.device_certs) more = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function spec(): HostSpec {
|
||||||
|
const rules = (rs: Rule[]): HeaderRule[] =>
|
||||||
|
rs.map((r) =>
|
||||||
|
r.action === "remove"
|
||||||
|
? { action: "remove", name: r.name }
|
||||||
|
: r.kind === "secret"
|
||||||
|
? { action: "set", name: r.name, secret: r.secret }
|
||||||
|
: { action: "set", name: r.name, value: r.value },
|
||||||
|
);
|
||||||
|
// The UI always sends every field explicitly (the schema's own defaults differ).
|
||||||
|
return {
|
||||||
|
hostname: host.hostname.trim(),
|
||||||
|
upstreams: host.upstreams.map((u) => u.trim()).filter((u, i) => u !== "" || i === 0),
|
||||||
|
tls: host.tls,
|
||||||
|
auth: host.auth,
|
||||||
|
websockets: host.websockets,
|
||||||
|
share_links: host.share_links,
|
||||||
|
device_certs: host.device_certs,
|
||||||
|
access_log: host.access_log,
|
||||||
|
health_check: host.hc ? { path: host.hcPath, interval_secs: Number(host.hcEvery) } : null,
|
||||||
|
request_headers: rules(host.req),
|
||||||
|
response_headers: rules(host.resp),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
if (resume) {
|
||||||
|
phase = "progress";
|
||||||
|
stop = follow(resume, onApply);
|
||||||
|
}
|
||||||
|
if (prefill) {
|
||||||
|
fromSpec(prefill);
|
||||||
|
} else if (hostname) {
|
||||||
|
try {
|
||||||
|
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
|
||||||
|
fromSpec(d.host);
|
||||||
|
rev = d.rev;
|
||||||
|
} catch (e) {
|
||||||
|
notFound = sentence(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
rev = app.overview?.rev ?? null;
|
||||||
|
if (!signinOk) host.auth = "none";
|
||||||
|
}
|
||||||
|
// A form saved before this tab went to sign in comes back (App.svelte, signIn).
|
||||||
|
try {
|
||||||
|
const raw = sessionStorage.getItem(DRAFT);
|
||||||
|
const d = raw ? (JSON.parse(raw) as { hostname: string; host: typeof host }) : null;
|
||||||
|
if (d && d.hostname === (hostname ?? "") && !resume) {
|
||||||
|
Object.assign(host, d.host);
|
||||||
|
more = more || d.host.hc || d.host.req.length > 0 || d.host.resp.length > 0;
|
||||||
|
}
|
||||||
|
sessionStorage.removeItem(DRAFT);
|
||||||
|
} catch {
|
||||||
|
/* no storage: nothing to bring back */
|
||||||
|
}
|
||||||
|
loading = false;
|
||||||
|
if (phase === "form") {
|
||||||
|
// The Dialog focused its heading while this said "Loading…": now the first field
|
||||||
|
// (Hostname; Send traffic to when editing), so typing right after opening works.
|
||||||
|
const f = focusField ?? (hostname ? "upstreams[0]" : "hostname");
|
||||||
|
if (f.startsWith("health_check")) more = true;
|
||||||
|
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
|
||||||
|
}
|
||||||
|
window.addEventListener("ianitor:save-draft", saveDraft);
|
||||||
|
});
|
||||||
|
|
||||||
|
const DRAFT = "ianitor-draft";
|
||||||
|
function saveDraft() {
|
||||||
|
if (phase !== "form") return;
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(DRAFT, JSON.stringify({ hostname: hostname ?? "", host: $state.snapshot(host) }));
|
||||||
|
} catch {
|
||||||
|
/* no storage */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
stop?.();
|
||||||
|
clearTimeout(closeTimer);
|
||||||
|
if (typeof window !== "undefined") window.removeEventListener("ianitor:save-draft", saveDraft);
|
||||||
|
});
|
||||||
|
|
||||||
|
function fieldId(f: string): string {
|
||||||
|
return "f-" + f.replace(/[^a-z0-9]+/gi, "-");
|
||||||
|
}
|
||||||
|
const errAt = (f: string) => errors[f];
|
||||||
|
|
||||||
|
function setErrors(list: ErrorBody[], only?: string) {
|
||||||
|
const next: Record<string, ErrorBody> = only ? { ...errors } : {};
|
||||||
|
if (only) {
|
||||||
|
for (const k of Object.keys(next)) if (k === only || k.startsWith(only + "[")) delete next[k];
|
||||||
|
}
|
||||||
|
for (const e of list) {
|
||||||
|
const f = e.field ?? "";
|
||||||
|
if (!f) continue;
|
||||||
|
if (only && !(f === only || f.startsWith(only + "["))) continue;
|
||||||
|
next[f] = e;
|
||||||
|
}
|
||||||
|
errors = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validation on blur (§2.10): only the field that lost focus, debounced.
|
||||||
|
let blurTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
function blur(field: string) {
|
||||||
|
touched[field] = true;
|
||||||
|
clearTimeout(blurTimer);
|
||||||
|
blurTimer = setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await call("POST", `/hosts/validate?mode=${hostname ? "edit" : "create"}`, spec());
|
||||||
|
setErrors([], field);
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError) setErrors(e.errors.length ? e.errors : [e.body], field);
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit(e?: Event) {
|
||||||
|
e?.preventDefault();
|
||||||
|
if (changesBlocked()) return;
|
||||||
|
const body = spec();
|
||||||
|
const text = JSON.stringify(body);
|
||||||
|
if (text !== lastBody) {
|
||||||
|
idem = newKey();
|
||||||
|
lastBody = text;
|
||||||
|
}
|
||||||
|
underFooter = "";
|
||||||
|
conflict = null;
|
||||||
|
topError = null;
|
||||||
|
try {
|
||||||
|
const path = hostname ? `/hosts/${encodeURIComponent(hostname)}` : "/hosts";
|
||||||
|
const a = await call<{ apply: ApplyView }>(hostname ? "PUT" : "POST", path, { host: body, base_rev: rev }, { idem });
|
||||||
|
const ap = a.data?.apply;
|
||||||
|
if (!ap) return;
|
||||||
|
apply = ap;
|
||||||
|
phase = "progress";
|
||||||
|
stop?.();
|
||||||
|
stop = follow(ap.id, onApply);
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof ApiError)) {
|
||||||
|
topError = null;
|
||||||
|
underFooter = sentence(err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (err.code === "change.conflict") {
|
||||||
|
conflict = err.body;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (err.code === "change.unchanged") {
|
||||||
|
underFooter = "This is the same as what is live now, so nothing changed.";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const list = err.errors.length ? err.errors : err.body.field ? [err.body] : [];
|
||||||
|
if (list.length) {
|
||||||
|
setErrors(list);
|
||||||
|
for (const x of list) if (x.field) touched[x.field] = true;
|
||||||
|
summary = `${list.length} ${list.length === 1 ? "thing" : "things"} to fix before Apply.`;
|
||||||
|
const first = list.find((x) => x.field)?.field;
|
||||||
|
if (first?.startsWith("health_check") || first?.includes("headers")) more = true;
|
||||||
|
if (first) setTimeout(() => document.getElementById(fieldId(first))?.focus(), 0);
|
||||||
|
} else {
|
||||||
|
topError = err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onApply(a: ApplyView) {
|
||||||
|
apply = a;
|
||||||
|
if (a.state === "kept") {
|
||||||
|
if (a.kind !== "remove") app.focusHost = a.hosts[0] ?? null;
|
||||||
|
closeTimer = setTimeout(() => onclose(), 1500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cancelQueued() {
|
||||||
|
if (!apply) return;
|
||||||
|
try {
|
||||||
|
await del(`/applies/${encodeURIComponent(apply.id)}`);
|
||||||
|
toast("Cancelled before it started. Nothing changed.");
|
||||||
|
stop?.();
|
||||||
|
phase = "form";
|
||||||
|
apply = null;
|
||||||
|
} catch (e) {
|
||||||
|
underFooter = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function editAgain(field?: string) {
|
||||||
|
stop?.();
|
||||||
|
phase = "form";
|
||||||
|
apply = null;
|
||||||
|
idem = newKey();
|
||||||
|
const f = field ?? "upstreams[0]";
|
||||||
|
if (f.startsWith("health_check")) {
|
||||||
|
more = true;
|
||||||
|
host.hc = true;
|
||||||
|
}
|
||||||
|
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function keepMine() {
|
||||||
|
if (!hostname) {
|
||||||
|
rev = app.overview?.rev ?? rev;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
|
||||||
|
rev = d.rev;
|
||||||
|
} catch {
|
||||||
|
/* keep the old rev */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await refresh();
|
||||||
|
if (!hostname) rev = app.overview?.rev ?? rev;
|
||||||
|
conflict = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function useTheirs() {
|
||||||
|
if (!hostname) return;
|
||||||
|
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
|
||||||
|
fromSpec(d.host);
|
||||||
|
rev = d.rev;
|
||||||
|
conflict = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const name = $derived(host.hostname.trim() || hostname || "the host");
|
||||||
|
const heading = $derived.by(() => {
|
||||||
|
if (phase !== "progress" || !apply) return hostname ? `Edit ${hostname}` : "New host";
|
||||||
|
const h = apply.hosts[0] ?? name;
|
||||||
|
switch (apply.kind) {
|
||||||
|
case "add":
|
||||||
|
return `Adding ${h}`;
|
||||||
|
case "remove":
|
||||||
|
return `Removing ${h}`;
|
||||||
|
case "share_links":
|
||||||
|
return `Turning on share links for ${h}`;
|
||||||
|
case "undo":
|
||||||
|
return `Undoing: ${apply.summary.replace(/^Undid: /, "")}`;
|
||||||
|
case "restore":
|
||||||
|
return apply.summary.replace(/^Restored /, "Restoring ");
|
||||||
|
default:
|
||||||
|
return `Changing ${h}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const reasonOffer = $derived.by(() => {
|
||||||
|
const c = apply?.reason?.code ?? "";
|
||||||
|
if (/apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
|
||||||
|
if (/apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: "" };
|
||||||
|
if (c.startsWith("apply.reverted") || c === "apply.failed.validation" || c.startsWith("pki.")) return { label: "Edit and try again", field: apply?.reason?.field ?? undefined };
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
const blocked = $derived(changesBlocked());
|
||||||
|
const shareWarning = $derived(host.auth === "none" && host.share_links);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Dialog title={heading} kind="panel" {onclose}>
|
||||||
|
{#if loading}
|
||||||
|
<p class="ia-muted">Loading…</p>
|
||||||
|
{:else if notFound}
|
||||||
|
<Banner tone="notice" live="status">{#snippet title()}{notFound}{/snippet}
|
||||||
|
{#snippet actions()}<Button onclick={onclose}>Back to hosts</Button>{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{:else if phase === "progress" && apply}
|
||||||
|
<div aria-live="polite" class="sr-only">
|
||||||
|
{#if apply.state === "queued"}Waiting for another change to finish.{:else if apply.state === "watching"}Watching health checks.{:else if apply.state === "kept"}Kept. {apply.reason?.message}{:else if apply.state === "reverted"}Reverted. {apply.reason?.message}{:else if apply.state === "failed"}Not applied. {apply.reason?.message}{/if}
|
||||||
|
</div>
|
||||||
|
<ApplyProgress {apply} oncancel={cancelQueued} />
|
||||||
|
{#if apply.state === "kept"}
|
||||||
|
<Banner tone="kept">
|
||||||
|
{#snippet title()}<span class="ia-status" data-s="kept"><span class="word">kept</span></span> <strong>{apply?.hosts[0] ?? name}</strong> {apply?.kind === "remove" ? "is removed." : "is live."}{/snippet}
|
||||||
|
{(apply.reason?.message ?? "").replace(/^\S+ is (live|removed)\.\s*/, "")}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if}
|
||||||
|
</Banner>
|
||||||
|
{:else if apply.state === "reverted" || apply.state === "failed"}
|
||||||
|
{@const parts = firstSentence(apply.reason?.message ?? "")}
|
||||||
|
<Banner tone="notice" live="status">
|
||||||
|
{#snippet title()}<span class="ia-status" data-s="reverted"><span class="word">{apply?.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
|
||||||
|
{#if parts[1]}Reason: {parts[1]}{/if}
|
||||||
|
{#snippet actions()}
|
||||||
|
{#if reasonOffer}
|
||||||
|
<Button variant="outline" onclick={() => (reasonOffer?.field === "" ? (editAgain(), submit()) : editAgain(reasonOffer?.field))}>{reasonOffer.label}</Button>
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{#if apply.reason?.detail}<Details detail={apply.reason.detail} />{/if}
|
||||||
|
<p class="ia-hint">Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.</p>
|
||||||
|
{:else if apply.state === "needs_attention"}
|
||||||
|
<Banner tone="down" live="alert">{#snippet title()}<strong>Ianitor could not undo a failed change.</strong>{/snippet}{apply.reason?.message}
|
||||||
|
{#if restoreProblem}<p role="status">{restoreProblem}</p>{/if}
|
||||||
|
{#snippet actions()}
|
||||||
|
{#if app.overview?.undo?.target}<Button variant="primary" pending={restoring} onclick={async () => { restoring = true; restoreProblem = await restoreLastKept(); restoring = false; }}>Restore the last kept version</Button>{/if}
|
||||||
|
{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<form id="host-form" onsubmit={submit} novalidate>
|
||||||
|
{#if summary}<p class="sr-only" role="alert">{summary}</p>{/if}
|
||||||
|
{#if conflict}
|
||||||
|
<Banner tone="notice" live="status">
|
||||||
|
{#snippet title()}{conflict?.message}{/snippet}
|
||||||
|
{#snippet actions()}<Button onclick={keepMine}>Keep my edits</Button>{#if hostname}<Button onclick={useTheirs}>Use the new version</Button>{/if}{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{/if}
|
||||||
|
{#if topError}
|
||||||
|
<Banner tone="notice" live="status">{#snippet title()}{sentence(topError)}{/snippet}</Banner>
|
||||||
|
{#if topError.body.detail}<Details detail={topError.body.detail} reference={topError.requestId} />{/if}
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for={fieldId("hostname")}>Hostname</label>
|
||||||
|
<input id={fieldId("hostname")} class="domi-input" bind:value={host.hostname} readonly={!!hostname}
|
||||||
|
autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
|
||||||
|
aria-invalid={errAt("hostname") && touched["hostname"] ? "true" : undefined}
|
||||||
|
aria-describedby="{fieldId('hostname')}-e {fieldId('hostname')}-h" onblur={() => blur("hostname")} />
|
||||||
|
{#if errAt("hostname") && touched["hostname"]}
|
||||||
|
<p class="domi-error" id="{fieldId('hostname')}-e"><Icon name="ring" />{errAt("hostname").message}
|
||||||
|
{#if errAt("hostname").params?.suggestion}
|
||||||
|
<button type="button" class="domi-btn link" onclick={() => { host.hostname = errAt("hostname").params.suggestion; blur("hostname"); }}>Use {errAt("hostname").params.suggestion}</button>
|
||||||
|
{/if}
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
{#if hostname}<p class="ia-hint" id="{fieldId('hostname')}-h">To use another address, add a new host and remove this one.</p>{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#each host.upstreams as _, i (i)}
|
||||||
|
{@const f = `upstreams[${i}]`}
|
||||||
|
{@const err = errAt(f) ?? (i === 0 ? errAt("upstreams") : undefined)}
|
||||||
|
<div class="domi-field">
|
||||||
|
{#if i === 0}<label class="domi-field-label" for={fieldId(f)}>Send traffic to</label>{/if}
|
||||||
|
<div class="row">
|
||||||
|
<input id={fieldId(f)} class="domi-input" bind:value={host.upstreams[i]} autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
|
||||||
|
aria-label={i === 0 ? undefined : `Also send traffic to, address ${i + 1}`}
|
||||||
|
aria-invalid={err && (touched[f] || touched["upstreams"]) ? "true" : undefined}
|
||||||
|
aria-describedby="{fieldId(f)}-e" onblur={() => blur(f)} />
|
||||||
|
{#if i > 0}<button type="button" class="ia-icon-btn" aria-label="Remove this address" onclick={() => host.upstreams.splice(i, 1)}><Icon name="trash" /></button>{/if}
|
||||||
|
</div>
|
||||||
|
{#if err && (touched[f] || touched["upstreams"])}
|
||||||
|
<p class="domi-error" id="{fieldId(f)}-e"><Icon name="ring" />{err.message}
|
||||||
|
{#if err.params?.suggestion}<button type="button" class="domi-btn link" onclick={() => { host.upstreams[i] = err.params.suggestion; blur(f); }}>Use {err.params.suggestion}</button>{/if}
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
{#if i === 0 && host.upstreams.length === 1}<p class="ia-hint">Add another address later for a second server.</p>{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
<div><button type="button" class="domi-btn link" onclick={() => host.upstreams.push("")}>Add another address</button></div>
|
||||||
|
|
||||||
|
<Segmented legend="Certificate" name="tls" bind:value={host.tls}
|
||||||
|
options={[{ value: "domi", label: "Domi certificate" }, { value: "letsencrypt", label: "Let's Encrypt" }]} />
|
||||||
|
<p class="ia-hint">Domi for home devices only; Let's Encrypt for a public site.</p>
|
||||||
|
|
||||||
|
<Segmented legend="Who can open it" name="auth" bind:value={host.auth} disabled={signinOk ? [] : ["forward-auth"]}
|
||||||
|
options={[{ value: "forward-auth", label: "Sign in first" }, { value: "none", label: "Anyone" }]} />
|
||||||
|
{#if !signinOk}<p class="ia-hint">Sign-in is not set up on this server yet, so choose Anyone for now. To set it up, add the Authelia address to ianitor.toml in the routes repository.</p>{/if}
|
||||||
|
{#if errAt("auth")}<p class="domi-error"><Icon name="ring" />{errAt("auth").message}</p>{/if}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button type="button" class="domi-btn link" aria-expanded={more} aria-controls="more-options" onclick={() => (more = !more)}>
|
||||||
|
More options: headers, websockets, health check, share links, visit log
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{#if more}
|
||||||
|
<div id="more-options" class="more">
|
||||||
|
<div class="domi-field">
|
||||||
|
<span class="domi-field-label">Health check</span>
|
||||||
|
<label class="ia-check"><input type="checkbox" bind:checked={host.hc} /> Check that it answers</label>
|
||||||
|
<p class="ia-hint">Ianitor asks this address regularly and shows the result on the main screen.</p>
|
||||||
|
</div>
|
||||||
|
{#if host.hc}
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for={fieldId("health_check.path")}>Health check address</label>
|
||||||
|
<input id={fieldId("health_check.path")} class="domi-input" bind:value={host.hcPath} aria-invalid={errAt("health_check.path") ? "true" : undefined} onblur={() => blur("health_check.path")} />
|
||||||
|
{#if errAt("health_check.path")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.path").message}</p>{/if}
|
||||||
|
<p class="ia-hint">Use an address that answers without signing in, like /health.</p>
|
||||||
|
</div>
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for={fieldId("health_check.interval_secs")}>Checks every</label>
|
||||||
|
<div class="row"><input id={fieldId("health_check.interval_secs")} class="domi-input narrow" type="number" min="1" max="3600" bind:value={host.hcEvery} onblur={() => blur("health_check.interval_secs")} /> <span class="ia-text2">seconds</span></div>
|
||||||
|
{#if errAt("health_check.interval_secs")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.interval_secs").message}</p>{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div class="domi-field">
|
||||||
|
<span class="domi-field-label">Websockets</span>
|
||||||
|
<label class="ia-check"><input type="checkbox" bind:checked={host.websockets} /> Allow websockets</label>
|
||||||
|
<p class="ia-hint">Live updates for apps like Home Assistant. Leave on unless you know the app does not need them.</p>
|
||||||
|
</div>
|
||||||
|
<div class="domi-field">
|
||||||
|
<span class="domi-field-label">Share links</span>
|
||||||
|
<label class="ia-check"><input type="checkbox" bind:checked={host.share_links} /> Allow share links</label>
|
||||||
|
<p class="ia-hint">Lets you make links that open this host without signing in, until they expire.</p>
|
||||||
|
{#if shareWarning}<p class="ia-hint">Anyone can already open {name}, so a share link changes nothing.</p>{/if}
|
||||||
|
</div>
|
||||||
|
<div class="domi-field">
|
||||||
|
<span class="domi-field-label">Device certificates</span>
|
||||||
|
<label class="ia-check"><input type="checkbox" bind:checked={host.device_certs} /> Only devices with a Domi device certificate</label>
|
||||||
|
<p class="ia-hint">Phones, computers and apps need a certificate from Certificates before they can open it.</p>
|
||||||
|
</div>
|
||||||
|
<Segmented legend="Visit log" name="access_log" bind:value={host.access_log} options={[{ value: "off", label: "Off" }, { value: "truncated", label: "On" }]} />
|
||||||
|
<p class="ia-hint">On keeps a log on this server, with visitor addresses shortened.</p>
|
||||||
|
{#each [{ list: "request_headers", rules: host.req, title: "Header rules sent to your service", secrets: true }, { list: "response_headers", rules: host.resp, title: "Header rules sent back to visitors", secrets: false }] as group (group.list)}
|
||||||
|
<div class="domi-field">
|
||||||
|
<span class="domi-field-label">{group.title}</span>
|
||||||
|
{#each group.rules as r, i (i)}
|
||||||
|
{@const p = `${group.list}[${i}]`}
|
||||||
|
<div class="rule ia-card">
|
||||||
|
<Segmented legend="Rule {i + 1}" name="{p}-action" bind:value={r.action} options={[{ value: "set", label: "Set" }, { value: "remove", label: "Remove" }]} />
|
||||||
|
<label class="domi-field-label" for={fieldId(p + ".name")}>Header name</label>
|
||||||
|
<input id={fieldId(p + ".name")} class="domi-input" bind:value={r.name} onblur={() => blur(p + ".name")} />
|
||||||
|
{#if r.action === "set"}
|
||||||
|
{#if group.secrets}
|
||||||
|
<Segmented legend="Value" name="{p}-kind" bind:value={r.kind} disabled={(site?.secrets.length ?? 0) === 0 ? ["secret"] : []} options={[{ value: "value", label: "Fixed value" }, { value: "secret", label: "Secret" }]} />
|
||||||
|
{/if}
|
||||||
|
{#if r.kind === "secret" && group.secrets}
|
||||||
|
<select class="domi-input" bind:value={r.secret} aria-label="Secret">
|
||||||
|
{#each site?.secrets ?? [] as s (s)}<option value={s}>{s}</option>{/each}
|
||||||
|
</select>
|
||||||
|
{:else}
|
||||||
|
<input class="domi-input" bind:value={r.value} aria-label="Value" onblur={() => blur(p + ".value")} />
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
{#each Object.entries(errors).filter(([k]) => k.startsWith(p)) as [, e] (e.code + e.field)}<p class="domi-error"><Icon name="ring" />{e.message}</p>{/each}
|
||||||
|
<button type="button" class="ia-icon-btn" aria-label="Remove this rule" onclick={() => group.rules.splice(i, 1)}><Icon name="trash" /></button>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
<div><button type="button" class="domi-btn link" onclick={() => group.rules.push({ action: "set", name: "", kind: "value", value: "", secret: site?.secrets[0] ?? "" })}>Add a rule</button></div>
|
||||||
|
{#if group.secrets && (site?.secrets.length ?? 0) === 0}<p class="ia-hint">No secrets are listed in ianitor.toml.</p>{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#snippet footer()}
|
||||||
|
{#if phase === "form" && !loading && !notFound}
|
||||||
|
{#if underFooter}<p class="ia-hint full" role="status">{underFooter}</p>{/if}
|
||||||
|
{#if blocked}<p class="ia-hint full" id="apply-blocked">{blocked}</p>{/if}
|
||||||
|
<Button onclick={onclose}>Cancel</Button>
|
||||||
|
<Button variant="primary" type="submit" form="host-form" disabled={!!blocked} describedby={blocked ? "apply-blocked" : undefined}>Apply</Button>
|
||||||
|
{:else if phase === "progress" && apply && FINAL.includes(apply.state)}
|
||||||
|
<Button onclick={onclose}>Close</Button>
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
form { display: flex; flex-direction: column; gap: 16px; }
|
||||||
|
.row { display: flex; gap: 8px; align-items: center; }
|
||||||
|
.more { display: flex; flex-direction: column; gap: 16px; }
|
||||||
|
.rule { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.narrow { max-width: 8rem; }
|
||||||
|
.full { flex-basis: 100%; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §13.5: the intermediate banner. Renew is 1 click; the banner then shows the match
|
||||||
|
// code. Until Custos can sign (docs/custos-ticket.md) the request is signed by hand offline,
|
||||||
|
// so the waiting banner links to that page.
|
||||||
|
import { Banner, Button } from "@ianitor/ui";
|
||||||
|
import { del, post, sentence } from "../lib/api";
|
||||||
|
import { app, navigate, refresh, secondsLeft } from "../lib/app.svelte";
|
||||||
|
import { duration, longDate } from "../lib/format";
|
||||||
|
import type { PkiRequest } from "../lib/types";
|
||||||
|
|
||||||
|
const i = $derived(app.overview?.intermediate ?? null);
|
||||||
|
let pending = $state(false);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
|
||||||
|
async function renew() {
|
||||||
|
pending = true;
|
||||||
|
problem = null;
|
||||||
|
try {
|
||||||
|
await post<PkiRequest>("/certs/intermediate/renewal");
|
||||||
|
await refresh();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
} finally {
|
||||||
|
pending = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cancel(id: string) {
|
||||||
|
try {
|
||||||
|
await del(`/pki-requests/${encodeURIComponent(id)}`);
|
||||||
|
await refresh();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if app.renewedUntil}
|
||||||
|
<Banner tone="kept" live="status" ondismiss={() => (app.renewedUntil = null)}>
|
||||||
|
{#snippet title()}Renewed. The Domi intermediate certificate is now valid until {longDate(app.renewedUntil, false)}.{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{:else if i?.renewal}
|
||||||
|
{@const r = i.renewal}
|
||||||
|
<Banner tone="notice" label="Domi intermediate certificate">
|
||||||
|
{#snippet title()}
|
||||||
|
<span tabindex="-1">Sign the renewal on the offline computer. The next page has the files, the command and a fingerprint to check.</span>
|
||||||
|
{/snippet}
|
||||||
|
The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if}
|
||||||
|
{#snippet actions()}
|
||||||
|
<Button variant="outline" onclick={() => navigate("/certificates/renew-by-hand")}>Sign it by hand</Button>
|
||||||
|
<Button onclick={() => cancel(r.request_id)}>Cancel request</Button>
|
||||||
|
{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{:else if i?.banner}
|
||||||
|
<Banner tone={i.state === "due" ? "notice" : "down"} label="Domi intermediate certificate">
|
||||||
|
{#snippet title()}<strong>{i.banner?.message}</strong>{/snippet}
|
||||||
|
{i.state === "missing" ? "Setting it up makes a request that the Domi root signs on the offline computer." : "Renewing makes a request that the Domi root signs on the offline computer."}
|
||||||
|
{#if problem} {problem}{/if}
|
||||||
|
{#snippet actions()}<Button variant="outline" onclick={renew} {pending}>{i.state === "missing" ? "Set up" : "Renew"}</Button>{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{/if}
|
||||||
|
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §8.2: mint on open (click 2), Copy link (click 3). Changing an option re-mints with
|
||||||
|
// `replaces`, so one link from this dialog is valid at a time; closing without copying stops it.
|
||||||
|
// Links off: "Turn on share links" applies the change, then Copy link (4 clicks: open
|
||||||
|
// question Q1 is not decided, so this is the fallback path the design allows).
|
||||||
|
import { onDestroy, onMount } from "svelte";
|
||||||
|
import { Banner, Button, Dialog, Icon, Segmented } from "@ianitor/ui";
|
||||||
|
import ApplyProgress from "./ApplyProgress.svelte";
|
||||||
|
import { ApiError, call, del, newKey, patch, sentence } from "../lib/api";
|
||||||
|
import { app } from "../lib/app.svelte";
|
||||||
|
import { follow } from "../lib/applies";
|
||||||
|
import { longDate } from "../lib/format";
|
||||||
|
import type { ApplyView, MintedLink } from "../lib/types";
|
||||||
|
|
||||||
|
let { hostname, onclose }: { hostname: string; onclose: () => void } = $props();
|
||||||
|
|
||||||
|
// Known before the Dialog mounts, so its focus lands on Copy link (§2.9), not the title.
|
||||||
|
// svelte-ignore state_referenced_locally
|
||||||
|
let on = $state(!!app.overview?.hosts.find((h) => h.hostname === hostname)?.share_links);
|
||||||
|
let link = $state<MintedLink | null>(null);
|
||||||
|
let minting = $state(false);
|
||||||
|
let copied = $state(false);
|
||||||
|
let copiedBefore = $state(false);
|
||||||
|
let refused = $state(false);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
let fieldErr = $state<{ field: string; message: string } | null>(null);
|
||||||
|
let days = $state<"1" | "7" | "30">("7");
|
||||||
|
let prefix = $state("/");
|
||||||
|
let showPassword = $state(false);
|
||||||
|
let password = $state("");
|
||||||
|
let usingPassword = $state(false);
|
||||||
|
let turning = $state<ApplyView | null>(null);
|
||||||
|
let stopFollow: (() => void) | undefined;
|
||||||
|
let secretBox: HTMLTextAreaElement | undefined = $state();
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
if (on) void mint();
|
||||||
|
});
|
||||||
|
onDestroy(() => stopFollow?.());
|
||||||
|
|
||||||
|
async function mint() {
|
||||||
|
minting = true;
|
||||||
|
problem = null;
|
||||||
|
fieldErr = null;
|
||||||
|
try {
|
||||||
|
const body: Record<string, unknown> = { path_prefix: prefix || "/", expires_in_s: Number(days) * 86400 };
|
||||||
|
if (usingPassword && password) body.password = password;
|
||||||
|
if (link) body.replaces = link.id;
|
||||||
|
const a = await call<MintedLink>("POST", `/hosts/${encodeURIComponent(hostname)}/share-links`, body, { idem: newKey() });
|
||||||
|
if (link && copied) copiedBefore = true;
|
||||||
|
link = a.data;
|
||||||
|
copied = false;
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError && e.body.field) {
|
||||||
|
fieldErr = { field: e.body.field, message: e.body.message };
|
||||||
|
if (e.body.field === "password") usingPassword = false;
|
||||||
|
}
|
||||||
|
else problem = sentence(e);
|
||||||
|
} finally {
|
||||||
|
minting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copy() {
|
||||||
|
if (!link) return;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(link.url);
|
||||||
|
copied = true;
|
||||||
|
refused = false;
|
||||||
|
} catch {
|
||||||
|
refused = true;
|
||||||
|
secretBox?.select();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function turnOn() {
|
||||||
|
try {
|
||||||
|
const a = await patch<{ apply: ApplyView }>(`/hosts/${encodeURIComponent(hostname)}`, { share_links: true, base_rev: app.overview?.rev ?? null });
|
||||||
|
turning = a.apply;
|
||||||
|
stopFollow = follow(a.apply.id, async (x) => {
|
||||||
|
turning = x;
|
||||||
|
if (x.state === "kept") {
|
||||||
|
on = true;
|
||||||
|
await mint();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
// A link nobody copied does not stay valid.
|
||||||
|
if (link && !copied) void del(`/share-links/${encodeURIComponent(link.id)}`, { keepalive: true }).catch(() => {});
|
||||||
|
onclose();
|
||||||
|
}
|
||||||
|
|
||||||
|
const underCaddy = $derived(app.overview?.engine.running === "caddy");
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Dialog title="Share {hostname}" onclose={close}>
|
||||||
|
{#if !on}
|
||||||
|
{#if turning}
|
||||||
|
<ApplyProgress apply={turning} />
|
||||||
|
{#if turning.state === "reverted" || turning.state === "failed"}
|
||||||
|
<Banner tone="notice" live="status">{#snippet title()}Share links were not turned on. {turning?.reason?.message}{/snippet}</Banner>
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<p><strong>Share links are off for {hostname}.</strong></p>
|
||||||
|
<p class="ia-text2">Turning them on is a change to the host, checked like any other.</p>
|
||||||
|
{#if problem}<p class="domi-error" role="alert"><Icon name="ring" />{problem}</p>{/if}
|
||||||
|
<div><Button variant="outline" onclick={turnOn} disabled={!!app.overview?.paused}>Turn on share links</Button></div>
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<p class="ia-text2">Anyone with this link can open the site without signing in, until it expires.</p>
|
||||||
|
{#if underCaddy}
|
||||||
|
<Banner tone="notice">{#snippet title()}Caddy is serving right now, so share links do not work: visitors with this link get the normal sign-in. The link works after switching back to Pingora, until it expires.{/snippet}</Banner>
|
||||||
|
{/if}
|
||||||
|
{#if link?.warning}<p class="ia-hint">{link.warning.message}</p>{/if}
|
||||||
|
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||||
|
{#if link}
|
||||||
|
<textarea bind:this={secretBox} class="ia-secret" readonly value={link.url} aria-label="Share link" onfocus={(e) => (e.currentTarget as HTMLTextAreaElement).select()}></textarea>
|
||||||
|
{:else if minting}
|
||||||
|
<p class="ia-muted">Making the link…</p>
|
||||||
|
{/if}
|
||||||
|
{#if copied}
|
||||||
|
<p class="ia-status" data-s="kept" role="status"><Icon name="check" /><span>Copied</span></p>
|
||||||
|
<p class="ia-hint">Expires on {longDate(link?.expires_at)}. To stop it sooner: Settings, Share links, Stop this link.</p>
|
||||||
|
{:else}
|
||||||
|
<Button variant="primary" full icon="copy" onclick={copy} disabled={!link || minting} data-autofocus>Copy link</Button>
|
||||||
|
{/if}
|
||||||
|
{#if refused}<p class="ia-hint" role="alert">Your browser did not allow copying. Press Ctrl+C to copy the selected link.</p>{/if}
|
||||||
|
{#if copiedBefore && !copied}<p class="ia-hint">The link you copied before is stopped. Copy this one.</p>{/if}
|
||||||
|
|
||||||
|
<Segmented legend="Expires after" name="expiry" bind:value={days} onchange={() => mint()}
|
||||||
|
options={[{ value: "1", label: "1 day" }, { value: "7", label: "7 days" }, { value: "30", label: "30 days" }]} />
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for="share-prefix">Only addresses starting with</label>
|
||||||
|
<input id="share-prefix" class="domi-input" bind:value={prefix} onblur={() => mint()} onkeydown={(e) => { if (e.key === "Enter") { e.preventDefault(); void mint(); } }}
|
||||||
|
aria-invalid={fieldErr?.field === "path_prefix" ? "true" : undefined} />
|
||||||
|
{#if fieldErr?.field === "path_prefix"}<p class="domi-error"><Icon name="ring" />{fieldErr.message}</p>{/if}
|
||||||
|
<p class="ia-hint">/ shares the whole site. Try /share/summer-2026 for one album.</p>
|
||||||
|
</div>
|
||||||
|
{#if usingPassword}
|
||||||
|
<p class="ia-hint">This link asks for the password.</p>
|
||||||
|
<div><button type="button" class="domi-btn link" onclick={() => { usingPassword = false; password = ""; void mint(); }}>Remove the password</button></div>
|
||||||
|
{:else if showPassword}
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for="share-password">Password</label>
|
||||||
|
<input id="share-password" class="domi-input" type="password" autocomplete="new-password" bind:value={password}
|
||||||
|
aria-invalid={fieldErr?.field === "password" ? "true" : undefined} />
|
||||||
|
{#if fieldErr?.field === "password"}<p class="domi-error"><Icon name="ring" />{fieldErr.message}</p>{/if}
|
||||||
|
<p class="ia-hint">At least 8 characters. Send it to them separately.</p>
|
||||||
|
<div><Button onclick={() => { usingPassword = true; void mint(); }}>Use this password</Button></div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div><button type="button" class="domi-btn link" onclick={() => (showPassword = true)}>Add a password</button></div>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</Dialog>
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// T4: the team without Authelia. Invite: Settings → Team → Invite (3 clicks), then Copy link.
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { Banner, Button, Segmented } from "@ianitor/ui";
|
||||||
|
import { del, get, post, put, sentence } from "../lib/api";
|
||||||
|
import { toast } from "../lib/app.svelte";
|
||||||
|
import { shortDate } from "../lib/format";
|
||||||
|
import type { TeamView } from "../lib/types";
|
||||||
|
|
||||||
|
let team = $state<TeamView | null>(null);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
let name = $state("");
|
||||||
|
let role = $state<"member" | "admin">("member");
|
||||||
|
let link = $state<string | null>(null);
|
||||||
|
let confirmRemove = $state<string | null>(null);
|
||||||
|
let root = $state("");
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
team = await get<TeamView>("/team");
|
||||||
|
root = team.me?.tessera_root ?? "";
|
||||||
|
problem = null;
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onMount(() => void load());
|
||||||
|
|
||||||
|
async function invite() {
|
||||||
|
try {
|
||||||
|
const r = await post<{ link_fragment: string }>("/team/invites", { name: name.trim(), role });
|
||||||
|
link = `${location.origin}/${r.link_fragment}`;
|
||||||
|
name = "";
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copy() {
|
||||||
|
if (!link) return;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(link);
|
||||||
|
toast("Copied. Send it to them; it works once, for 7 days.");
|
||||||
|
} catch {
|
||||||
|
problem = "Your browser did not allow copying. Select the link and press Ctrl+C.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: string) {
|
||||||
|
try {
|
||||||
|
await del(`/team/members/${encodeURIComponent(id)}`);
|
||||||
|
confirmRemove = null;
|
||||||
|
toast("Removed and signed out everywhere.");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveRoot() {
|
||||||
|
try {
|
||||||
|
await put("/team/me/root", { tessera_root: root.trim() || null });
|
||||||
|
toast("Saved.");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = $derived(team?.me ? team.me.role === "admin" : true);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||||
|
{#if team?.authelia}
|
||||||
|
<p class="ia-hint">Authelia signs people in on this server. Team links work too.</p>
|
||||||
|
{/if}
|
||||||
|
<h2 class="ia-h3">People</h2>
|
||||||
|
<ul class="rows">
|
||||||
|
{#each team?.members ?? [] as m (m.id)}
|
||||||
|
<li>
|
||||||
|
<div class="grow"><strong>{m.name}</strong>{team?.me?.id === m.id ? " (you)" : ""}
|
||||||
|
<span class="ia-sub" style="display:block">{m.role} · since {shortDate(m.added_at)}{m.match_code ? ` · Domi identity ${m.match_code}` : ""}</span></div>
|
||||||
|
{#if admin && team?.me?.id !== m.id}
|
||||||
|
{#if confirmRemove === m.id}
|
||||||
|
<span>Remove {m.name}? They are signed out everywhere.</span>
|
||||||
|
<Button small onclick={() => (confirmRemove = null)}>Keep</Button>
|
||||||
|
<Button small variant="danger" onclick={() => remove(m.id)}>Remove</Button>
|
||||||
|
{:else}
|
||||||
|
<Button small variant="danger" onclick={() => (confirmRemove = m.id)}>Remove</Button>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
{#if admin}
|
||||||
|
<div class="row">
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for="invite-name">Name</label>
|
||||||
|
<input id="invite-name" class="domi-input" bind:value={name} placeholder="Petra" />
|
||||||
|
</div>
|
||||||
|
<Segmented legend="Role" name="invite-role" bind:value={role} options={[{ value: "member", label: "Member" }, { value: "admin", label: "Admin" }]} />
|
||||||
|
<Button variant="outline" icon="plus" onclick={invite} disabled={!name.trim()}>Invite</Button>
|
||||||
|
</div>
|
||||||
|
<p class="ia-hint">Members change hosts and previews. Admins also manage people, API tokens, the engine and certificates.</p>
|
||||||
|
{#if link}
|
||||||
|
<div class="grid">
|
||||||
|
<input class="ia-secret" readonly value={link} aria-label="Invite link" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} />
|
||||||
|
<Button variant="primary" icon="copy" onclick={copy} data-autofocus>Copy link</Button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if team?.me}
|
||||||
|
<h2 class="ia-h3">Your Domi identity</h2>
|
||||||
|
<div class="row">
|
||||||
|
<div class="domi-field grow">
|
||||||
|
<label class="domi-field-label" for="tessera-root">Tessera root (Custos → Domi identity)</label>
|
||||||
|
<input id="tessera-root" class="domi-input" bind:value={root} spellcheck="false" />
|
||||||
|
</div>
|
||||||
|
<Button onclick={saveRoot}>Save</Button>
|
||||||
|
</div>
|
||||||
|
<p class="ia-hint">Your teammates see its match code next to your name, the same digits Custos shows.</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.rows { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.rows li { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; min-height: 44px; padding: 8px 0; border-top: 1px solid var(--hairline); }
|
||||||
|
.grow { flex: 1 1 200px; min-width: 0; }
|
||||||
|
.row { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; }
|
||||||
|
.grid { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: end; }
|
||||||
|
@media (max-width: 719.98px) { .grid { grid-template-columns: 1fr; } }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §2.8 order: paused / needs attention, lost contact, health unavailable, the Caddy
|
||||||
|
// notice, then (on Hosts) the intermediate banner. First on every screen.
|
||||||
|
import { Banner, Button, Details } from "@ianitor/ui";
|
||||||
|
import { app, refresh, restorable as canRestore, restoreLastKept } from "../lib/app.svelte";
|
||||||
|
import { atTime, whenInline } from "../lib/format";
|
||||||
|
|
||||||
|
const o = $derived(app.overview);
|
||||||
|
let restoring = $state(false);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
|
||||||
|
const restorable = $derived(canRestore());
|
||||||
|
|
||||||
|
async function restore() {
|
||||||
|
restoring = true;
|
||||||
|
problem = await restoreLastKept();
|
||||||
|
restoring = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// §7.6: the bold line and line 2 by the pause's underlying code.
|
||||||
|
const pause = $derived.by(() => {
|
||||||
|
const code = o?.paused_reason ?? "";
|
||||||
|
const message = o?.paused?.message ?? "";
|
||||||
|
if (code === "apply.needs_attention")
|
||||||
|
return { bold: "Ianitor could not undo a failed change.", line2: "Visitors are served the last good settings, but the routes repository still has the change. Restore the last kept version to make them match again.", extra: "" };
|
||||||
|
if (code === "control.files_unwritten")
|
||||||
|
return { bold: "The change is live, but Ianitor could not save the proxy settings to disk.", line2: "Changes are paused until Ianitor restarts and saves them. Restoring the last kept version also clears this.", extra: "On the server: sudo systemctl restart ianitor-control" };
|
||||||
|
// control.paused wraps the reason: "Changes are paused: <reason>"; show the reason itself.
|
||||||
|
const own = message.replace(/^Changes are paused: /, "");
|
||||||
|
if (/^(repo|file|site)\./.test(code))
|
||||||
|
return { bold: own, line2: `Fix the file in the ${o?.repo?.name ?? "routes"} repository; Ianitor picks it up by itself.`, extra: "" };
|
||||||
|
return { bold: own, line2: "", extra: "" };
|
||||||
|
});
|
||||||
|
|
||||||
|
// "Show details" for every pause (§7.6): the server's detail, the restart command, or the
|
||||||
|
// full message when there is nothing more.
|
||||||
|
const pauseDetail = $derived(
|
||||||
|
[o?.paused_detail, pause.extra].filter(Boolean).join("\n") || (o?.paused ? (o.paused.message ?? "") : ""),
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
async function retry() {
|
||||||
|
await refresh();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if o?.paused}
|
||||||
|
<Banner tone="down" live="alert">
|
||||||
|
{#snippet title()}<span class="ia-status" data-s="down"><span class="word">{o.paused_reason === "apply.needs_attention" ? "needs attention" : "paused"}</span></span> <strong>{pause.bold}</strong>{/snippet}
|
||||||
|
{#if pause.line2}<span class="line2">{pause.line2}</span>{/if}
|
||||||
|
{#if restorable && o.undo?.target}<p class="ia-hint">Goes back to "{o.undo.target.summary}" from {whenInline(o.undo.target.kept_at, app.now)}. It is checked like any change.</p>{/if}
|
||||||
|
{#if problem}<p role="status">{problem}</p>{/if}
|
||||||
|
{#if pauseDetail}<Details detail={pauseDetail} />{/if}
|
||||||
|
{#snippet actions()}
|
||||||
|
{#if restorable}<Button variant="primary" onclick={restore} pending={restoring}>Restore the last kept version</Button>{/if}
|
||||||
|
{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if app.lostContact}
|
||||||
|
<Banner tone="down" live="alert">
|
||||||
|
{#snippet title()}<strong>{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."}</strong>{/snippet}
|
||||||
|
Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {atTime(new Date(app.lastUpdated).toISOString(), app.now)}.{/if}
|
||||||
|
{#snippet actions()}<Button onclick={retry}>Try again now</Button>{/snippet}
|
||||||
|
</Banner>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if o?.health_error}
|
||||||
|
<Banner tone="notice">{#snippet title()}{o.health_error?.message}{/snippet}</Banner>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if app.switchResult}
|
||||||
|
{@const r = app.switchResult}
|
||||||
|
<Banner tone={r.ok ? "kept" : "down"} live="status" ondismiss={() => (app.switchResult = null)}>
|
||||||
|
{#snippet title()}<strong>{r.title}</strong>{/snippet}
|
||||||
|
{r.text}
|
||||||
|
{#if r.detail}<Details detail={r.detail} />{/if}
|
||||||
|
</Banner>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if o?.engine.running === "caddy" && (o.hosts.some((h) => h.share_links) ?? false)}
|
||||||
|
<Banner tone="notice">{#snippet title()}Caddy is serving (the fallback), so share links do not work until you switch back.{/snippet}</Banner>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// The one typed API client (handoff §0, §10, §11). It owns the base path, the UI header (CSRF),
|
||||||
|
// redirect: "manual" (sign-out detection), Idempotency-Keys, the error envelope, the server
|
||||||
|
// clock offset, rate-limit and in-progress retries, and lost-contact detection. It decides
|
||||||
|
// nothing about the data.
|
||||||
|
|
||||||
|
import type { ErrorBody, ErrorEnvelope } from "./types";
|
||||||
|
|
||||||
|
export const BASE = "/api/v1";
|
||||||
|
|
||||||
|
/** A refusal from control, with its envelope. */
|
||||||
|
export class ApiError extends Error {
|
||||||
|
constructor(
|
||||||
|
public status: number,
|
||||||
|
public body: ErrorBody,
|
||||||
|
public errors: ErrorBody[],
|
||||||
|
public requestId: string,
|
||||||
|
) {
|
||||||
|
super(body.message);
|
||||||
|
}
|
||||||
|
get code(): string {
|
||||||
|
return this.body.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Authelia's portal redirect, or a 401 without Ianitor's envelope. */
|
||||||
|
export class SignedOut extends Error {}
|
||||||
|
|
||||||
|
/** No answer (network, or a proxy error without an envelope). */
|
||||||
|
export class LostContact extends Error {}
|
||||||
|
|
||||||
|
type Listener = () => void;
|
||||||
|
|
||||||
|
export interface ClientEvents {
|
||||||
|
onSignedOut?: Listener;
|
||||||
|
onContact?: (ok: boolean) => void;
|
||||||
|
onServerTime?: (offsetMs: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let events: ClientEvents = {};
|
||||||
|
export function setClientEvents(e: ClientEvents): void {
|
||||||
|
events = e;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A key for one click; reused by every retry of that click (§11.3). */
|
||||||
|
export function newKey(): string {
|
||||||
|
if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
|
||||||
|
return Math.random().toString(36).slice(2) + Date.now().toString(36);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CallOptions {
|
||||||
|
idem?: string;
|
||||||
|
etag?: string;
|
||||||
|
/** Do not count a failure as lost contact (engine switch, §9.2). */
|
||||||
|
quiet?: boolean;
|
||||||
|
keepalive?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Answer<T> {
|
||||||
|
status: number;
|
||||||
|
data: T | null;
|
||||||
|
etag: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
|
||||||
|
function envelope(v: unknown): v is ErrorEnvelope {
|
||||||
|
return typeof v === "object" && v !== null && "error" in v && typeof (v as ErrorEnvelope).error === "object";
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function call<T>(
|
||||||
|
method: string,
|
||||||
|
path: string,
|
||||||
|
body?: unknown,
|
||||||
|
opts: CallOptions = {},
|
||||||
|
): Promise<Answer<T>> {
|
||||||
|
let rateRetried = false;
|
||||||
|
for (let attempt = 0; attempt < 12; attempt++) {
|
||||||
|
const headers: Record<string, string> = { "X-Ianitor-UI": "1", Accept: "application/json" };
|
||||||
|
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||||
|
if (opts.idem) headers["Idempotency-Key"] = opts.idem;
|
||||||
|
if (opts.etag) headers["If-None-Match"] = opts.etag;
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await fetch(BASE + path, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
redirect: "manual",
|
||||||
|
credentials: "same-origin",
|
||||||
|
keepalive: opts.keepalive,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
if (!opts.quiet) events.onContact?.(false);
|
||||||
|
throw new LostContact("no answer");
|
||||||
|
}
|
||||||
|
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400 && res.status !== 304)) {
|
||||||
|
events.onSignedOut?.();
|
||||||
|
throw new SignedOut("signed out");
|
||||||
|
}
|
||||||
|
if (res.status === 304) {
|
||||||
|
events.onContact?.(true);
|
||||||
|
return { status: 304, data: null, etag: opts.etag ?? null };
|
||||||
|
}
|
||||||
|
let json: unknown = null;
|
||||||
|
const text = await res.text();
|
||||||
|
try {
|
||||||
|
json = text ? JSON.parse(text) : null;
|
||||||
|
} catch {
|
||||||
|
json = null;
|
||||||
|
}
|
||||||
|
if (json && typeof json === "object" && "server_time" in json) {
|
||||||
|
const t = Date.parse(String((json as { server_time: string }).server_time));
|
||||||
|
if (!Number.isNaN(t)) events.onServerTime?.(t - Date.now());
|
||||||
|
}
|
||||||
|
if (!envelope(json)) {
|
||||||
|
if (res.status === 401) {
|
||||||
|
events.onSignedOut?.();
|
||||||
|
throw new SignedOut("signed out");
|
||||||
|
}
|
||||||
|
if (res.status >= 502 && res.status <= 504) {
|
||||||
|
if (!opts.quiet) events.onContact?.(false);
|
||||||
|
throw new LostContact(`proxy answered ${res.status}`);
|
||||||
|
}
|
||||||
|
events.onContact?.(true);
|
||||||
|
return { status: res.status, data: json as T, etag: res.headers.get("ETag") };
|
||||||
|
}
|
||||||
|
events.onContact?.(true);
|
||||||
|
const env = json;
|
||||||
|
if (env.error.code === "request.in_progress") {
|
||||||
|
await sleep(1000);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (env.error.code === "rate.limited" && !rateRetried) {
|
||||||
|
rateRetried = true;
|
||||||
|
await sleep(Math.min(60, env.error.retry_after_s ?? 1) * 1000);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (res.status === 401 && (env.error.code.startsWith("token.") || env.error.code.startsWith("session."))) {
|
||||||
|
// The UI holds no token: a token refusal means the sign-in did not reach control.
|
||||||
|
events.onSignedOut?.();
|
||||||
|
throw new SignedOut(env.error.message);
|
||||||
|
}
|
||||||
|
throw new ApiError(res.status, env.error, env.errors ?? [], env.request_id ?? "");
|
||||||
|
}
|
||||||
|
throw new ApiError(
|
||||||
|
409,
|
||||||
|
{
|
||||||
|
code: "request.in_progress",
|
||||||
|
message: "The first request with this Idempotency-Key is still being handled. Try again in a moment.",
|
||||||
|
field: null,
|
||||||
|
params: {},
|
||||||
|
retry_after_s: 1,
|
||||||
|
detail: null,
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
"",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const get = <T>(path: string, opts?: CallOptions) => call<T>("GET", path, undefined, opts).then((a) => a.data as T);
|
||||||
|
export const post = <T>(path: string, body: unknown = {}, opts?: CallOptions) =>
|
||||||
|
call<T>("POST", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
|
||||||
|
export const put = <T>(path: string, body: unknown, opts?: CallOptions) =>
|
||||||
|
call<T>("PUT", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
|
||||||
|
export const patch = <T>(path: string, body: unknown, opts?: CallOptions) =>
|
||||||
|
call<T>("PATCH", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
|
||||||
|
export const del = (path: string, opts?: CallOptions) => call<unknown>("DELETE", path, undefined, opts).then(() => undefined);
|
||||||
|
|
||||||
|
/** A UI sentence for request.* codes (handoff §12.4): bugs or a stale page, not user mistakes. */
|
||||||
|
export function sentence(e: unknown): string {
|
||||||
|
if (e instanceof ApiError) {
|
||||||
|
if (e.code.startsWith("request.") && e.code !== "request.in_progress") {
|
||||||
|
return "Ianitor refused this request from the page. Reload the page and try again.";
|
||||||
|
}
|
||||||
|
return e.body.message;
|
||||||
|
}
|
||||||
|
if (e instanceof LostContact) return "Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back.";
|
||||||
|
if (e instanceof SignedOut) return "Your sign-in has ended. Sign in again; this page keeps what you typed.";
|
||||||
|
return "Something went wrong.";
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state,
|
||||||
|
// the server clock offset and toasts. No business logic: everything shown comes from control.
|
||||||
|
|
||||||
|
import { call, newKey, sentence, setClientEvents } from "./api";
|
||||||
|
import type { Overview } from "./types";
|
||||||
|
|
||||||
|
export interface Toast {
|
||||||
|
id: number;
|
||||||
|
text: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const app = $state({
|
||||||
|
/** Why a `#signin=` link did not sign this browser in. */
|
||||||
|
linkProblem: null as string | null,
|
||||||
|
overview: null as Overview | null,
|
||||||
|
etag: null as string | null,
|
||||||
|
loadError: false,
|
||||||
|
lostContact: false,
|
||||||
|
lostSince: 0,
|
||||||
|
lastUpdated: 0,
|
||||||
|
signedOut: false,
|
||||||
|
offset: 0,
|
||||||
|
now: Date.now(),
|
||||||
|
path: typeof location === "undefined" ? "/" : location.pathname + location.search,
|
||||||
|
toasts: [] as Toast[],
|
||||||
|
/** Dismissed banner keys (reverted outcome, renewed, switched). */
|
||||||
|
dismissed: [] as string[],
|
||||||
|
/** The outcome of the last engine switch, until dismissed (handoff §9.2). */
|
||||||
|
switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null },
|
||||||
|
/** A renewal just installed (handoff §13.5). */
|
||||||
|
renewedUntil: null as null | string,
|
||||||
|
/** After a kept add or edit: the row whose More button gets focus (§7.5). */
|
||||||
|
focusHost: null as string | null,
|
||||||
|
/** Narrower than 720 px (the phone layout, handoff §5.2). */
|
||||||
|
phone: false,
|
||||||
|
/** Panels the main screen opens (add/edit host, share, engine). */
|
||||||
|
panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" },
|
||||||
|
});
|
||||||
|
|
||||||
|
let failures = 0;
|
||||||
|
let firstFailure = 0;
|
||||||
|
|
||||||
|
setClientEvents({
|
||||||
|
onSignedOut: () => {
|
||||||
|
app.signedOut = true;
|
||||||
|
},
|
||||||
|
onContact: (ok) => {
|
||||||
|
if (ok) {
|
||||||
|
failures = 0;
|
||||||
|
app.lostContact = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (failures === 0) firstFailure = Date.now();
|
||||||
|
failures++;
|
||||||
|
// Retry quietly for 10 s (a reload takes about 2 s), then say so (§11.1).
|
||||||
|
if (Date.now() - firstFailure >= 10_000) {
|
||||||
|
if (!app.lostContact) app.lostSince = Date.now();
|
||||||
|
app.lostContact = true;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onServerTime: (o) => {
|
||||||
|
app.offset = o;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Server time now, in ms (all countdowns use it, §7.2). */
|
||||||
|
export function serverNow(): number {
|
||||||
|
return app.now + app.offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Seconds left until an ISO time, on the server's clock. */
|
||||||
|
export function secondsLeft(iso: string | null | undefined): number {
|
||||||
|
if (!iso) return 0;
|
||||||
|
return Math.max(0, Math.ceil((Date.parse(iso) - serverNow()) / 1000));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function refresh(): Promise<void> {
|
||||||
|
if (app.signedOut) return;
|
||||||
|
try {
|
||||||
|
const a = await call<Overview>("GET", "/overview", undefined, { etag: app.etag ?? undefined });
|
||||||
|
if (a.status === 200 && a.data) {
|
||||||
|
app.overview = a.data;
|
||||||
|
app.etag = a.etag;
|
||||||
|
}
|
||||||
|
app.loadError = false;
|
||||||
|
app.lastUpdated = Date.now();
|
||||||
|
} catch {
|
||||||
|
if (!app.overview) app.loadError = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
let hiddenSince = 0;
|
||||||
|
|
||||||
|
/** Poll every 5 s while visible, 30 s when hidden, stop after 15 min hidden (Q9). */
|
||||||
|
export function startPolling(): () => void {
|
||||||
|
let stopped = false;
|
||||||
|
const tick = async () => {
|
||||||
|
if (stopped) return;
|
||||||
|
const hidden = typeof document !== "undefined" && document.visibilityState === "hidden";
|
||||||
|
if (hidden && !hiddenSince) hiddenSince = Date.now();
|
||||||
|
if (!hidden) hiddenSince = 0;
|
||||||
|
if (!(hidden && Date.now() - hiddenSince > 15 * 60_000)) await refresh();
|
||||||
|
const every = app.lostContact ? 5000 : hidden ? 30_000 : 5000;
|
||||||
|
timer = setTimeout(tick, every);
|
||||||
|
};
|
||||||
|
const vis = () => {
|
||||||
|
if (document.visibilityState === "visible" && hiddenSince) {
|
||||||
|
hiddenSince = 0;
|
||||||
|
clearTimeout(timer);
|
||||||
|
void tick();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener("visibilitychange", vis);
|
||||||
|
const clock = setInterval(() => (app.now = Date.now()), 1000);
|
||||||
|
void tick();
|
||||||
|
return () => {
|
||||||
|
stopped = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
clearInterval(clock);
|
||||||
|
document.removeEventListener("visibilitychange", vis);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let toastId = 0;
|
||||||
|
export function toast(text: string): void {
|
||||||
|
const id = ++toastId;
|
||||||
|
app.toasts = [...app.toasts.slice(-2), { id, text }];
|
||||||
|
setTimeout(() => {
|
||||||
|
app.toasts = app.toasts.filter((t) => t.id !== id);
|
||||||
|
}, 6000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function navigate(path: string): void {
|
||||||
|
if (path === app.path) return;
|
||||||
|
history.pushState({}, "", path);
|
||||||
|
app.path = path;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
|
||||||
|
const mq = window.matchMedia("(max-width: 719.98px)");
|
||||||
|
app.phone = mq.matches;
|
||||||
|
mq.addEventListener?.("change", (e) => (app.phone = e.matches));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
window.addEventListener("popstate", () => {
|
||||||
|
app.path = location.pathname + location.search;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Is a change allowed now? (Paused, or no contact.) */
|
||||||
|
export function changesBlocked(): string | null {
|
||||||
|
const o = app.overview;
|
||||||
|
if (app.lostContact) return "Ianitor's control service is not answering.";
|
||||||
|
if (o?.paused) return "Changes are paused.";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Restore the last kept version" (handoff §7.6): start it and show its progress in a panel.
|
||||||
|
* Returns the sentence to show when it could not start. */
|
||||||
|
export async function restoreLastKept(): Promise<string | null> {
|
||||||
|
const o = app.overview;
|
||||||
|
if (!o?.undo?.target) return null;
|
||||||
|
try {
|
||||||
|
const a = await call<{ apply: { id: string } }>("POST", "/restore", { change_id: o.undo.target.change_id, base_rev: o.rev }, { idem: newKey() });
|
||||||
|
if (a.data) app.panel = { kind: "host", resume: a.data.apply.id };
|
||||||
|
return null;
|
||||||
|
} catch (e) {
|
||||||
|
return sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the pause can be cleared by restoring the last kept version. */
|
||||||
|
export function restorable(): boolean {
|
||||||
|
const o = app.overview;
|
||||||
|
return !!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target;
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// Following an apply (handoff §2.2 of ui-api, §3 here): GET /applies/{id} every second while it
|
||||||
|
// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it.
|
||||||
|
|
||||||
|
import { get } from "./api";
|
||||||
|
import { app, refresh } from "./app.svelte";
|
||||||
|
import type { ApplyView } from "./types";
|
||||||
|
|
||||||
|
export const FINAL = ["kept", "reverted", "failed", "needs_attention"];
|
||||||
|
const KEY = "ianitor.activeApply";
|
||||||
|
|
||||||
|
export function remember(id: string | null): void {
|
||||||
|
try {
|
||||||
|
if (id) sessionStorage.setItem(KEY, id);
|
||||||
|
else sessionStorage.removeItem(KEY);
|
||||||
|
} catch {
|
||||||
|
/* storage may be off; the bar still shows the running apply */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function remembered(): string | null {
|
||||||
|
try {
|
||||||
|
return sessionStorage.getItem(KEY);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Poll until the apply ends. Returns a stop function. */
|
||||||
|
export function follow(id: string, onupdate: (a: ApplyView) => void, every = 1000): () => void {
|
||||||
|
let stopped = false;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
remember(id);
|
||||||
|
const tick = async () => {
|
||||||
|
if (stopped) return;
|
||||||
|
if (app.signedOut) {
|
||||||
|
// No requests while signed out (the overview poll stops too); look again shortly.
|
||||||
|
timer = setTimeout(tick, every);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const a = await get<ApplyView>(`/applies/${encodeURIComponent(id)}`);
|
||||||
|
if (stopped) return;
|
||||||
|
onupdate(a);
|
||||||
|
if (FINAL.includes(a.state)) {
|
||||||
|
remember(null);
|
||||||
|
void refresh();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* lost contact or a reload in progress: keep trying (the banner says so after 10 s) */
|
||||||
|
}
|
||||||
|
timer = setTimeout(tick, every);
|
||||||
|
};
|
||||||
|
void tick();
|
||||||
|
return () => {
|
||||||
|
stopped = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// Formatting only (handoff §3): times in the browser's zone, 24-hour clock, counts sentences.
|
||||||
|
|
||||||
|
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||||
|
const LONG = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||||
|
|
||||||
|
const two = (n: number) => String(n).padStart(2, "0");
|
||||||
|
|
||||||
|
/** "Today 14:02", "Yesterday 21:14", "5 Nov 21:14", "5 Nov 2025". */
|
||||||
|
export function when(iso: string | null | undefined, now = Date.now()): string {
|
||||||
|
if (!iso) return "";
|
||||||
|
const d = new Date(iso);
|
||||||
|
if (Number.isNaN(d.getTime())) return "";
|
||||||
|
const n = new Date(now);
|
||||||
|
const hm = `${two(d.getHours())}:${two(d.getMinutes())}`;
|
||||||
|
const sameDay = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
|
||||||
|
if (sameDay(d, n)) return `Today ${hm}`;
|
||||||
|
const y = new Date(n);
|
||||||
|
y.setDate(n.getDate() - 1);
|
||||||
|
if (sameDay(d, y)) return `Yesterday ${hm}`;
|
||||||
|
if (d.getFullYear() !== n.getFullYear()) return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`;
|
||||||
|
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Inside a sentence: "today 14:02", "yesterday 21:14", "5 Nov 21:14". */
|
||||||
|
export function whenInline(iso: string | null | undefined, now = Date.now()): string {
|
||||||
|
return when(iso, now).replace(/^(Today|Yesterday)/, (s) => s.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** After "at" / "on": "at 14:03", "yesterday at 21:14", "on 5 Nov at 21:14", "on 5 Nov 2025". */
|
||||||
|
export function atTime(iso: string | null | undefined, now = Date.now()): string {
|
||||||
|
const w = when(iso, now);
|
||||||
|
if (!w) return "";
|
||||||
|
if (w.startsWith("Today ")) return `at ${w.slice(6)}`;
|
||||||
|
if (w.startsWith("Yesterday ")) return `yesterday at ${w.slice(10)}`;
|
||||||
|
const m = /^(\d+ \w+) (\d\d:\d\d)$/.exec(w);
|
||||||
|
return m ? `on ${m[1]} at ${m[2]}` : `on ${w}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "14 November 2026 at 14:20". */
|
||||||
|
export function longDate(iso: string | null | undefined, withTime = true): string {
|
||||||
|
if (!iso) return "";
|
||||||
|
const d = new Date(iso);
|
||||||
|
if (Number.isNaN(d.getTime())) return "";
|
||||||
|
const s = `${d.getDate()} ${LONG[d.getMonth()]} ${d.getFullYear()}`;
|
||||||
|
return withTime ? `${s} at ${two(d.getHours())}:${two(d.getMinutes())}` : s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "2 Mar 2027". */
|
||||||
|
export function shortDate(iso: string | null | undefined): string {
|
||||||
|
if (!iso) return "";
|
||||||
|
const d = new Date(iso);
|
||||||
|
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "8 s", "6 minutes", "2 hours", "3 days". */
|
||||||
|
export function duration(secs: number): string {
|
||||||
|
if (secs < 60) return `${Math.max(0, Math.round(secs))} s`;
|
||||||
|
const m = Math.round(secs / 60);
|
||||||
|
if (m < 60) return m === 1 ? "1 minute" : `${m} minutes`;
|
||||||
|
const h = Math.round(secs / 3600);
|
||||||
|
if (h < 48) return h === 1 ? "1 hour" : `${h} hours`;
|
||||||
|
const days = Math.round(secs / 86400);
|
||||||
|
return `${days} days`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ago(iso: string | null | undefined, now: number): string {
|
||||||
|
if (!iso) return "";
|
||||||
|
return duration((now - Date.parse(iso)) / 1000) + " ago";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1); short (phone, §5.2): "5 healthy, 1 degraded, 1 down". */
|
||||||
|
export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }, short = false): string {
|
||||||
|
const parts = [`${c.healthy} healthy`];
|
||||||
|
if (c.degraded) parts.push(`${c.degraded} degraded`);
|
||||||
|
if (c.down) parts.push(`${c.down} down`);
|
||||||
|
if (c.unknown) parts.push(`${c.unknown} not checked`);
|
||||||
|
if (short) return parts.join(", ");
|
||||||
|
return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Split a server message on its first sentence (handoff §7.5). */
|
||||||
|
export function firstSentence(m: string): [string, string] {
|
||||||
|
const i = m.indexOf(". ");
|
||||||
|
return i < 0 ? [m, ""] : [m.slice(0, i + 1), m.slice(i + 2)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Field labels in sentences (handoff §6.5). */
|
||||||
|
export const FIELD_LABEL: Record<string, string> = {
|
||||||
|
hostname: "address",
|
||||||
|
upstreams: "sends traffic to",
|
||||||
|
tls: "certificate",
|
||||||
|
auth: "who can open it",
|
||||||
|
"health_check.path": "health check address",
|
||||||
|
"health_check.interval_secs": "checks every",
|
||||||
|
share_links: "share links",
|
||||||
|
device_certs: "device certificates",
|
||||||
|
access_log: "visit log",
|
||||||
|
websockets: "websockets",
|
||||||
|
headers: "header rules",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function fieldValue(field: string, v: string): string {
|
||||||
|
if (v === "") return "none";
|
||||||
|
if (field === "tls") return v === "domi" ? "Domi certificate" : "Let's Encrypt";
|
||||||
|
if (field === "auth") return v === "forward-auth" ? "sign in first" : "anyone";
|
||||||
|
if (field === "access_log") return v === "truncated" ? "on" : "off";
|
||||||
|
if (v === "true") return "on";
|
||||||
|
if (v === "false") return "off";
|
||||||
|
if (field === "health_check.interval_secs") return `${v} s`;
|
||||||
|
return v;
|
||||||
|
}
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// The shapes the UI reads from control (docs/api.md, docs/ui-api.md, GET /api/v1/openapi.json).
|
||||||
|
// Only the fields the UI uses are typed.
|
||||||
|
|
||||||
|
export interface ErrorBody {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
field: string | null;
|
||||||
|
params: Record<string, string>;
|
||||||
|
retry_after_s: number | null;
|
||||||
|
detail: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ErrorEnvelope {
|
||||||
|
error: ErrorBody;
|
||||||
|
errors: ErrorBody[];
|
||||||
|
request_id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Blocked {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Reason {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
hostname?: string | null;
|
||||||
|
upstream?: string | null;
|
||||||
|
field?: string | null;
|
||||||
|
detail?: string | null;
|
||||||
|
params?: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Step {
|
||||||
|
key: "validate" | "compile" | "write" | "reload" | "watch" | "push";
|
||||||
|
state: "pending" | "running" | "done" | "failed" | "skipped";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApplyView {
|
||||||
|
id: string;
|
||||||
|
change_id: string;
|
||||||
|
kind: "add" | "edit" | "remove" | "undo" | "restore" | "share_links";
|
||||||
|
summary: string;
|
||||||
|
hosts: string[];
|
||||||
|
state: "queued" | "validating" | "applying" | "watching" | "kept" | "reverted" | "failed" | "needs_attention";
|
||||||
|
created_at: string;
|
||||||
|
finished_at: string | null;
|
||||||
|
steps: Step[];
|
||||||
|
queue: { position: number; waiting_for: { apply_id: string; summary: string; seconds_left: number | null } | null } | null;
|
||||||
|
watch: { ends_at: string; seconds_left: number; hosts: { hostname: string; passed: number; failed: number; total: number }[] } | null;
|
||||||
|
reason: Reason | null;
|
||||||
|
errors: ErrorBody[];
|
||||||
|
commit_short: string | null;
|
||||||
|
push: { state: "pushed" | "pending" | "failed"; at: string | null; error_code: string | null; next_try_at: string | null } | null;
|
||||||
|
attempted_host?: HostSpec | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HeaderRule {
|
||||||
|
action: "set" | "remove";
|
||||||
|
name: string;
|
||||||
|
value?: string;
|
||||||
|
secret?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HostSpec {
|
||||||
|
hostname: string;
|
||||||
|
upstreams: string[];
|
||||||
|
tls: "domi" | "letsencrypt";
|
||||||
|
auth: "none" | "forward-auth";
|
||||||
|
websockets: boolean;
|
||||||
|
share_links: boolean;
|
||||||
|
device_certs?: boolean;
|
||||||
|
access_log: "off" | "truncated";
|
||||||
|
health_check?: { path: string; interval_secs: number } | null;
|
||||||
|
request_headers?: HeaderRule[];
|
||||||
|
response_headers?: HeaderRule[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HealthView {
|
||||||
|
state: "healthy" | "degraded" | "down" | "unknown" | "pending";
|
||||||
|
last_check_at: string | null;
|
||||||
|
latency_ms: number | null;
|
||||||
|
since: string | null;
|
||||||
|
failure: { kind: string; upstream: string | null; count: number; of: number } | null;
|
||||||
|
upstreams: { url: string; state: string; last_check_at: string | null; latency_ms: number | null; failure_kind: string | null }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HostRow {
|
||||||
|
hostname: string;
|
||||||
|
upstreams: string[];
|
||||||
|
tls: string;
|
||||||
|
auth: string;
|
||||||
|
websockets: boolean;
|
||||||
|
share_links: boolean;
|
||||||
|
device_certs: boolean;
|
||||||
|
added_at: string | null;
|
||||||
|
health: HealthView;
|
||||||
|
certificate: { state: "ok" | "pending" | "failed"; not_after: string | null; error_code: string | null };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PkiRequest {
|
||||||
|
request_id: string;
|
||||||
|
kind: "device" | "intermediate";
|
||||||
|
state: "waiting" | "approved" | "denied" | "expired" | "cancelled" | "failed";
|
||||||
|
match_code: string;
|
||||||
|
created_at: string;
|
||||||
|
expires_at: string;
|
||||||
|
approved_at: string | null;
|
||||||
|
device_id: string | null;
|
||||||
|
name: string | null;
|
||||||
|
csr_pem: string | null;
|
||||||
|
csr_sha256?: string | null;
|
||||||
|
not_after: string | null;
|
||||||
|
message_code: string;
|
||||||
|
message: string;
|
||||||
|
approve_command: string | null;
|
||||||
|
file_base?: string | null;
|
||||||
|
problem: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntermediateView {
|
||||||
|
state: "ok" | "due" | "urgent" | "expired" | "missing";
|
||||||
|
subject: string | null;
|
||||||
|
not_after: string | null;
|
||||||
|
days_left: number | null;
|
||||||
|
renewal: PkiRequest | null;
|
||||||
|
banner: Blocked | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EngineView {
|
||||||
|
running: "pingora" | "caddy";
|
||||||
|
state: "running" | "switching" | "stopped";
|
||||||
|
since: string | null;
|
||||||
|
target: string | null;
|
||||||
|
switchable: boolean;
|
||||||
|
fallback_ready: { built_at: string | null; current: boolean; compared: number; matched: number; differences: string[] } | null;
|
||||||
|
last_error: Reason | null;
|
||||||
|
notes: Blocked[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UndoView {
|
||||||
|
available: boolean;
|
||||||
|
target: { change_id: string; summary: string; kept_at: string | null; commit_short: string | null } | null;
|
||||||
|
effect: string | null;
|
||||||
|
blocked: Blocked | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Overview {
|
||||||
|
counts: { hosts: number; healthy: number; degraded: number; down: number; unknown: number };
|
||||||
|
hosts: HostRow[];
|
||||||
|
engine: EngineView;
|
||||||
|
last_apply: ApplyView | null;
|
||||||
|
undo: UndoView;
|
||||||
|
active_apply: { id: string; state: string; summary: string; seconds_left: number | null; kind: string; hosts: string[]; watch_ends_at: string | null; queued: number } | null;
|
||||||
|
repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null;
|
||||||
|
intermediate: IntermediateView | null;
|
||||||
|
site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean; auth_logout_url?: string | null } | null;
|
||||||
|
paused: Blocked | null;
|
||||||
|
paused_reason: string | null;
|
||||||
|
paused_detail?: string | null;
|
||||||
|
health_error: Blocked | null;
|
||||||
|
rev: string | null;
|
||||||
|
viewer?: { name: string; via: string } | null;
|
||||||
|
server_time: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HistoryEntry {
|
||||||
|
change_id: string;
|
||||||
|
summary: string;
|
||||||
|
kind: string;
|
||||||
|
state: string;
|
||||||
|
at: string;
|
||||||
|
commit_short: string | null;
|
||||||
|
hosts: string[];
|
||||||
|
reason_short: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RestorePreview {
|
||||||
|
restorable: boolean;
|
||||||
|
same_as_current: boolean;
|
||||||
|
changes: { hostname: string; effect: "added" | "removed" | "changed"; fields: { field: string; from: string; to: string }[] }[];
|
||||||
|
blocked: Blocked | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShareLink {
|
||||||
|
id: string;
|
||||||
|
hostname: string;
|
||||||
|
path_prefix: string;
|
||||||
|
created_at: string;
|
||||||
|
expires_at: string;
|
||||||
|
has_password: boolean;
|
||||||
|
state: "active" | "expired" | "stopped";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MintedLink {
|
||||||
|
id: string;
|
||||||
|
url: string;
|
||||||
|
expires_at: string;
|
||||||
|
path_prefix: string;
|
||||||
|
has_password: boolean;
|
||||||
|
warning: Blocked | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TokenRow {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
created_at: string;
|
||||||
|
last_used_at: string | null;
|
||||||
|
expires_at: string | null;
|
||||||
|
revoked_at?: string | null;
|
||||||
|
scope?: "full" | "previews";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreatedToken {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
token: string;
|
||||||
|
expires_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeviceRow {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
kind: "phone" | "computer" | "app";
|
||||||
|
created_at: string;
|
||||||
|
not_after: string;
|
||||||
|
state: "valid" | "revoked" | "expired";
|
||||||
|
revoked_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CertsView {
|
||||||
|
intermediate: IntermediateView | null;
|
||||||
|
root: { offline: boolean; subject: string; not_after: string; sha256: string };
|
||||||
|
devices: DeviceRow[];
|
||||||
|
device_lifetime_days: number;
|
||||||
|
device_valid_until: string | null;
|
||||||
|
server_lifetime_days: number;
|
||||||
|
approval: string;
|
||||||
|
requests: PkiRequest[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Bundle {
|
||||||
|
download_url: string;
|
||||||
|
one_time_password: string;
|
||||||
|
expires_at: string;
|
||||||
|
filename: string;
|
||||||
|
qr_svg: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// T4: branch previews and the team (docs/previews.md, crate::team).
|
||||||
|
export interface PreviewView {
|
||||||
|
hostname: string;
|
||||||
|
url: string;
|
||||||
|
project: string;
|
||||||
|
branch: string;
|
||||||
|
upstream: string;
|
||||||
|
expires_at: string;
|
||||||
|
state: "applying" | "live" | "failed";
|
||||||
|
problem?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PreviewList {
|
||||||
|
items: PreviewView[];
|
||||||
|
domain: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MemberView {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
role: "admin" | "member";
|
||||||
|
added_at: string;
|
||||||
|
tessera_root: string | null;
|
||||||
|
match_code: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamView {
|
||||||
|
me: MemberView | null;
|
||||||
|
members: MemberView[];
|
||||||
|
invites: { id: string; name: string | null; role: string; expires_at: string }[];
|
||||||
|
authelia: boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
import "@ianitor/ui/tokens.css";
|
||||||
|
import "@ianitor/ui/components.css";
|
||||||
|
import { mount } from "svelte";
|
||||||
|
import App from "./App.svelte";
|
||||||
|
|
||||||
|
const target = document.getElementById("app");
|
||||||
|
if (target) mount(App, { target });
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §13: Certificates → + Device → Issue (3 clicks), approval with the match code, then
|
||||||
|
// the install (the accepted 4th click). Until Custos can approve, approval is the server
|
||||||
|
// command control names (docs/pki.md).
|
||||||
|
import { onDestroy, onMount } from "svelte";
|
||||||
|
import { Banner, Button, Dialog, Icon, Segmented, Status } from "@ianitor/ui";
|
||||||
|
import HostMenu from "../components/HostMenu.svelte";
|
||||||
|
import IntermediateBanner from "../components/IntermediateBanner.svelte";
|
||||||
|
import { ApiError, del, get, post, sentence } from "../lib/api";
|
||||||
|
import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte";
|
||||||
|
import { atTime, shortDate } from "../lib/format";
|
||||||
|
import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types";
|
||||||
|
|
||||||
|
let { newDevice }: { newDevice: boolean } = $props();
|
||||||
|
|
||||||
|
let certs = $state<CertsView | null>(null);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
let name = $state("");
|
||||||
|
let kind = $state<"phone" | "computer" | "app">("phone");
|
||||||
|
let nameErr = $state<string | null>(null);
|
||||||
|
let issuing = $state(false);
|
||||||
|
let request = $state<PkiRequest | null>(null);
|
||||||
|
let bundle = $state<{ device: DeviceRow | { id: string; name: string; kind: string }; b: Bundle; format: string } | null>(null);
|
||||||
|
let confirmRevoke = $state<string | null>(null);
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
certs = await get<CertsView>("/certs");
|
||||||
|
problem = null;
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onMount(load);
|
||||||
|
onDestroy(() => clearTimeout(timer));
|
||||||
|
|
||||||
|
async function issue(e?: Event) {
|
||||||
|
e?.preventDefault();
|
||||||
|
issuing = true;
|
||||||
|
nameErr = null;
|
||||||
|
try {
|
||||||
|
request = await post<PkiRequest>("/certs/devices", { name, kind });
|
||||||
|
poll();
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiError && err.body.field === "name") nameErr = err.body.message;
|
||||||
|
else problem = sentence(err);
|
||||||
|
} finally {
|
||||||
|
issuing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function poll() {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = setTimeout(async () => {
|
||||||
|
if (!request) return;
|
||||||
|
try {
|
||||||
|
request = await get<PkiRequest>(`/pki-requests/${encodeURIComponent(request.request_id)}`);
|
||||||
|
} catch {
|
||||||
|
/* keep waiting */
|
||||||
|
}
|
||||||
|
if (request?.state === "waiting") poll();
|
||||||
|
else void load();
|
||||||
|
}, 2000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cancelRequest() {
|
||||||
|
if (!request) return;
|
||||||
|
await del(`/pki-requests/${encodeURIComponent(request.request_id)}`).catch(() => {});
|
||||||
|
request = null;
|
||||||
|
closeForm();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function install(d: { id: string; name: string; kind: string }, format: "qr" | "p12") {
|
||||||
|
try {
|
||||||
|
const b = await post<Bundle>(`/certs/devices/${encodeURIComponent(d.id)}/bundle`, { format });
|
||||||
|
bundle = { device: d, b, format };
|
||||||
|
if (format === "p12") {
|
||||||
|
// The link's GET is only a page (so link previews cannot use it up); this browser is
|
||||||
|
// signed in on the same host, so it posts to the path and saves the file itself.
|
||||||
|
const res = await fetch(new URL(b.download_url, location.href).pathname, { method: "POST", credentials: "same-origin" });
|
||||||
|
if (!res.ok) {
|
||||||
|
problem = "The install file could not be downloaded. Choose Install again for a new link.";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const href = URL.createObjectURL(await res.blob());
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = href;
|
||||||
|
a.download = `${d.name}.p12`;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(href), 10_000);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revoke(d: DeviceRow) {
|
||||||
|
try {
|
||||||
|
await del(`/certs/devices/${encodeURIComponent(d.id)}`);
|
||||||
|
toast(`Revoked. ${d.name} can no longer get in.`);
|
||||||
|
confirmRevoke = null;
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeForm() {
|
||||||
|
clearTimeout(timer);
|
||||||
|
name = "";
|
||||||
|
nameErr = null;
|
||||||
|
if (request?.state !== "approved") request = null;
|
||||||
|
navigate("/certificates");
|
||||||
|
}
|
||||||
|
|
||||||
|
const lifetime = $derived(certs?.device_lifetime_days ?? 365);
|
||||||
|
// The server caps it at the intermediate's end (Q7); without one it cannot issue anyway.
|
||||||
|
const until = $derived(shortDate(certs?.device_valid_until ?? new Date(Date.now() + lifetime * 86_400_000).toISOString()));
|
||||||
|
const capped = $derived(
|
||||||
|
!!certs?.device_valid_until && Date.parse(certs.device_valid_until) < Date.now() + (lifetime - 1) * 86_400_000,
|
||||||
|
);
|
||||||
|
const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => {
|
||||||
|
switch (certs?.intermediate?.state) {
|
||||||
|
case "ok": return ["healthy", "valid"];
|
||||||
|
case "due": return ["degraded", "renew soon"];
|
||||||
|
case "urgent": return ["down", "renew now"];
|
||||||
|
case "expired": return ["down", "expired"];
|
||||||
|
default: return ["unknown", "not set up"];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const kindIcon = (k: string) => (k === "phone" ? "phone" : k === "computer" ? "laptop" : "app") as "phone" | "laptop" | "app";
|
||||||
|
const issuedDevice = $derived(request?.state === "approved" && request.device_id ? { id: request.device_id, name: request.name ?? name, kind } : null);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="head">
|
||||||
|
<h1 class="ia-display">Certificates</h1>
|
||||||
|
<Button variant="outline" icon="plus" label="Add a device certificate" onclick={() => navigate("/certificates/new")}>Device</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<IntermediateBanner />
|
||||||
|
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||||
|
|
||||||
|
{#if certs}
|
||||||
|
<section class="ia-card">
|
||||||
|
<p class="ia-label">Domi intermediate</p>
|
||||||
|
<p><Status kind={intState[0]} word={intState[1]} /> {#if certs.intermediate?.not_after}expires {shortDate(certs.intermediate.not_after)}{/if}</p>
|
||||||
|
<p class="ia-sub">Root stays offline ({certs.root.subject}, until {shortDate(certs.root.not_after)}).</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<p class="ia-label">Devices</p>
|
||||||
|
{#if certs.devices.length === 0}
|
||||||
|
<div class="ia-frame"><h2 class="ia-h3">No device certificates yet</h2><p class="ia-text2">A device certificate lets a phone, computer or Domi app into hosts that ask for one.</p></div>
|
||||||
|
{:else}
|
||||||
|
<ul class="devices">
|
||||||
|
{#each certs.devices as d (d.id)}
|
||||||
|
<li>
|
||||||
|
<Icon name={kindIcon(d.kind)} />
|
||||||
|
<span class="dname">{d.name}</span>
|
||||||
|
<span class="ia-muted">until {shortDate(d.not_after)}</span>
|
||||||
|
{#if d.state === "revoked"}<Status kind="unknown" word="revoked {d.revoked_at ? shortDate(d.revoked_at) : ''}" />{:else if d.state === "expired"}<Status kind="down" word="expired" />{:else if Date.parse(d.not_after) - app.now < 30 * 86_400_000}<Status kind="degraded" word="renew soon" />{/if}
|
||||||
|
{#if confirmRevoke === d.id}
|
||||||
|
<span class="confirm">Revoke the certificate of "{d.name}"? It can no longer get in.
|
||||||
|
<Button small onclick={() => (confirmRevoke = null)} data-autofocus>Cancel</Button>
|
||||||
|
<Button small variant="danger" onclick={() => revoke(d)}>Revoke</Button></span>
|
||||||
|
{:else if d.state === "valid"}
|
||||||
|
<HostMenu hostname={d.name} items={[
|
||||||
|
{ label: "Install on the device", icon: "key", run: () => install(d, d.kind === "computer" ? "p12" : "qr") },
|
||||||
|
{ label: "Revoke", icon: "trash", danger: true, divider: true, run: () => (confirmRevoke = d.id) },
|
||||||
|
]} />
|
||||||
|
{/if}
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if newDevice}
|
||||||
|
<Dialog title="New device certificate" kind="panel" onclose={closeForm}>
|
||||||
|
{#if !request}
|
||||||
|
<form id="device-form" onsubmit={issue} class="form">
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for="device-name">Device name</label>
|
||||||
|
<input id="device-name" class="domi-input" bind:value={name} autocomplete="off" aria-invalid={nameErr ? "true" : undefined} aria-describedby="device-name-h" />
|
||||||
|
{#if nameErr}<p class="domi-error"><Icon name="ring" />{nameErr}</p>{/if}
|
||||||
|
<p class="ia-hint" id="device-name-h">Shown in this list and inside the certificate.</p>
|
||||||
|
</div>
|
||||||
|
<Segmented legend="What is it" name="kind" bind:value={kind} options={[{ value: "phone", label: "Phone or tablet" }, { value: "computer", label: "Computer" }, { value: "app", label: "Domi app" }]} />
|
||||||
|
<p class="ia-hint">{#if capped}Valid until {until}, when the Domi intermediate certificate ends (renew it to issue for a full year).{:else}Valid for {lifetime} days, until {until}.{/if} It lets this device into hosts that ask for a Domi device certificate.</p>
|
||||||
|
</form>
|
||||||
|
{:else if request.state === "waiting"}
|
||||||
|
<p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p>
|
||||||
|
<p>Custos cannot approve device certificates yet, so approve it on the server, and only if it shows the same code:</p>
|
||||||
|
<p class="ia-code" aria-label="Match code {request.match_code}">{request.match_code}</p>
|
||||||
|
{#if request.approve_command}<p class="ia-hint">Run on the server:</p><pre class="ia-secret ia-cmd">{request.approve_command}</pre>{/if}
|
||||||
|
<p class="ia-muted">The request stays open for 10 minutes ({Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")} left). Nothing is issued until it is approved.</p>
|
||||||
|
<div><Button onclick={cancelRequest}>Cancel request</Button></div>
|
||||||
|
<span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span>
|
||||||
|
{:else if issuedDevice}
|
||||||
|
<Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved {atTime(request?.approved_at, app.now)}.{/snippet}</Banner>
|
||||||
|
<div class="buttons">
|
||||||
|
<Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button>
|
||||||
|
<Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button>
|
||||||
|
</div>
|
||||||
|
<p class="ia-hint">The file is protected with a one-time password shown next to the QR code.</p>
|
||||||
|
{:else}
|
||||||
|
<Banner tone="notice" live="status">{#snippet title()}{request?.message}{/snippet}
|
||||||
|
{#snippet actions()}<Button variant="outline" onclick={() => { request = null; void issue(); }}>Try again</Button>{/snippet}</Banner>
|
||||||
|
{/if}
|
||||||
|
{#snippet footer()}
|
||||||
|
{#if !request}
|
||||||
|
<Button onclick={closeForm}>Cancel</Button>
|
||||||
|
<Button variant="primary" type="submit" form="device-form" pending={issuing}>Issue</Button>
|
||||||
|
{:else if request.state !== "waiting"}
|
||||||
|
<Button onclick={() => { request = null; closeForm(); void load(); }}>Close</Button>
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
</Dialog>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if bundle}
|
||||||
|
<Dialog title="Install on {bundle.device.name}" onclose={() => { bundle = null; void refresh(); }}>
|
||||||
|
<div class="install">
|
||||||
|
{#if bundle.b.qr_svg}
|
||||||
|
<div class="ia-qr" role="img" aria-label="QR code for downloading the certificate">{@html bundle.b.qr_svg}</div>
|
||||||
|
{/if}
|
||||||
|
<div>
|
||||||
|
<p class="ia-label">Password for the file</p>
|
||||||
|
<p class="otp">{bundle.b.one_time_password}</p>
|
||||||
|
<p class="ia-hint">Works once, for 10 minutes ({Math.floor(secondsLeft(bundle.b.expires_at) / 60)}:{String(secondsLeft(bundle.b.expires_at) % 60).padStart(2, "0")} left).</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="ia-text2">
|
||||||
|
{#if bundle.device.kind === "computer"}Open the downloaded file and enter the password when it asks.
|
||||||
|
{:else if bundle.device.kind === "app"}In the app, choose Import certificate, pick the file, and enter the password.
|
||||||
|
{:else}Scan the code with the device's camera, open the link, and enter the password when it asks. Then allow the certificate in the device's settings.{/if}
|
||||||
|
</p>
|
||||||
|
</Dialog>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.head { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; flex-wrap: wrap; }
|
||||||
|
.devices { list-style: none; margin: 0; padding: 0; border: 1px solid var(--hairline); border-radius: var(--radius-lg); }
|
||||||
|
.devices li { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; min-height: 56px; padding: 6px 10px 6px 16px; border-top: 1px solid var(--hairline); }
|
||||||
|
.devices li:first-child { border-top: 0; }
|
||||||
|
.dname { font-weight: 600; flex: 1 1 140px; }
|
||||||
|
.confirm { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; flex-basis: 100%; }
|
||||||
|
.form { display: flex; flex-direction: column; gap: 16px; }
|
||||||
|
.buttons { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.install { display: flex; gap: 20px; flex-wrap: wrap; align-items: flex-start; }
|
||||||
|
.otp { font-weight: 700; font-size: 1.4rem; letter-spacing: 0.08em; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §8.1: History → pick → Restore this version (3 clicks with the nav click).
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { Banner, Button, Status } from "@ianitor/ui";
|
||||||
|
import type { StatusKind } from "@ianitor/ui";
|
||||||
|
import HostPanel from "../components/HostPanel.svelte";
|
||||||
|
import { get, post, sentence } from "../lib/api";
|
||||||
|
import { app, changesBlocked, navigate } from "../lib/app.svelte";
|
||||||
|
import { FIELD_LABEL, fieldValue, when } from "../lib/format";
|
||||||
|
import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types";
|
||||||
|
|
||||||
|
let { host, pick }: { host?: string; pick?: string } = $props();
|
||||||
|
|
||||||
|
let entries = $state<HistoryEntry[]>([]);
|
||||||
|
let next = $state<string | null>(null);
|
||||||
|
let loaded = $state(false);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
let chosen = $state<string | null>(null);
|
||||||
|
let preview = $state<RestorePreview | null>(null);
|
||||||
|
let attempt = $state<ApplyView | null>(null);
|
||||||
|
let restoring = $state(false);
|
||||||
|
let resume = $state<string | null>(null);
|
||||||
|
let editFrom = $state<HostSpec | null>(null);
|
||||||
|
|
||||||
|
async function load(before?: string) {
|
||||||
|
try {
|
||||||
|
const q = new URLSearchParams({ limit: "50" });
|
||||||
|
if (host) q.set("host", host);
|
||||||
|
if (before) q.set("before", before);
|
||||||
|
const r = await get<{ entries: HistoryEntry[]; next_before: string | null }>(`/history?${q}`);
|
||||||
|
entries = before ? [...entries, ...r.entries] : r.entries;
|
||||||
|
next = r.next_before;
|
||||||
|
problem = null;
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
} finally {
|
||||||
|
loaded = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function choose(id: string) {
|
||||||
|
chosen = id;
|
||||||
|
preview = null;
|
||||||
|
attempt = null;
|
||||||
|
try {
|
||||||
|
preview = await get<RestorePreview>(`/history/${encodeURIComponent(id)}/restore-preview`);
|
||||||
|
if (preview.blocked?.code === "restore.not_kept") attempt = await get<ApplyView>(`/history/${encodeURIComponent(id)}`);
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function restore() {
|
||||||
|
if (!chosen) return;
|
||||||
|
restoring = true;
|
||||||
|
try {
|
||||||
|
const a = await post<{ apply: ApplyView }>("/restore", { change_id: chosen, base_rev: app.overview?.rev ?? null });
|
||||||
|
resume = a.apply.id;
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
} finally {
|
||||||
|
restoring = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void load().then(() => {
|
||||||
|
if (pick) void choose(pick);
|
||||||
|
});
|
||||||
|
const focus = () => void load();
|
||||||
|
window.addEventListener("focus", focus);
|
||||||
|
return () => window.removeEventListener("focus", focus);
|
||||||
|
});
|
||||||
|
|
||||||
|
function stateOf(e: HistoryEntry): [StatusKind, string] {
|
||||||
|
switch (e.state) {
|
||||||
|
case "kept": return ["kept", "kept"];
|
||||||
|
case "reverted": return ["reverted", "reverted"];
|
||||||
|
case "failed": return ["reverted", "not applied"];
|
||||||
|
case "queued": return ["running", "waiting"];
|
||||||
|
default: return ["running", "applying"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const entry = $derived(entries.find((e) => e.change_id === chosen));
|
||||||
|
const n = $derived(preview?.changes.length ?? 0);
|
||||||
|
const paused = $derived(app.overview?.paused ? !["apply.needs_attention", "control.files_unwritten"].includes(app.overview.paused_reason ?? "") : false);
|
||||||
|
const blocked = $derived(paused ? "Changes are paused." : changesBlocked() && !app.overview?.paused ? changesBlocked() : null);
|
||||||
|
|
||||||
|
function key(e: KeyboardEvent, i: number) {
|
||||||
|
const btns = Array.from(document.querySelectorAll<HTMLButtonElement>(".entries button"));
|
||||||
|
if (e.key === "ArrowDown") { e.preventDefault(); btns[Math.min(btns.length - 1, i + 1)]?.focus(); }
|
||||||
|
if (e.key === "ArrowUp") { e.preventDefault(); btns[Math.max(0, i - 1)]?.focus(); }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<h1 class="ia-display">{host ? `History of ${host}` : "History"}</h1>
|
||||||
|
{#if host}<div><button type="button" class="domi-btn link" onclick={() => navigate("/history")}>Show all changes</button></div>{/if}
|
||||||
|
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||||
|
|
||||||
|
<div class="cols">
|
||||||
|
<div class="list">
|
||||||
|
{#if loaded && entries.length === 0}
|
||||||
|
<div class="ia-frame"><h2 class="ia-h3">No changes yet</h2><p class="ia-text2">Every change you apply is listed here, newest first.</p></div>
|
||||||
|
{/if}
|
||||||
|
<ul class="entries">
|
||||||
|
{#each entries as e, i (e.change_id)}
|
||||||
|
{@const [k, w] = stateOf(e)}
|
||||||
|
<li>
|
||||||
|
<button type="button" class="entry" aria-current={chosen === e.change_id ? "true" : undefined} onclick={() => choose(e.change_id)} onkeydown={(ev) => key(ev, i)}>
|
||||||
|
<span class="sum">{e.summary}</span><Status kind={k} word={w} />
|
||||||
|
<span class="ia-sub">{when(e.at, app.now)} · {e.state === "kept" ? (e.commit_short ?? "") : (e.reason_short ?? "")}</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
{#if next}<Button onclick={() => load(next ?? undefined)}>Show older changes</Button>{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if chosen && preview}
|
||||||
|
<section class="detail" aria-label="Version">
|
||||||
|
<p class="ia-label">Version of {when(entry?.at, app.now)}</p>
|
||||||
|
{#if preview.blocked?.code === "restore.not_kept"}
|
||||||
|
<h2 class="ia-h3">This change did not stay</h2>
|
||||||
|
{#if attempt?.reason}<p>{attempt.reason.message}</p>{/if}
|
||||||
|
<p class="ia-text2">This change was undone at the time, so there is nothing to go back to.</p>
|
||||||
|
{#if attempt?.attempted_host}<div><Button variant="outline" onclick={() => (editFrom = attempt?.attempted_host ?? null)}>Edit and try again</Button></div>{/if}
|
||||||
|
{:else if preview.blocked?.code === "restore.same"}
|
||||||
|
<h2 class="ia-h3">Go back to this version?</h2>
|
||||||
|
<p class="ia-text2">This version is the same as the current one. Nothing to restore.</p>
|
||||||
|
<div class="buttons"><Button onclick={() => (chosen = null)}>Close</Button></div>
|
||||||
|
{:else}
|
||||||
|
<h2 class="ia-h3">Go back to this version?</h2>
|
||||||
|
<p>{n === 1 ? "Restoring puts 1 host back to how it was then:" : `Restoring puts ${n} hosts back to how they were then:`}</p>
|
||||||
|
<ul>
|
||||||
|
{#each preview.changes as c (c.hostname)}
|
||||||
|
{#if c.effect === "added"}<li><strong>{c.hostname}</strong> is added back</li>
|
||||||
|
{:else if c.effect === "removed"}<li><strong>{c.hostname}</strong> is removed</li>
|
||||||
|
{:else}
|
||||||
|
{#each c.fields as f (f.field)}
|
||||||
|
<li><strong>{c.hostname}</strong>: {#if f.field === "headers"}header rules change{:else}{FIELD_LABEL[f.field] ?? f.field} changes from {fieldValue(f.field, f.from)} to {fieldValue(f.field, f.to)}{/if}</li>
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
<p class="ia-hint">Applied as a new commit with the same {app.overview?.site?.watch_seconds ?? 60}-second watch. If health checks fail, it is undone.</p>
|
||||||
|
{#if blocked}<p class="ia-hint" id="restore-blocked">{blocked}</p>{/if}
|
||||||
|
<div class="buttons">
|
||||||
|
<Button onclick={() => (chosen = null)}>Close</Button>
|
||||||
|
<Button variant="primary" onclick={restore} pending={restoring} disabled={!!blocked} describedby={blocked ? "restore-blocked" : undefined}>Restore this version</Button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if resume}
|
||||||
|
<HostPanel resume={resume} onclose={() => { resume = null; void load(); }} />
|
||||||
|
{/if}
|
||||||
|
{#if editFrom}
|
||||||
|
<HostPanel prefill={editFrom} hostname={undefined} onclose={() => { editFrom = null; void load(); }} />
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.cols { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; }
|
||||||
|
.list { flex: 1 1 360px; max-width: 520px; display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.entries { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.entry { display: grid; grid-template-columns: 1fr auto; gap: 2px 12px; width: 100%; min-height: 44px; padding: 10px 12px; border-radius: var(--radius-sm); border: 1px solid transparent; background: none; color: var(--text); text-align: left; cursor: pointer; }
|
||||||
|
.entry:hover { background: var(--surface); }
|
||||||
|
.entry[aria-current="true"] { background: var(--surface-2); border-color: color-mix(in srgb, var(--accent) 55%, transparent); }
|
||||||
|
.sum { font-weight: 600; }
|
||||||
|
.detail { flex: 2 1 360px; background: var(--colonnade); border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.detail ul { margin: 0; padding-left: 1.1rem; }
|
||||||
|
.buttons { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §5: the main screen.
|
||||||
|
import { tick } from "svelte";
|
||||||
|
import { Banner, Button } from "@ianitor/ui";
|
||||||
|
import ChangeBar from "../components/ChangeBar.svelte";
|
||||||
|
import EngineChip from "../components/EngineChip.svelte";
|
||||||
|
import HostList from "../components/HostList.svelte";
|
||||||
|
import HostPanel from "../components/HostPanel.svelte";
|
||||||
|
import IntermediateBanner from "../components/IntermediateBanner.svelte";
|
||||||
|
import ShareDialog from "../components/ShareDialog.svelte";
|
||||||
|
import { call, newKey, post, sentence } from "../lib/api";
|
||||||
|
import { app, changesBlocked, navigate, refresh, toast } from "../lib/app.svelte";
|
||||||
|
import { atTime, countsSentence } from "../lib/format";
|
||||||
|
import type { ApplyView, HostSpec } from "../lib/types";
|
||||||
|
|
||||||
|
let { route }: { route: { newHost: boolean; edit?: string } } = $props();
|
||||||
|
|
||||||
|
const o = $derived(app.overview);
|
||||||
|
let prefill = $state<HostSpec | null>(null);
|
||||||
|
let focusField = $state<string | undefined>(undefined);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
|
||||||
|
const panelOpen = $derived(route.newHost || !!route.edit || app.panel?.kind === "host");
|
||||||
|
const blocked = $derived(changesBlocked());
|
||||||
|
|
||||||
|
async function closePanel() {
|
||||||
|
prefill = null;
|
||||||
|
focusField = undefined;
|
||||||
|
if (app.panel?.kind === "host") app.panel = null;
|
||||||
|
if (route.newHost || route.edit) navigate("/");
|
||||||
|
await refresh();
|
||||||
|
const h = app.focusHost;
|
||||||
|
app.focusHost = null;
|
||||||
|
if (h) {
|
||||||
|
await tick();
|
||||||
|
document.querySelector<HTMLElement>(`[aria-label="More for ${h.replace(/["\\]/g, "")}"]`)?.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(h: string) {
|
||||||
|
problem = null;
|
||||||
|
try {
|
||||||
|
await call("DELETE", `/hosts/${encodeURIComponent(h)}?base_rev=${encodeURIComponent(o?.rev ?? "")}`, undefined, { idem: newKey() });
|
||||||
|
await refresh();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function retry(h: string) {
|
||||||
|
try {
|
||||||
|
await post(`/hosts/${encodeURIComponent(h)}/certificate/retry`);
|
||||||
|
toast("Trying Let's Encrypt again.");
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function editAgain(a: ApplyView, field?: string) {
|
||||||
|
prefill = a.attempted_host ?? null;
|
||||||
|
focusField = field;
|
||||||
|
if (a.kind === "add" || !a.hosts[0]) {
|
||||||
|
navigate("/hosts/new");
|
||||||
|
} else {
|
||||||
|
navigate(`/hosts/${encodeURIComponent(a.hosts[0])}/edit`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="head">
|
||||||
|
<div>
|
||||||
|
<h1 class="ia-display">Hosts</h1>
|
||||||
|
{#if o}<p class={app.phone ? "ia-sub" : "ia-text2"}>{countsSentence(o.counts, app.phone)}</p>{/if}
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
{#if !app.phone}<EngineChip />{/if}
|
||||||
|
<Button variant="primary" icon="plus" label="Add a host" disabled={!!blocked} describedby={blocked ? "add-blocked" : undefined} onclick={() => navigate("/hosts/new")}>Host</Button>
|
||||||
|
{#if blocked}<span class="sr-only" id="add-blocked">{blocked}</span>{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<IntermediateBanner />
|
||||||
|
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||||
|
|
||||||
|
<ChangeBar onshowsteps={(id) => (app.panel = { kind: "host", resume: id })} onedit={editAgain} />
|
||||||
|
|
||||||
|
{#if !o && !app.loadError}
|
||||||
|
<div class="ia-list" aria-busy="true"><span class="sr-only">Loading hosts…</span>
|
||||||
|
{#each [0, 1, 2] as i (i)}<div class="ia-row"><span class="ia-placeholder"></span><span class="ia-placeholder"></span><span class="ia-placeholder"></span><span></span></div>{/each}
|
||||||
|
</div>
|
||||||
|
{:else if app.loadError && !o}
|
||||||
|
<Banner tone="down" live="alert">{#snippet title()}This page could not load. Ianitor's control service may be restarting.{/snippet}
|
||||||
|
{#snippet actions()}<Button onclick={() => refresh()}>Try again now</Button>{/snippet}</Banner>
|
||||||
|
{:else if o && o.hosts.length === 0}
|
||||||
|
<div class="ia-frame"><h2 class="ia-h3">No hosts yet</h2><p class="ia-text2">Add the first one: the name people type, and where Ianitor should send them.</p></div>
|
||||||
|
{:else if o}
|
||||||
|
<HostList hosts={o.hosts}
|
||||||
|
onedit={(h) => navigate(`/hosts/${encodeURIComponent(h)}/edit`)}
|
||||||
|
onremove={remove}
|
||||||
|
onshare={(h) => (app.panel = { kind: "share", hostname: h })}
|
||||||
|
onhistory={(h) => navigate(`/history?host=${encodeURIComponent(h)}`)}
|
||||||
|
onretry={retry} />
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if o?.repo}
|
||||||
|
<hr class="ia-ornament" />
|
||||||
|
<p class="ia-muted footer">
|
||||||
|
Routes live in the {o.repo.name} repository, one file per host.
|
||||||
|
{#if o.repo.last_push_at}Last pushed to Gitea {atTime(o.repo.last_push_at, app.now)}.{/if}
|
||||||
|
{#if o.repo.unpushed}{o.repo.unpushed} changes not yet pushed.{/if}
|
||||||
|
<button type="button" class="domi-btn link" onclick={() => navigate("/history")}>See history</button>
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if panelOpen}
|
||||||
|
{#key route.edit ?? (app.panel?.kind === "host" ? app.panel.resume : "new")}
|
||||||
|
<HostPanel hostname={route.edit} resume={app.panel?.kind === "host" ? app.panel.resume : undefined} {prefill} {focusField} onclose={closePanel} />
|
||||||
|
{/key}
|
||||||
|
{/if}
|
||||||
|
{#if app.panel?.kind === "share"}
|
||||||
|
<ShareDialog hostname={app.panel.hostname} onclose={() => { app.panel = null; void refresh(); }} />
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 16px; }
|
||||||
|
.actions { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
|
||||||
|
.footer { text-align: center; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// T4: branch previews Fabrica opens. See them: 1 click (the nav). Close one: 2 clicks
|
||||||
|
// (Close → Close preview).
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { Banner, Button, Status } from "@ianitor/ui";
|
||||||
|
import type { StatusKind } from "@ianitor/ui";
|
||||||
|
import { del, get, sentence } from "../lib/api";
|
||||||
|
import { app, toast } from "../lib/app.svelte";
|
||||||
|
import { whenInline } from "../lib/format";
|
||||||
|
import type { PreviewList, PreviewView } from "../lib/types";
|
||||||
|
|
||||||
|
let list = $state<PreviewList | null>(null);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
let confirm = $state<string | null>(null);
|
||||||
|
let closing = $state<string | null>(null);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
list = await get<PreviewList>("/previews");
|
||||||
|
problem = null;
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function close(p: PreviewView) {
|
||||||
|
closing = p.hostname;
|
||||||
|
try {
|
||||||
|
await del(`/previews/${encodeURIComponent(p.hostname)}`);
|
||||||
|
toast(`Closing the preview of ${p.branch}.`);
|
||||||
|
confirm = null;
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
} finally {
|
||||||
|
closing = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void load();
|
||||||
|
const t = setInterval(() => void load(), 5000);
|
||||||
|
const f = () => void load();
|
||||||
|
window.addEventListener("focus", f);
|
||||||
|
return () => {
|
||||||
|
clearInterval(t);
|
||||||
|
window.removeEventListener("focus", f);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
function badge(p: PreviewView): [StatusKind, string] {
|
||||||
|
if (p.state === "live") return ["healthy", "live"];
|
||||||
|
if (p.state === "failed") return ["down", "failed"];
|
||||||
|
return ["running", "opening"];
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<h1 class="ia-display">Previews</h1>
|
||||||
|
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||||
|
|
||||||
|
{#if list && !list.domain}
|
||||||
|
<div class="ia-frame">
|
||||||
|
<h2 class="ia-h3">Previews are off</h2>
|
||||||
|
<p class="ia-text2">Set a preview domain in control.toml (<code>[previews] domain</code>) and point a wildcard DNS record at this server. Then every branch Fabrica builds gets its own address here.</p>
|
||||||
|
</div>
|
||||||
|
{:else if list && list.items.length === 0}
|
||||||
|
<div class="ia-frame">
|
||||||
|
<h2 class="ia-h3">No previews open</h2>
|
||||||
|
<p class="ia-text2">When Fabrica builds a branch, its preview appears here as <code><branch>--<project>.{list.domain}</code>. It closes on merge or when its time runs out.</p>
|
||||||
|
</div>
|
||||||
|
{:else if list}
|
||||||
|
<p class="ia-hint">Under {list.domain}. Fabrica opens them with a token that can only manage previews.</p>
|
||||||
|
<ul class="rows">
|
||||||
|
{#each list.items as p (p.hostname)}
|
||||||
|
{@const [kind, label] = badge(p)}
|
||||||
|
<li>
|
||||||
|
<Status {kind} word={label} />
|
||||||
|
<div class="grow">
|
||||||
|
<a class="host" href={p.url} target="_blank" rel="noreferrer">{p.hostname}</a>
|
||||||
|
<span class="ia-sub" style="display:block">{p.branch} · {p.project} · to {p.upstream} · closes {whenInline(p.expires_at, app.now)}</span>
|
||||||
|
{#if p.problem}<span class="domi-error">{p.problem}</span>{/if}
|
||||||
|
</div>
|
||||||
|
{#if confirm === p.hostname}
|
||||||
|
<span>Close the preview of {p.branch}? Its address stops working.</span>
|
||||||
|
<Button small onclick={() => (confirm = null)}>Keep it</Button>
|
||||||
|
<Button small variant="danger" pending={closing === p.hostname} onclick={() => close(p)} data-autofocus>Close preview</Button>
|
||||||
|
{:else}
|
||||||
|
<Button small variant="danger" onclick={() => (confirm = p.hostname)}>Close</Button>
|
||||||
|
{/if}
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.rows { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.rows li { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; min-height: 52px; padding: 10px 0; border-top: 1px solid var(--hairline); }
|
||||||
|
.grow { flex: 1 1 260px; min-width: 0; }
|
||||||
|
.host { font-weight: 600; color: var(--text); overflow-wrap: anywhere; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §13.6: signing the intermediate by hand on the offline computer (the temporary step
|
||||||
|
// until Custos can sign, docs/pki.md). The root key never comes to this server.
|
||||||
|
import { Banner, Button, Icon } from "@ianitor/ui";
|
||||||
|
import { ApiError, post, put, sentence } from "../lib/api";
|
||||||
|
import { app, navigate, refresh } from "../lib/app.svelte";
|
||||||
|
import type { PkiRequest } from "../lib/types";
|
||||||
|
|
||||||
|
const r = $derived(app.overview?.intermediate?.renewal ?? null);
|
||||||
|
let pem = $state("");
|
||||||
|
let paste = $state(false);
|
||||||
|
let err = $state<string | null>(null);
|
||||||
|
let pending = $state(false);
|
||||||
|
let starting = $state(false);
|
||||||
|
const base = $derived(r?.file_base ?? `domi-intermediate-${new Date().toISOString().slice(0, 10)}`);
|
||||||
|
const signCmd = $derived(r?.approve_command ?? `openssl x509 -req -in ${base}.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile ${base}.ext -out ${base}.crt`);
|
||||||
|
const checkCmd = $derived(`openssl req -in ${base}.csr -outform DER | openssl dgst -sha256`);
|
||||||
|
let copied = $state(false);
|
||||||
|
// Groups of 8, easier to compare by eye; openssl prints it without spaces.
|
||||||
|
const group = (h: string) => h.match(/.{1,8}/g)?.join(" ") ?? h;
|
||||||
|
async function copy(text: string) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
copied = true;
|
||||||
|
setTimeout(() => (copied = false), 3000);
|
||||||
|
} catch {
|
||||||
|
err = "Your browser did not allow copying. Select the command and copy it.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function save(text: string, name: string, type: string) {
|
||||||
|
const url = URL.createObjectURL(new Blob([text], { type }));
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = name;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function download() {
|
||||||
|
if (r?.csr_pem) save(r.csr_pem, `${base}.csr`, "application/pkcs10");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadExt() {
|
||||||
|
if (!r) return;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/v1/pki-requests/${encodeURIComponent(r.request_id)}/ext`, { headers: { "X-Ianitor-UI": "1" }, redirect: "manual", credentials: "same-origin" });
|
||||||
|
if (res.ok) save(await res.text(), `${base}.ext`, "text/plain");
|
||||||
|
else err = "The signing settings file could not be downloaded. Reload the page and try again.";
|
||||||
|
} catch {
|
||||||
|
err = "Ianitor's control service is not answering.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function file(e: Event) {
|
||||||
|
const f = (e.currentTarget as HTMLInputElement).files?.[0];
|
||||||
|
if (f) pem = await f.text();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function use() {
|
||||||
|
if (!r) return;
|
||||||
|
pending = true;
|
||||||
|
err = null;
|
||||||
|
try {
|
||||||
|
const done = await put<PkiRequest>(`/pki-requests/${encodeURIComponent(r.request_id)}/certificate`, { certificate_pem: pem });
|
||||||
|
app.renewedUntil = done.not_after;
|
||||||
|
await refresh();
|
||||||
|
navigate("/certificates");
|
||||||
|
} catch (e) {
|
||||||
|
err = e instanceof ApiError ? e.body.message : sentence(e);
|
||||||
|
} finally {
|
||||||
|
pending = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function start() {
|
||||||
|
starting = true;
|
||||||
|
try {
|
||||||
|
await post("/certs/intermediate/renewal");
|
||||||
|
await refresh();
|
||||||
|
} catch (e) {
|
||||||
|
err = sentence(e);
|
||||||
|
} finally {
|
||||||
|
starting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<h1 class="ia-display">Sign the intermediate by hand</h1>
|
||||||
|
<p class="ia-text2">Custos cannot sign certificates yet, so the Domi root signs on the offline computer. The root key never comes to this server.</p>
|
||||||
|
|
||||||
|
{#if !r}
|
||||||
|
<Banner tone="notice">{#snippet title()}There is no open renewal request.{/snippet}
|
||||||
|
{#snippet actions()}<Button variant="outline" onclick={start} pending={starting}>Start a renewal</Button>{/snippet}</Banner>
|
||||||
|
{:else}
|
||||||
|
<section class="step">
|
||||||
|
<p class="ia-label">Step 1</p>
|
||||||
|
<h2 class="ia-h3">Download the request</h2>
|
||||||
|
<p class="ia-text2">This file asks the Domi root to sign a new intermediate certificate. It holds no secret.</p>
|
||||||
|
<div class="row"><Button icon="download" onclick={download}>Download the request (.csr)</Button><Button icon="download" onclick={downloadExt}>Download the signing settings (.ext)</Button></div>
|
||||||
|
</section>
|
||||||
|
<section class="step">
|
||||||
|
<p class="ia-label">Step 2</p>
|
||||||
|
<h2 class="ia-h3">Sign it on the offline computer</h2>
|
||||||
|
<p class="ia-text2">Copy both files to the offline computer that holds the Domi root.</p>
|
||||||
|
<p class="ia-text2">First check that the request is the one this server made. This prints its fingerprint:</p>
|
||||||
|
<pre class="ia-secret ia-cmd">{checkCmd}</pre>
|
||||||
|
{#if r.csr_sha256}<p>openssl must print the same fingerprint as this page: <span class="ia-cmd fp" aria-label="Fingerprint {r.csr_sha256}">{group(r.csr_sha256)}</span></p>{/if}
|
||||||
|
<p class="ia-text2">Then sign it:</p>
|
||||||
|
<pre class="ia-secret ia-cmd">{signCmd}</pre>
|
||||||
|
<div class="row"><Button icon="copy" onclick={() => copy(signCmd)}>Copy command</Button>{#if copied}<span class="ia-status" data-s="kept" role="status"><Icon name="check" />Copied</span>{/if}</div>
|
||||||
|
<p class="ia-muted">On a computer with Ianitor installed, <code>ianitor-control ca sign</code> signs it instead and shows the match code {r.match_code}.</p>
|
||||||
|
</section>
|
||||||
|
<section class="step">
|
||||||
|
<p class="ia-label">Step 3</p>
|
||||||
|
<h2 class="ia-h3">Upload the signed certificate</h2>
|
||||||
|
{#if paste}
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for="cert-paste">Signed certificate</label>
|
||||||
|
<textarea id="cert-paste" class="domi-input" rows="8" bind:value={pem} aria-invalid={err ? "true" : undefined}></textarea>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for="cert-file">Signed certificate (.crt)</label>
|
||||||
|
<input id="cert-file" class="domi-input" type="file" accept=".crt,.pem" onchange={file} aria-invalid={err ? "true" : undefined} />
|
||||||
|
<div><button type="button" class="domi-btn link" onclick={() => (paste = true)}>Paste it instead</button></div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if err}<p class="domi-error" role="alert"><Icon name="ring" />{err}</p>{/if}
|
||||||
|
<div><Button variant="primary" onclick={use} {pending} disabled={!pem.includes("BEGIN CERTIFICATE")}>Use this certificate</Button></div>
|
||||||
|
</section>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.row { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.step { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.fp { word-break: break-all; color: var(--accent-strong); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §8.3: Settings with General, API (⚙ → API → New token = 3 clicks, Copy token the
|
||||||
|
// accepted 4th), Share links and About.
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { Banner, Button, Dialog, Segmented } from "@ianitor/ui";
|
||||||
|
import TeamTab from "../components/TeamTab.svelte";
|
||||||
|
import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api";
|
||||||
|
import { app, navigate, toast } from "../lib/app.svelte";
|
||||||
|
import { longDate, shortDate, whenInline } from "../lib/format";
|
||||||
|
import type { CreatedToken, ShareLink, TokenRow } from "../lib/types";
|
||||||
|
|
||||||
|
let { tab }: { tab: string } = $props();
|
||||||
|
const TABS = [
|
||||||
|
{ id: "general", label: "General" },
|
||||||
|
{ id: "team", label: "Team" },
|
||||||
|
{ id: "api", label: "API" },
|
||||||
|
{ id: "share-links", label: "Share links" },
|
||||||
|
{ id: "about", label: "About" },
|
||||||
|
];
|
||||||
|
|
||||||
|
let settings = $state<{ repo: { name: string; last_push_at: string | null } | null; watch_seconds: number } | null>(null);
|
||||||
|
let tokens = $state<TokenRow[]>([]);
|
||||||
|
let revoked = $state<Record<string, string>>({});
|
||||||
|
let links = $state<ShareLink[]>([]);
|
||||||
|
let problem = $state<string | null>(null);
|
||||||
|
let expiry = $state<"year" | "never">("year");
|
||||||
|
let scope = $state<"full" | "previews">("full");
|
||||||
|
let made = $state<CreatedToken | null>(null);
|
||||||
|
let tokenName = $state("");
|
||||||
|
let tokenCopied = $state(false);
|
||||||
|
let askClose = $state(false);
|
||||||
|
let nameErr = $state<string | null>(null);
|
||||||
|
let confirmRevoke = $state<string | null>(null);
|
||||||
|
let confirmStopAll = $state(false);
|
||||||
|
let creating = $state(false);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
if (tab === "general") settings = await get("/settings");
|
||||||
|
if (tab === "api") tokens = (await get<{ items: TokenRow[] }>("/tokens")).items;
|
||||||
|
if (tab === "share-links") links = (await get<{ items: ShareLink[] }>("/share-links")).items;
|
||||||
|
problem = null;
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$effect(() => {
|
||||||
|
void tab;
|
||||||
|
void load();
|
||||||
|
});
|
||||||
|
onMount(() => {
|
||||||
|
const f = () => void load();
|
||||||
|
window.addEventListener("focus", f);
|
||||||
|
return () => window.removeEventListener("focus", f);
|
||||||
|
});
|
||||||
|
|
||||||
|
function tabKey(e: KeyboardEvent, i: number) {
|
||||||
|
let j = i;
|
||||||
|
if (e.key === "ArrowRight") j = (i + 1) % TABS.length;
|
||||||
|
else if (e.key === "ArrowLeft") j = (i - 1 + TABS.length) % TABS.length;
|
||||||
|
else if (e.key === "Home") j = 0;
|
||||||
|
else if (e.key === "End") j = TABS.length - 1;
|
||||||
|
else return;
|
||||||
|
e.preventDefault();
|
||||||
|
navigate(`/settings/${TABS[j].id}`);
|
||||||
|
setTimeout(() => document.getElementById(`tab-${TABS[j].id}`)?.focus(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function newToken() {
|
||||||
|
creating = true;
|
||||||
|
try {
|
||||||
|
const name = scope === "previews" ? `Fabrica previews ${shortDate(new Date().toISOString())}` : `Token made ${shortDate(new Date().toISOString())}`;
|
||||||
|
const body = expiry === "never" ? { name, never_expires: true, scope } : { name, expires_in_days: 365, scope };
|
||||||
|
made = await post<CreatedToken>("/tokens", body);
|
||||||
|
tokenName = made.name;
|
||||||
|
tokenCopied = false;
|
||||||
|
askClose = false;
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
} finally {
|
||||||
|
creating = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyToken() {
|
||||||
|
if (!made) return;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(made.token);
|
||||||
|
tokenCopied = true;
|
||||||
|
} catch {
|
||||||
|
problem = "Your browser did not allow copying. Select the token and press Ctrl+C.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function closeToken(force = false) {
|
||||||
|
if (!made) return;
|
||||||
|
if (!tokenCopied && !force) {
|
||||||
|
askClose = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (tokenName.trim() && tokenName !== made.name) {
|
||||||
|
try {
|
||||||
|
await patch(`/tokens/${encodeURIComponent(made.id)}`, { name: tokenName.trim() });
|
||||||
|
toast("Renamed.");
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError && e.code === "token.name") {
|
||||||
|
nameErr = e.body.message;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The token leaves memory with the dialog.
|
||||||
|
made = null;
|
||||||
|
tokenName = "";
|
||||||
|
void load();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revoke(t: TokenRow) {
|
||||||
|
try {
|
||||||
|
await del(`/tokens/${encodeURIComponent(t.id)}`);
|
||||||
|
revoked = { ...revoked, [t.id]: new Date().toISOString() };
|
||||||
|
confirmRevoke = null;
|
||||||
|
toast(`Revoked. Anything using "${t.name}" stops working now.`);
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stop(l: ShareLink) {
|
||||||
|
try {
|
||||||
|
await del(`/share-links/${encodeURIComponent(l.id)}`);
|
||||||
|
toast("Stopped. The link stops working within a few seconds.");
|
||||||
|
void load();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stopAll() {
|
||||||
|
try {
|
||||||
|
await call("POST", "/share-links/stop-all", {}, { idem: newKey() });
|
||||||
|
toast("All share links are stopped. New ones work as usual.");
|
||||||
|
confirmStopAll = false;
|
||||||
|
void load();
|
||||||
|
} catch (e) {
|
||||||
|
problem = sentence(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const active = $derived(links.filter((l) => l.state === "active"));
|
||||||
|
const ended = $derived(links.filter((l) => l.state !== "active"));
|
||||||
|
const viewer = $derived(app.overview?.viewer ?? null);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<h1 class="ia-display">Settings</h1>
|
||||||
|
<div class="tabs" role="tablist" aria-label="Settings">
|
||||||
|
{#each TABS as t, i (t.id)}
|
||||||
|
<button type="button" role="tab" id="tab-{t.id}" aria-selected={tab === t.id} aria-controls="panel-{t.id}" tabindex={tab === t.id ? 0 : -1}
|
||||||
|
onclick={() => navigate(`/settings/${t.id}`)} onkeydown={(e) => tabKey(e, i)}>{t.label}</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||||
|
|
||||||
|
<div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel">
|
||||||
|
{#if tab === "general"}
|
||||||
|
<p class="ia-label">Routes repository</p>
|
||||||
|
<p>{settings?.repo ? `${settings.repo.name} · ${settings.repo.last_push_at ? "pushed " + whenInline(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</p>
|
||||||
|
<p class="ia-label">Health watch after apply</p>
|
||||||
|
<p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p>
|
||||||
|
<p class="ia-label">Signed in</p>
|
||||||
|
<p>{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : viewer.via === "session" ? viewer.name : `API token "${viewer.name}"`) : "Not signed in"}</p>
|
||||||
|
{#if app.overview?.site?.auth_logout_url}<p><a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a></p>{/if}
|
||||||
|
{:else if tab === "team"}
|
||||||
|
<TeamTab />
|
||||||
|
{:else if tab === "api"}
|
||||||
|
<div class="row">
|
||||||
|
<h2 class="ia-h3">API tokens</h2>
|
||||||
|
<Button variant="outline" icon="plus" onclick={newToken} pending={creating}>New token</Button>
|
||||||
|
<Segmented legend="New tokens expire after" name="token-expiry" bind:value={expiry} options={[{ value: "year", label: "1 year" }, { value: "never", label: "Never" }]} />
|
||||||
|
<Segmented legend="New tokens may" name="token-scope" bind:value={scope} options={[{ value: "full", label: "Do everything" }, { value: "previews", label: "Previews only" }]} />
|
||||||
|
</div>
|
||||||
|
<p class="ia-hint">Fabrica needs a previews-only token: it can open and close branch previews and touch nothing else. Keep it in the Custos team vault.</p>
|
||||||
|
<p class="ia-hint">The API listens on 127.0.0.1 only. Ianitor keeps a hash of each token, never the token.</p>
|
||||||
|
{#if tokens.length === 0}
|
||||||
|
<div class="ia-frame"><h2 class="ia-h3">No API tokens</h2><p class="ia-text2">Scripts and other Domi apps use a token to talk to Ianitor.</p></div>
|
||||||
|
{:else}
|
||||||
|
<ul class="rows">
|
||||||
|
{#each tokens as t (t.id)}
|
||||||
|
<li>
|
||||||
|
<div class="grow">
|
||||||
|
<span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span>{#if t.scope === "previews"} <span class="ia-sub">previews only</span>{/if}
|
||||||
|
<span class="ia-sub" style="display:block">
|
||||||
|
{#if revoked[t.id]}Revoked {whenInline(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${whenInline(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{#if !revoked[t.id] && !t.revoked_at}
|
||||||
|
{#if confirmRevoke === t.id}
|
||||||
|
<span>Revoke "{t.name}"? Anything using it stops working now.</span>
|
||||||
|
<Button small onclick={() => (confirmRevoke = null)} data-autofocus>Cancel</Button>
|
||||||
|
<Button small variant="danger" onclick={() => revoke(t)}>Revoke</Button>
|
||||||
|
{:else}
|
||||||
|
<Button small variant="danger" onclick={() => (confirmRevoke = t.id)}>Revoke</Button>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
{/if}
|
||||||
|
{:else if tab === "share-links"}
|
||||||
|
<div class="row">
|
||||||
|
<h2 class="ia-h3">Share links</h2>
|
||||||
|
{#if active.length}<Button variant="danger" onclick={() => (confirmStopAll = true)}>Stop all share links</Button>{/if}
|
||||||
|
</div>
|
||||||
|
{#if app.overview?.engine.running === "caddy"}
|
||||||
|
<Banner tone="notice">{#snippet title()}Caddy is serving, so these links do not work right now. They work again after switching back to Pingora.{/snippet}</Banner>
|
||||||
|
{/if}
|
||||||
|
{#if confirmStopAll}
|
||||||
|
<p>Stop all {active.length} active links? Every link made so far stops working. New ones work as usual.
|
||||||
|
<Button small onclick={() => (confirmStopAll = false)}>Cancel</Button> <Button small variant="danger" onclick={stopAll}>Stop all</Button></p>
|
||||||
|
{/if}
|
||||||
|
{#if links.length === 0}
|
||||||
|
<div class="ia-frame"><h2 class="ia-h3">No share links</h2><p class="ia-text2">Make one from a host's menu (⋯), Share link.</p></div>
|
||||||
|
{:else}
|
||||||
|
<ul class="rows">
|
||||||
|
{#each active as l (l.id)}
|
||||||
|
<li>
|
||||||
|
<div class="grow"><strong>{l.hostname}</strong>{l.path_prefix !== "/" ? l.path_prefix : ""}
|
||||||
|
<span class="ia-sub" style="display:block">Made {whenInline(l.created_at, app.now)} · expires {whenInline(l.expires_at, app.now)}{l.has_password ? " · password" : ""}</span></div>
|
||||||
|
<Button small onclick={() => stop(l)}>Stop this link</Button>
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
{#if ended.length}
|
||||||
|
<details><summary>Ended ({ended.length})</summary>
|
||||||
|
<ul class="rows">{#each ended as l (l.id)}<li><span class="grow">{l.hostname}{l.path_prefix !== "/" ? l.path_prefix : ""}</span><span class="ia-sub">{l.state} {shortDate(l.expires_at)}</span></li>{/each}</ul>
|
||||||
|
</details>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<p>Ianitor Domi 0.2.0</p>
|
||||||
|
<p>MPL-2.0</p>
|
||||||
|
<p>Built, tested and signed by Fabrica Domi</p>
|
||||||
|
<p><a class="domi-btn link" href="https://gitea.marek-novak.cz/mnovak/Ianitor" rel="noreferrer">Source on Gitea</a></p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if made}
|
||||||
|
<Dialog title="Your new token" escape={false} onclose={() => closeToken()}>
|
||||||
|
<p><strong>Copy it now and save it in Custos.</strong></p>
|
||||||
|
<p class="ia-text2">Ianitor cannot show it again; if it is lost, make a new one and revoke this one.</p>
|
||||||
|
<input class="ia-secret" readonly value={made.token} aria-label="New API token" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} />
|
||||||
|
<div class="grid">
|
||||||
|
<div class="domi-field">
|
||||||
|
<label class="domi-field-label" for="token-name">Name</label>
|
||||||
|
<input id="token-name" class="domi-input" bind:value={tokenName} aria-invalid={nameErr ? "true" : undefined} />
|
||||||
|
{#if nameErr}<p class="domi-error">{nameErr}</p>{/if}
|
||||||
|
<p class="ia-hint">Rename it now or later, so you know what uses it.</p>
|
||||||
|
</div>
|
||||||
|
<Button variant={tokenCopied ? "quiet" : "primary"} icon="copy" onclick={copyToken} data-autofocus>{tokenCopied ? "Copy again" : "Copy token"}</Button>
|
||||||
|
</div>
|
||||||
|
{#if tokenCopied}<p role="status">Copied. Paste it into Custos now. Ianitor cannot show it again.</p>{/if}
|
||||||
|
<p class="ia-muted">{made.expires_at ? `Expires on ${longDate(made.expires_at, false)}.` : "Never expires."}</p>
|
||||||
|
{#if askClose}
|
||||||
|
<p role="alert">Close without copying? The token cannot be shown again.
|
||||||
|
<Button small onclick={() => (askClose = false)}>Go back</Button> <Button small variant="danger" onclick={() => closeToken(true)}>Close anyway</Button></p>
|
||||||
|
{/if}
|
||||||
|
{#snippet footer()}<Button onclick={() => closeToken()}>I have saved it</Button>{/snippet}
|
||||||
|
</Dialog>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.tabs { display: flex; gap: 4px; overflow-x: auto; }
|
||||||
|
.tabs [role="tab"] { min-height: 44px; padding: 0 1rem; border-radius: var(--radius-sm); border: 0; background: none; color: var(--text-2); font-weight: 600; cursor: pointer; }
|
||||||
|
.tabs [role="tab"][aria-selected="true"] { background: var(--surface-2); color: var(--text); }
|
||||||
|
.panel { display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.row { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; }
|
||||||
|
.rows { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.rows li { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; min-height: 44px; padding: 8px 0; border-top: 1px solid var(--hairline); }
|
||||||
|
.grow { flex: 1 1 200px; min-width: 0; }
|
||||||
|
.tname { font-weight: 600; }
|
||||||
|
.struck { text-decoration: line-through; color: var(--muted); }
|
||||||
|
.grid { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: end; }
|
||||||
|
@media (max-width: 719.98px) { .grid { grid-template-columns: 1fr; } }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||||
|
<script lang="ts">
|
||||||
|
// Handoff §10.2: Authelia sends the sign-in tab back here; it tells the first tab and closes.
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const back = new URL(location.href).searchParams.get("back");
|
||||||
|
try {
|
||||||
|
const ch = new BroadcastChannel("ianitor-auth");
|
||||||
|
ch.postMessage("signed-in");
|
||||||
|
ch.close();
|
||||||
|
} catch {
|
||||||
|
/* the first tab rechecks with "I have signed in" */
|
||||||
|
}
|
||||||
|
if (back && back.startsWith("/") && !back.startsWith("//")) {
|
||||||
|
location.replace(back);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTimeout(() => window.close(), 300);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<main class="signed-in">
|
||||||
|
<p class="ia-wordmark">IANITOR DOMI</p>
|
||||||
|
<h1 class="ia-h3">You are signed in again.</h1>
|
||||||
|
<p class="ia-text2">You can close this tab and go back to Ianitor.</p>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.signed-in { max-width: 420px; margin: 20vh auto; padding: 0 16px; display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
|
||||||
|
|
||||||
|
export default { preprocess: vitePreprocess() };
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// The release's screenshots (docs/release.md): every shot's screen is drawn from the demo control
|
||||||
|
// plane alone (each click and wait selector found, no call unanswered), and nothing the demo
|
||||||
|
// serves or the page shows names a real host, address or person.
|
||||||
|
|
||||||
|
import { cleanup, render, waitFor } from "@testing-library/svelte";
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
import App from "../src/App.svelte";
|
||||||
|
import { app } from "../src/lib/app.svelte";
|
||||||
|
import { SHOTS, demoApi } from "./demo";
|
||||||
|
|
||||||
|
const ALLOWED_TLDS = new Set(["test", "example", "invalid"]);
|
||||||
|
const DOC_NETS = ["192.0.2.", "198.51.100.", "203.0.113."];
|
||||||
|
const FORBIDDEN = ["mark", "marek", "novak", "flowers", "esp32", "hyperv"];
|
||||||
|
|
||||||
|
/** What in a text could be real: addresses outside the documentation ranges, names outside .test. */
|
||||||
|
function realLooking(text: string): string[] {
|
||||||
|
const found: string[] = [];
|
||||||
|
for (const m of text.matchAll(/(?<![\w.])\d{1,3}(?:\.\d{1,3}){3}(?![\w.])/g)) {
|
||||||
|
if (m[0] !== "127.0.0.1" && !DOC_NETS.some((n) => m[0].startsWith(n))) found.push(m[0]);
|
||||||
|
}
|
||||||
|
for (const m of text.matchAll(/(?<![\w.-])(?:[a-z0-9-]+\.)+([a-z][a-z0-9-]*)(?![\w-])/gi)) {
|
||||||
|
if (!ALLOWED_TLDS.has(m[1].toLowerCase())) found.push(m[0]);
|
||||||
|
}
|
||||||
|
for (const w of FORBIDDEN) if (new RegExp(`\\b${w}\\b`, "i").test(text)) found.push(w);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
let served: { status: number; path: string; text: string | null }[] = [];
|
||||||
|
|
||||||
|
function start(path: string) {
|
||||||
|
history.replaceState({}, "", path);
|
||||||
|
app.path = path;
|
||||||
|
app.panel = null;
|
||||||
|
app.overview = null;
|
||||||
|
app.etag = null;
|
||||||
|
app.signedOut = false;
|
||||||
|
app.switchResult = null;
|
||||||
|
app.renewedUntil = null;
|
||||||
|
app.dismissed = [];
|
||||||
|
served = [];
|
||||||
|
const api = demoApi();
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
|
const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url;
|
||||||
|
const path = url.replace(/^.*\/api\/v1/, "");
|
||||||
|
const a = api(init?.method ?? "GET", path, init?.body ? JSON.parse(String(init.body)) : {});
|
||||||
|
served.push({ status: a.status, path, text: a.text });
|
||||||
|
return new Response(a.text, { status: a.status, headers: { "Content-Type": "application/json" } });
|
||||||
|
}) as typeof fetch;
|
||||||
|
render(App);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pageText(): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
||||||
|
for (let n = walk.nextNode(); n; n = walk.nextNode()) if (n.textContent?.trim()) out.push(n.textContent);
|
||||||
|
document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("input, textarea").forEach((i) => out.push(i.value));
|
||||||
|
document.querySelectorAll("[href]").forEach((a) => out.push(a.getAttribute("href") ?? ""));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => cleanup());
|
||||||
|
|
||||||
|
describe("realLooking", () => {
|
||||||
|
it("passes invented names and refuses real-looking ones", () => {
|
||||||
|
expect(realLooking("wiki.home.test http://192.0.2.10:3000 on 127.0.0.1 for ada")).toEqual([]);
|
||||||
|
expect(realLooking("http://10.0.0.2:3000")).toEqual(["10.0.0.2"]);
|
||||||
|
expect(realLooking("gitea.example.cz and Mark's phone")).toEqual(["gitea.example.cz", "mark"]);
|
||||||
|
expect(realLooking("flowers.stage")).toEqual(["flowers.stage", "flowers"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the release's screenshots from the demo control plane", () => {
|
||||||
|
for (const shot of SHOTS) {
|
||||||
|
it(`${shot.name}: drawn from invented data only`, async () => {
|
||||||
|
start(shot.path);
|
||||||
|
for (const sel of shot.click ?? []) {
|
||||||
|
const el = await waitFor(() => {
|
||||||
|
const e = document.querySelector<HTMLElement>(sel);
|
||||||
|
expect(e, `click ${sel}`).not.toBeNull();
|
||||||
|
return e as HTMLElement;
|
||||||
|
}, { timeout: 5000 });
|
||||||
|
el.click();
|
||||||
|
}
|
||||||
|
await waitFor(() => expect(document.querySelector(shot.wait), `wait ${shot.wait}`).not.toBeNull(), { timeout: 5000 });
|
||||||
|
|
||||||
|
expect(served.filter((s) => s.status === 404).map((s) => s.path)).toEqual([]);
|
||||||
|
// Control's codes (apply.kept, pki.renew_due) are dotted words, not names.
|
||||||
|
const json = served.map((s) => (s.text ?? "").replace(/"(?:code|message_code|error_code)":"[^"]*"/g, ""));
|
||||||
|
const seen = [...json, ...pageText()];
|
||||||
|
expect(seen.flatMap(realLooking)).toEqual([]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// The demo control plane for the release's screenshots (docs/release.md): control's answers
|
||||||
|
// (docs/api.md) for a small invented home server, built on the click smoke test's stand-in
|
||||||
|
// (mockApi.ts), whose routes answer every call the demo does not replace. Everything here is
|
||||||
|
// invented: hostnames under .test, addresses in the documentation ranges (RFC 5737), people ada
|
||||||
|
// and felix, made-up commits and fingerprints. demo.test.ts renders every shot from it and fails
|
||||||
|
// on any other name or address.
|
||||||
|
|
||||||
|
import { apply, host, mockRoutes, newMock, respond, type Route } from "./mockApi";
|
||||||
|
|
||||||
|
/** One screenshot: the page, the selectors clicked in order, and the selector that means "drawn". */
|
||||||
|
export interface Shot {
|
||||||
|
name: string;
|
||||||
|
title: string;
|
||||||
|
path: string;
|
||||||
|
click?: string[];
|
||||||
|
wait: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The viewport in CSS pixels; the PNGs are this size. */
|
||||||
|
export const SIZE = { width: 1440, height: 900 } as const;
|
||||||
|
|
||||||
|
export const SHOTS: Shot[] = [
|
||||||
|
{ name: "hosts", title: "Every host, its health and where it sends traffic", path: "/", wait: "[aria-label=Hosts] .ia-row:nth-child(8) .ia-host" },
|
||||||
|
{ name: "host", title: "Editing a host", path: "/hosts/wiki.home.test/edit", wait: "#host-form input[readonly]" },
|
||||||
|
{ name: "engine", title: "Pingora serving, Caddy ready as the fallback", path: "/", click: ["[data-engine-chip]"], wait: "dialog.ia-popover[open] .ia-card" },
|
||||||
|
{ name: "history", title: "History: going back to a kept version", path: "/history/ch_0006", wait: "section.detail ul li:nth-child(2)" },
|
||||||
|
{ name: "certificates", title: "The Domi CA and the device certificates", path: "/certificates", wait: "ul.devices li:nth-child(5)" },
|
||||||
|
];
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>;
|
||||||
|
|
||||||
|
const DAY = 86_400;
|
||||||
|
const at = (s: number) => new Date(Date.now() + s * 1000).toISOString();
|
||||||
|
|
||||||
|
interface Health {
|
||||||
|
state: string;
|
||||||
|
latency?: number | null;
|
||||||
|
upstreams?: Json[];
|
||||||
|
failure?: Json | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function demoHost(hostname: string, upstreams: string[], h: Health, over: Json = {}): Json {
|
||||||
|
const base = host(hostname, false);
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
upstreams,
|
||||||
|
health: {
|
||||||
|
state: h.state,
|
||||||
|
last_check_at: h.state === "unknown" ? null : at(-4),
|
||||||
|
latency_ms: h.latency ?? null,
|
||||||
|
since: at(-6 * DAY),
|
||||||
|
failure: h.failure ?? null,
|
||||||
|
upstreams: h.upstreams ?? [],
|
||||||
|
},
|
||||||
|
...over,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const MUSIC = ["http://192.0.2.20:4533", "http://192.0.2.21:4533"];
|
||||||
|
|
||||||
|
function hosts(): Json[] {
|
||||||
|
return [
|
||||||
|
demoHost("wiki.home.test", ["http://192.0.2.10:3000"], { state: "healthy", latency: 9 }, { share_links: true }),
|
||||||
|
demoHost("photos.home.test", ["http://192.0.2.11:2342"], { state: "healthy", latency: 23 }),
|
||||||
|
demoHost("recipes.home.test", ["http://192.0.2.12:9000"], { state: "healthy", latency: 14 }, { added_at: at(-2 * 3600) }),
|
||||||
|
demoHost("music.home.test", MUSIC, {
|
||||||
|
state: "degraded",
|
||||||
|
latency: 18,
|
||||||
|
failure: { kind: "refused", upstream: MUSIC[1], count: 3, of: 3 },
|
||||||
|
upstreams: [
|
||||||
|
{ url: MUSIC[0], state: "healthy", last_check_at: at(-4), latency_ms: 18, failure_kind: null },
|
||||||
|
{ url: MUSIC[1], state: "down", last_check_at: at(-4), latency_ms: null, failure_kind: "refused" },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
demoHost("cameras.home.test", ["https://192.0.2.30:7443"], { state: "healthy", latency: 31 }, { device_certs: true }),
|
||||||
|
demoHost("status.home.test", ["http://192.0.2.40:3001"], { state: "healthy", latency: 6 }, { tls: "letsencrypt", auth: "none" }),
|
||||||
|
demoHost("printer.home.test", ["http://192.0.2.50:631"], { state: "unknown" }, { websockets: false }),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function lastApply(): Json {
|
||||||
|
return {
|
||||||
|
...apply("ch_0008", "kept", "Added recipes.home.test", ["recipes.home.test"]),
|
||||||
|
created_at: at(-2 * 3600 - 70),
|
||||||
|
finished_at: at(-2 * 3600),
|
||||||
|
reason: { code: "apply.kept", message: "recipes.home.test is live. Health checks passed for 60 s." },
|
||||||
|
commit_short: "c41d7e2",
|
||||||
|
push: { state: "pushed", at: at(-2 * 3600), error_code: null, next_try_at: null },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function intermediate(): Json {
|
||||||
|
return { state: "ok", subject: "Demo Intermediate CA", not_after: at(212 * DAY), days_left: 212, renewal: null, banner: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function overview(): Json {
|
||||||
|
const list = hosts();
|
||||||
|
const count = (s: string) => list.filter((h) => (h.health as Json).state === s).length;
|
||||||
|
return {
|
||||||
|
counts: { hosts: list.length, healthy: count("healthy"), degraded: count("degraded"), down: count("down"), unknown: count("unknown") },
|
||||||
|
hosts: list,
|
||||||
|
engine: {
|
||||||
|
running: "pingora",
|
||||||
|
state: "running",
|
||||||
|
since: at(-6 * DAY),
|
||||||
|
target: null,
|
||||||
|
switchable: true,
|
||||||
|
fallback_ready: {
|
||||||
|
built_at: at(-2 * 3600),
|
||||||
|
current: true,
|
||||||
|
compared: list.length,
|
||||||
|
matched: list.length,
|
||||||
|
differences: ["Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."],
|
||||||
|
},
|
||||||
|
last_error: null,
|
||||||
|
notes: [],
|
||||||
|
},
|
||||||
|
last_apply: lastApply(),
|
||||||
|
undo: {
|
||||||
|
available: true,
|
||||||
|
target: { change_id: "ch_0008", summary: "Added recipes.home.test", kept_at: at(-2 * 3600), commit_short: "c41d7e2" },
|
||||||
|
effect: "Removes recipes.home.test",
|
||||||
|
blocked: null,
|
||||||
|
},
|
||||||
|
active_apply: null,
|
||||||
|
repo: { name: "home-routes", last_push_at: at(-2 * 3600), unpushed: 0, push_error_code: null },
|
||||||
|
intermediate: intermediate(),
|
||||||
|
site: { forward_auth_configured: true, acme_configured: true, secrets: ["photos_api_key"], watch_seconds: 60, share_links_available: true, auth_logout_url: "https://auth.home.test/logout" },
|
||||||
|
paused: null,
|
||||||
|
paused_reason: null,
|
||||||
|
health_error: null,
|
||||||
|
rev: "rev-demo-8",
|
||||||
|
viewer: { name: "ada", via: "authelia" },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function spec(hostname: string): Json | null {
|
||||||
|
const row = hosts().find((h) => h.hostname === hostname);
|
||||||
|
if (!row) return null;
|
||||||
|
const wiki = hostname === "wiki.home.test";
|
||||||
|
return {
|
||||||
|
hostname,
|
||||||
|
upstreams: row.upstreams,
|
||||||
|
tls: row.tls,
|
||||||
|
auth: row.auth,
|
||||||
|
websockets: row.websockets,
|
||||||
|
share_links: row.share_links,
|
||||||
|
device_certs: row.device_certs,
|
||||||
|
access_log: wiki ? "truncated" : "off",
|
||||||
|
health_check: (row.health as Json).state === "unknown" ? null : { path: wiki ? "/healthz" : "/", interval_secs: 30 },
|
||||||
|
request_headers: [],
|
||||||
|
response_headers: wiki ? [{ action: "set", name: "X-Frame-Options", value: "SAMEORIGIN" }] : [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const HISTORY = [
|
||||||
|
{ change_id: "ch_0008", summary: "Added recipes.home.test", kind: "add", state: "kept", ago: 2 * 3600, commit_short: "c41d7e2", hosts: ["recipes.home.test"], reason_short: null },
|
||||||
|
{ change_id: "ch_0007", summary: "Changed music.home.test", kind: "edit", state: "kept", ago: 1 * DAY, commit_short: "8e03b5a", hosts: ["music.home.test"], reason_short: null },
|
||||||
|
{ change_id: "ch_0006", summary: "Turned share links on for wiki.home.test", kind: "share_links", state: "kept", ago: 2 * DAY, commit_short: "5a9f210", hosts: ["wiki.home.test"], reason_short: null },
|
||||||
|
{ change_id: "ch_0005", summary: "Changed photos.home.test", kind: "edit", state: "reverted", ago: 3 * DAY, commit_short: null, hosts: ["photos.home.test"], reason_short: "photos.home.test answered 502 during the watch" },
|
||||||
|
{ change_id: "ch_0004", summary: "Added cameras.home.test", kind: "add", state: "kept", ago: 5 * DAY, commit_short: "0b7c4e9", hosts: ["cameras.home.test"], reason_short: null },
|
||||||
|
{ change_id: "ch_0003", summary: "Added printer.home.test", kind: "add", state: "kept", ago: 9 * DAY, commit_short: "e2d81f6", hosts: ["printer.home.test"], reason_short: null },
|
||||||
|
{ change_id: "ch_0002", summary: "Added status.home.test", kind: "add", state: "kept", ago: 12 * DAY, commit_short: "73a6c05", hosts: ["status.home.test"], reason_short: null },
|
||||||
|
{ change_id: "ch_0001", summary: "Added wiki.home.test", kind: "add", state: "kept", ago: 20 * DAY, commit_short: "1f4b9a3", hosts: ["wiki.home.test"], reason_short: null },
|
||||||
|
];
|
||||||
|
|
||||||
|
function history(): Json {
|
||||||
|
return { entries: HISTORY.map(({ ago, ...e }) => ({ ...e, at: at(-ago) })), next_before: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function restorePreview(id: string): Json {
|
||||||
|
if (id === "ch_0008") return { restorable: false, same_as_current: true, changes: [], blocked: { code: "restore.same", message: "This version is the same as the current one." } };
|
||||||
|
return {
|
||||||
|
restorable: true,
|
||||||
|
same_as_current: false,
|
||||||
|
changes: [
|
||||||
|
{ hostname: "recipes.home.test", effect: "removed", fields: [] },
|
||||||
|
{ hostname: "music.home.test", effect: "changed", fields: [{ field: "upstreams", from: MUSIC.join(", "), to: MUSIC[0] }] },
|
||||||
|
],
|
||||||
|
blocked: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function certs(): Json {
|
||||||
|
const device = (id: string, name: string, kind: string, made: number, until: number, revoked: number | null = null) => ({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
kind,
|
||||||
|
created_at: at(-made * DAY),
|
||||||
|
not_after: at(until * DAY),
|
||||||
|
state: revoked === null ? "valid" : "revoked",
|
||||||
|
revoked_at: revoked === null ? null : at(-revoked * DAY),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
intermediate: intermediate(),
|
||||||
|
root: { offline: true, subject: "Demo Root CA", not_after: at(3000 * DAY), sha256: "5c0f9e2a71d84b36a8e1f40c2d9b7e6315a2c8d04f9b1e7a6c3d5f8e0b2a4c61" },
|
||||||
|
devices: [
|
||||||
|
device("dv_1", "ada's phone", "phone", 40, 325),
|
||||||
|
device("dv_2", "felix's laptop", "computer", 61, 304),
|
||||||
|
device("dv_3", "Kitchen tablet", "phone", 345, 20),
|
||||||
|
device("dv_4", "Notes app on the desk PC", "app", 12, 353),
|
||||||
|
device("dv_5", "Old phone", "phone", 200, 165, 30),
|
||||||
|
],
|
||||||
|
device_lifetime_days: 365,
|
||||||
|
device_valid_until: null,
|
||||||
|
server_lifetime_days: 90,
|
||||||
|
approval: "manual",
|
||||||
|
requests: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The demo's own answers, first; the smoke test's stand-in answers the rest. */
|
||||||
|
export function demoRoutes(): Route[] {
|
||||||
|
return [
|
||||||
|
["GET", /^\/overview$/, () => [200, overview()]],
|
||||||
|
["GET", /^\/hosts\/([^/?]+)$/, (mm) => {
|
||||||
|
const s = spec(decodeURIComponent(mm[1]));
|
||||||
|
return s ? [200, { host: s, rev: "rev-demo-8" }] : [404, { error: { code: "host.not_found", message: "There is no such host.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "demo" }];
|
||||||
|
}],
|
||||||
|
["GET", /^\/history(\?.*)?$/, () => [200, history()]],
|
||||||
|
["GET", /^\/history\/([^/]+)\/restore-preview$/, (mm) => [200, restorePreview(decodeURIComponent(mm[1]))]],
|
||||||
|
["GET", /^\/certs$/, () => [200, certs()]],
|
||||||
|
["GET", /^\/settings$/, () => [200, { repo: { name: "home-routes", last_push_at: at(-2 * 3600) }, watch_seconds: 60 }]],
|
||||||
|
...mockRoutes(newMock()),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Control's API for the demo: `path` is what follows /api/v1 (with its query). */
|
||||||
|
export function demoApi(): (method: string, path: string, body: Json) => { status: number; text: string | null } {
|
||||||
|
const routes = demoRoutes();
|
||||||
|
return (method, path, body) => respond(routes, method.toUpperCase(), path, body);
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// The smoke test of every ROADMAP §4 flow with its clicks counted (handoff §4, §15): the real
|
||||||
|
// app against a stand-in for control's API. Typing, focus and waiting are not clicks.
|
||||||
|
|
||||||
|
import { cleanup, render, screen, waitFor, within } from "@testing-library/svelte";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import App from "../src/App.svelte";
|
||||||
|
import { app } from "../src/lib/app.svelte";
|
||||||
|
import { installMock, type Mock } from "./mockApi";
|
||||||
|
|
||||||
|
let mock: Mock;
|
||||||
|
let clicks = 0;
|
||||||
|
let user: ReturnType<typeof userEvent.setup>;
|
||||||
|
|
||||||
|
async function click(el: Element) {
|
||||||
|
clicks++;
|
||||||
|
await user.click(el);
|
||||||
|
}
|
||||||
|
|
||||||
|
function start(path = "/") {
|
||||||
|
history.replaceState({}, "", path);
|
||||||
|
app.path = path;
|
||||||
|
app.panel = null;
|
||||||
|
app.overview = null;
|
||||||
|
app.etag = null;
|
||||||
|
app.signedOut = false;
|
||||||
|
app.switchResult = null;
|
||||||
|
app.renewedUntil = null;
|
||||||
|
app.dismissed = [];
|
||||||
|
mock = installMock();
|
||||||
|
clicks = 0;
|
||||||
|
user = userEvent.setup();
|
||||||
|
render(App);
|
||||||
|
}
|
||||||
|
|
||||||
|
const called = (method: string, path: string) => mock.calls.some((c) => c.method === method && c.path.startsWith(path));
|
||||||
|
const T = { timeout: 5000 };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
try {
|
||||||
|
sessionStorage.clear();
|
||||||
|
} catch {
|
||||||
|
/* none */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
afterEach(() => cleanup());
|
||||||
|
|
||||||
|
describe("ROADMAP §4 flows, clicks counted", () => {
|
||||||
|
it("Add host: + Host → fill → Apply = 2 clicks, auto-kept", async () => {
|
||||||
|
start();
|
||||||
|
await click(await screen.findByRole("button", { name: "Add a host" }));
|
||||||
|
await user.type(await screen.findByLabelText("Hostname"), "recipes.home.test");
|
||||||
|
await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080");
|
||||||
|
await click(screen.getByRole("button", { name: "Apply" }));
|
||||||
|
// Kept: the panel closes by itself and the new host is in the list.
|
||||||
|
await waitFor(() => expect(called("GET", "/applies/ch_new")).toBe(true), T);
|
||||||
|
await waitFor(() => expect(document.querySelector("dialog.ia-panel")).toBeNull(), T);
|
||||||
|
await screen.findByRole("button", { name: "More for recipes.home.test" }, T);
|
||||||
|
expect(called("POST", "/hosts")).toBe(true);
|
||||||
|
const sent = mock.calls.find((c) => c.method === "POST" && c.path === "/hosts")?.body as { host: Record<string, unknown> };
|
||||||
|
// Every field is sent explicitly, with the design's defaults.
|
||||||
|
expect(sent.host).toMatchObject({ hostname: "recipes.home.test", tls: "domi", auth: "forward-auth", websockets: true });
|
||||||
|
expect(clicks).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Undo last change = 1 click", async () => {
|
||||||
|
start();
|
||||||
|
await click(await screen.findByRole("button", { name: /^Undo: Added recipes\.home\.test/ }));
|
||||||
|
await waitFor(() => expect(called("POST", "/undo")).toBe(true));
|
||||||
|
const body = mock.calls.find((c) => c.path === "/undo" && c.method === "POST")?.body as Record<string, string>;
|
||||||
|
expect(body.target_change_id).toBe("ch_1");
|
||||||
|
expect(clicks).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Restore: History → pick → Restore = 3 clicks", async () => {
|
||||||
|
start();
|
||||||
|
await screen.findByRole("button", { name: "Add a host" });
|
||||||
|
const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
|
||||||
|
await click(within(nav).getByRole("link", { name: "History" }));
|
||||||
|
await click(await screen.findByRole("button", { name: /Changed wiki\.home\.test/ }));
|
||||||
|
await screen.findByText(/sends traffic to changes from/);
|
||||||
|
await click(await screen.findByRole("button", { name: "Restore this version" }));
|
||||||
|
await waitFor(() => expect(called("POST", "/restore")).toBe(true));
|
||||||
|
expect(clicks).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Share link: ⋯ → Share link → Copy = 3 clicks (default expiry 7 days)", async () => {
|
||||||
|
start();
|
||||||
|
await click(await screen.findByRole("button", { name: "More for wiki.home.test" }));
|
||||||
|
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
|
||||||
|
const copy = await screen.findByRole("button", { name: "Copy link" });
|
||||||
|
await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull());
|
||||||
|
await click(copy);
|
||||||
|
await screen.findByText("Copied");
|
||||||
|
const mint = mock.calls.find((c) => c.method === "POST" && c.path.endsWith("/share-links"))?.body as Record<string, unknown>;
|
||||||
|
expect(mint.expires_in_s).toBe(604800);
|
||||||
|
expect(await navigator.clipboard.readText()).toContain("?share=ish1.");
|
||||||
|
expect(clicks).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Share link on a host with links off: 4 clicks (Mark, Q1: the accepted 4th)", async () => {
|
||||||
|
start();
|
||||||
|
await click(await screen.findByRole("button", { name: "More for photos.home.test" }));
|
||||||
|
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
|
||||||
|
await click(await screen.findByRole("button", { name: "Turn on share links" }));
|
||||||
|
const copy = await screen.findByRole("button", { name: "Copy link" }, T);
|
||||||
|
await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull());
|
||||||
|
await click(copy);
|
||||||
|
await screen.findByText("Copied");
|
||||||
|
expect(called("PATCH", "/hosts/photos.home.test")).toBe(true);
|
||||||
|
expect(clicks).toBe(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Switch engine: engine chip → Switch to Caddy = 2 clicks", async () => {
|
||||||
|
start();
|
||||||
|
await click(await screen.findByRole("button", { name: /^Engine: Pingora/ }));
|
||||||
|
await click(await screen.findByRole("button", { name: "Switch to Caddy" }));
|
||||||
|
await waitFor(() => expect(called("POST", "/engine")).toBe(true));
|
||||||
|
const body = mock.calls.find((c) => c.method === "POST" && c.path === "/engine")?.body as Record<string, string>;
|
||||||
|
expect(body.target).toBe("caddy");
|
||||||
|
await screen.findByText("Now serving with Caddy.", {}, T);
|
||||||
|
expect(clicks).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Device certificate: Certificates → + Device → Issue = 3 clicks; install is the accepted 4th", async () => {
|
||||||
|
start();
|
||||||
|
await screen.findByRole("button", { name: "Add a host" });
|
||||||
|
const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
|
||||||
|
await click(within(nav).getByRole("link", { name: "Certificates" }));
|
||||||
|
await click(await screen.findByRole("button", { name: "Add a device certificate" }));
|
||||||
|
await user.type(await screen.findByLabelText("Device name"), "Mark's phone");
|
||||||
|
await click(screen.getByRole("button", { name: "Issue" }));
|
||||||
|
await screen.findByLabelText("Match code 47 19 83");
|
||||||
|
expect(clicks).toBe(3);
|
||||||
|
// Approved on the server (the stand-in approves on the first poll).
|
||||||
|
await click(await screen.findByRole("button", { name: "Show QR code" }, T));
|
||||||
|
await screen.findByText("ABCD-EFGH-JKLM-NPQR");
|
||||||
|
expect(clicks).toBe(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Renew intermediate: banner Renew = 1 click", async () => {
|
||||||
|
start();
|
||||||
|
await click(await screen.findByRole("button", { name: "Renew" }));
|
||||||
|
await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true));
|
||||||
|
// The renewal is waiting: the banner says where to sign it (no code to compare with openssl).
|
||||||
|
await screen.findByRole("button", { name: "Sign it by hand" });
|
||||||
|
expect(clicks).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("API token: ⚙ → API → New token = 3 clicks; Copy token is the accepted 4th", async () => {
|
||||||
|
start();
|
||||||
|
await screen.findByRole("button", { name: "Add a host" });
|
||||||
|
const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
|
||||||
|
await click(within(nav).getByRole("link", { name: "Settings" }));
|
||||||
|
await click(await screen.findByRole("tab", { name: "API" }));
|
||||||
|
await click(await screen.findByRole("button", { name: "New token" }));
|
||||||
|
const box = (await screen.findByLabelText("New API token")) as HTMLInputElement;
|
||||||
|
expect(box.value).toBe("ian_tk1_secretvalue");
|
||||||
|
expect(clicks).toBe(3);
|
||||||
|
await click(screen.getByRole("button", { name: "Copy token" }));
|
||||||
|
expect(await navigator.clipboard.readText()).toBe("ian_tk1_secretvalue");
|
||||||
|
expect(clicks).toBe(4);
|
||||||
|
// The token is never stored by the page.
|
||||||
|
expect(JSON.stringify({ ...sessionStorage })).not.toContain("ian_tk1");
|
||||||
|
expect(JSON.stringify({ ...localStorage })).not.toContain("ian_tk1");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("T4 flows, clicks counted", () => {
|
||||||
|
it("See active previews = 1 click", async () => {
|
||||||
|
start();
|
||||||
|
const nav = (await screen.findAllByRole("navigation", { name: "Main" }, T))[0];
|
||||||
|
await click(within(nav).getByRole("link", { name: "Previews" }));
|
||||||
|
await screen.findByRole("link", { name: "fix-42--shop.preview.home.test" }, T);
|
||||||
|
expect(clicks).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Kill a preview = 2 clicks (Close → Close preview)", async () => {
|
||||||
|
start("/previews");
|
||||||
|
await click(await screen.findByRole("button", { name: "Close" }, T));
|
||||||
|
await click(await screen.findByRole("button", { name: "Close preview" }));
|
||||||
|
await waitFor(() => expect(called("DELETE", "/previews/fix-42--shop.preview.home.test")).toBe(true), T);
|
||||||
|
await screen.findByRole("heading", { name: "No previews open" }, T);
|
||||||
|
expect(clicks).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Invite a teammate: Settings → Team → Invite = 3 clicks, the link shown", async () => {
|
||||||
|
start();
|
||||||
|
const nav = (await screen.findAllByRole("navigation", { name: "Main" }, T))[0];
|
||||||
|
await click(within(nav).getByRole("link", { name: "Settings" }));
|
||||||
|
await click(await screen.findByRole("tab", { name: "Team" }));
|
||||||
|
await user.type(await screen.findByLabelText("Name"), "Petra");
|
||||||
|
await click(screen.getByRole("button", { name: "Invite" }));
|
||||||
|
const link = (await screen.findByLabelText("Invite link", {}, T)) as HTMLInputElement;
|
||||||
|
expect(link.value).toMatch(/\/#signin=iin_testcode$/);
|
||||||
|
expect(clicks).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("focus", () => {
|
||||||
|
it("+ Host puts the cursor in Hostname, so typing right after the click lands there", async () => {
|
||||||
|
start();
|
||||||
|
await click(await screen.findByRole("button", { name: "Add a host" }));
|
||||||
|
await user.keyboard("recipes.home.test");
|
||||||
|
expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("recipes.home.test");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("the share dialog opens on Copy link and gives focus back to the row's More button", async () => {
|
||||||
|
start();
|
||||||
|
const more = await screen.findByRole("button", { name: "More for wiki.home.test" });
|
||||||
|
await click(more);
|
||||||
|
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
|
||||||
|
const copy = await screen.findByRole("button", { name: "Copy link" });
|
||||||
|
await waitFor(() => expect(document.activeElement).toBe(copy));
|
||||||
|
// jsdom fires no cancel event on Esc for a modal dialog: close it with its button.
|
||||||
|
await click(screen.getByRole("button", { name: "Close" }));
|
||||||
|
await waitFor(() => expect(screen.queryByRole("button", { name: "Copy link" })).toBeNull());
|
||||||
|
await waitFor(() => expect(document.activeElement).toBe(more));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("the engine popover closes with Esc and focus goes back to the chip", async () => {
|
||||||
|
start();
|
||||||
|
const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
|
||||||
|
await click(chip);
|
||||||
|
await screen.findByRole("button", { name: "Switch to Caddy" });
|
||||||
|
await user.keyboard("{Escape}");
|
||||||
|
await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
|
||||||
|
expect(document.activeElement).toBe(screen.getByRole("button", { name: /^Engine: Pingora/ }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a click on the engine chip while its popover is open closes it", async () => {
|
||||||
|
start();
|
||||||
|
const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
|
||||||
|
await click(chip);
|
||||||
|
await screen.findByRole("button", { name: "Switch to Caddy" });
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
await click(chip);
|
||||||
|
await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sign-in and contact", () => {
|
||||||
|
it("a 401 without Ianitor's envelope shows the signed-out dialog", async () => {
|
||||||
|
start();
|
||||||
|
await screen.findByRole("button", { name: "Add a host" });
|
||||||
|
globalThis.fetch = (async () => new Response("", { status: 401 })) as typeof fetch;
|
||||||
|
app.etag = null;
|
||||||
|
await click(screen.getByRole("button", { name: "Add a host" }));
|
||||||
|
await user.type(await screen.findByLabelText("Hostname"), "x.home.test");
|
||||||
|
await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080");
|
||||||
|
await click(screen.getByRole("button", { name: "Apply" }));
|
||||||
|
await screen.findByRole("alertdialog", { name: "Your sign-in has ended" });
|
||||||
|
// What was typed is still there.
|
||||||
|
expect((screen.getByLabelText("Hostname") as HTMLInputElement).value).toBe("x.home.test");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("every request carries the UI header and no token", async () => {
|
||||||
|
const seen: Headers[] = [];
|
||||||
|
start();
|
||||||
|
const inner = globalThis.fetch;
|
||||||
|
globalThis.fetch = (async (i: RequestInfo | URL, init?: RequestInit) => {
|
||||||
|
seen.push(new Headers(init?.headers));
|
||||||
|
return inner(i, init);
|
||||||
|
}) as typeof fetch;
|
||||||
|
await click(await screen.findByRole("button", { name: /^Undo:/ }));
|
||||||
|
await waitFor(() => expect(seen.length).toBeGreaterThan(0));
|
||||||
|
for (const h of seen) {
|
||||||
|
expect(h.get("X-Ianitor-UI")).toBe("1");
|
||||||
|
expect(h.get("Authorization")).toBeNull();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// A stateful stand-in for control's API, shaped like the real answers (docs/api.md), so the
|
||||||
|
// smoke tests can walk every §4 flow and count its clicks. Its builders and routes are also the
|
||||||
|
// base of the screenshots' demo control plane (demo.ts, docs/release.md).
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>;
|
||||||
|
|
||||||
|
export interface Mock {
|
||||||
|
calls: { method: string; path: string; body: unknown }[];
|
||||||
|
state: {
|
||||||
|
engine: "pingora" | "caddy";
|
||||||
|
previewClosed: boolean;
|
||||||
|
switching: number;
|
||||||
|
intermediate: "ok" | "due";
|
||||||
|
renewal: boolean;
|
||||||
|
requestPolls: number;
|
||||||
|
hostsAdded: string[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = () => new Date().toISOString();
|
||||||
|
const later = (s: number) => new Date(Date.now() + s * 1000).toISOString();
|
||||||
|
|
||||||
|
export function host(hostname: string, share: boolean) {
|
||||||
|
return {
|
||||||
|
hostname,
|
||||||
|
upstreams: ["http://10.0.0.2:3000"],
|
||||||
|
tls: "domi",
|
||||||
|
auth: "forward-auth",
|
||||||
|
websockets: true,
|
||||||
|
share_links: share,
|
||||||
|
device_certs: false,
|
||||||
|
added_at: null,
|
||||||
|
health: { state: "healthy", last_check_at: now(), latency_ms: 12, since: now(), failure: null, upstreams: [] },
|
||||||
|
certificate: { state: "ok", not_after: later(86400 * 80), error_code: null },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function apply(id: string, state: string, summary: string, hosts: string[]) {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
change_id: id,
|
||||||
|
kind: "add",
|
||||||
|
summary,
|
||||||
|
hosts,
|
||||||
|
state,
|
||||||
|
created_at: now(),
|
||||||
|
finished_at: state === "kept" ? now() : null,
|
||||||
|
steps: ["validate", "compile", "write", "reload", "watch", "push"].map((key) => ({ key, state: state === "kept" ? "done" : "pending" })),
|
||||||
|
queue: null,
|
||||||
|
watch: null,
|
||||||
|
reason: state === "kept" ? { code: "apply.kept", message: `${hosts[0]} is live. Health checks passed for 60 s.` } : null,
|
||||||
|
errors: [],
|
||||||
|
commit_short: "4f1c2ab",
|
||||||
|
push: null,
|
||||||
|
attempted_host: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One API call: method, the path after /api/v1, and its answer as [status, body]. */
|
||||||
|
export type Route = [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]];
|
||||||
|
|
||||||
|
export function newMock(): Mock {
|
||||||
|
return {
|
||||||
|
calls: [],
|
||||||
|
state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [], previewClosed: false },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first route that matches answers, with server_time added as control does; else control's 404. */
|
||||||
|
export function respond(routes: Route[], method: string, path: string, body: Json): { status: number; text: string | null } {
|
||||||
|
for (const [mm, re, f] of routes) {
|
||||||
|
const match = path.match(re);
|
||||||
|
if (mm === method && match) {
|
||||||
|
const [status, data] = f(match, body);
|
||||||
|
const withTime = data && typeof data === "object" ? { ...(data as Json), server_time: now() } : data;
|
||||||
|
return { status, text: status === 204 ? null : JSON.stringify(withTime) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { status: 404, text: JSON.stringify({ error: { code: "request.not_found", message: "There is no such API call.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "x" }) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mockRoutes(m: Mock): Route[] {
|
||||||
|
const overview = (): Json => ({
|
||||||
|
counts: { hosts: 2 + m.state.hostsAdded.length, healthy: 2, degraded: 0, down: 0, unknown: 0 },
|
||||||
|
hosts: [host("wiki.home.test", true), host("photos.home.test", false), ...m.state.hostsAdded.map((h) => host(h, false))],
|
||||||
|
engine: {
|
||||||
|
running: m.state.engine,
|
||||||
|
state: m.state.switching > 0 ? "switching" : "running",
|
||||||
|
since: now(),
|
||||||
|
target: null,
|
||||||
|
switchable: true,
|
||||||
|
fallback_ready: { built_at: now(), current: true, compared: 3, matched: 3, differences: ["Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."] },
|
||||||
|
last_error: null,
|
||||||
|
notes: [],
|
||||||
|
},
|
||||||
|
last_apply: apply("ch_1", "kept", "Added recipes.home.test", ["recipes.home.test"]),
|
||||||
|
undo: {
|
||||||
|
available: true,
|
||||||
|
target: { change_id: "ch_1", summary: "Added recipes.home.test", kept_at: now(), commit_short: "4f1c2ab" },
|
||||||
|
effect: "Removes recipes.home.test",
|
||||||
|
blocked: null,
|
||||||
|
},
|
||||||
|
active_apply: null,
|
||||||
|
repo: { name: "ianitor-routes", last_push_at: now(), unpushed: 0, push_error_code: null },
|
||||||
|
intermediate:
|
||||||
|
m.state.intermediate === "due"
|
||||||
|
? {
|
||||||
|
state: "due",
|
||||||
|
subject: "Ianitor Domi Intermediate 2025-12",
|
||||||
|
not_after: later(86400 * 23),
|
||||||
|
days_left: 23,
|
||||||
|
renewal: m.state.renewal
|
||||||
|
? { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(3600), approved_at: null, device_id: null, name: null, csr_pem: "-----BEGIN CERTIFICATE REQUEST-----\nx\n-----END CERTIFICATE REQUEST-----\n", not_after: null, message_code: "pki.renew.manual", message: "Sign this request…", approve_command: "ianitor-control ca sign …", problem: null }
|
||||||
|
: null,
|
||||||
|
banner: m.state.renewal ? null : { code: "pki.renew_due", message: "The Domi intermediate certificate expires in 23 days, on 30 November 2026." },
|
||||||
|
}
|
||||||
|
: { state: "ok", subject: "x", not_after: later(86400 * 300), days_left: 300, renewal: null, banner: null },
|
||||||
|
site: { forward_auth_configured: true, acme_configured: true, secrets: ["api_key"], watch_seconds: 60, share_links_available: true },
|
||||||
|
paused: null,
|
||||||
|
paused_reason: null,
|
||||||
|
health_error: null,
|
||||||
|
rev: "rev1",
|
||||||
|
viewer: { name: "mark", via: "authelia" },
|
||||||
|
server_time: now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
return [
|
||||||
|
["GET", /^\/overview$/, () => [200, overview()]],
|
||||||
|
["POST", /^\/hosts\/validate/, () => [200, { message: "This host can be applied." }]],
|
||||||
|
["POST", /^\/hosts$/, (_, b) => {
|
||||||
|
const h = (b.host as Json).hostname as string;
|
||||||
|
m.state.hostsAdded.push(h);
|
||||||
|
return [202, { apply: apply("ch_new", "queued", `Added ${h}`, [h]) }];
|
||||||
|
}],
|
||||||
|
["GET", /^\/applies\/ch_new$/, () => [200, apply("ch_new", "kept", `Added ${m.state.hostsAdded.at(-1)}`, [m.state.hostsAdded.at(-1) ?? ""])]],
|
||||||
|
["GET", /^\/applies\/(.+)$/, (mm) => [200, apply(mm[1], "kept", "Done", ["x.home.test"])]],
|
||||||
|
["POST", /^\/undo$/, () => [202, { apply: apply("ch_undo", "queued", "Undid: Added recipes.home.test", ["recipes.home.test"]) }]],
|
||||||
|
["GET", /^\/history(\?.*)?$/, () => [200, { entries: [{ change_id: "ch_old", summary: "Changed wiki.home.test", kind: "edit", state: "kept", at: now(), commit_short: "9b20e7d", hosts: ["wiki.home.test"], reason_short: null }], next_before: null }]],
|
||||||
|
["GET", /^\/history\/ch_old\/restore-preview$/, () => [200, { restorable: true, same_as_current: false, changes: [{ hostname: "wiki.home.test", effect: "changed", fields: [{ field: "upstreams", from: "http://10.0.0.2:3000", to: "http://10.0.0.9:3000" }] }], blocked: null }]],
|
||||||
|
["POST", /^\/restore$/, () => [202, { apply: apply("ch_restore", "queued", "Restored the version of 5 November 2026", ["wiki.home.test"]) }]],
|
||||||
|
["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_1", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.abc`, expires_at: later(7 * 86400), path_prefix: "/", has_password: false, warning: null }]],
|
||||||
|
["PATCH", /^\/hosts\/([^/]+)$/, (mm) => [202, { apply: apply("ch_share", "queued", `Turned share links on for ${decodeURIComponent(mm[1])}`, [decodeURIComponent(mm[1])]) }]],
|
||||||
|
["DELETE", /^\/share-links\/.+$/, () => [204, null]],
|
||||||
|
["GET", /^\/engine$/, () => {
|
||||||
|
if (m.state.switching > 0) {
|
||||||
|
m.state.switching--;
|
||||||
|
if (m.state.switching === 0) m.state.engine = "caddy";
|
||||||
|
}
|
||||||
|
return [200, { running: m.state.engine, state: m.state.switching > 0 ? "switching" : "running", target: null, since: now(), switchable: true, last_error: null, notes: [] }];
|
||||||
|
}],
|
||||||
|
["POST", /^\/engine$/, () => {
|
||||||
|
m.state.switching = 1;
|
||||||
|
return [202, { running: m.state.engine, state: "switching", target: "caddy", since: now(), switchable: true, last_error: null, notes: [] }];
|
||||||
|
}],
|
||||||
|
["GET", /^\/certs$/, () => [200, { intermediate: overview().intermediate, root: { offline: true, subject: "Domi PKI Root", not_after: later(86400 * 3000), sha256: "ab" }, devices: [], device_lifetime_days: 365, server_lifetime_days: 90, approval: "manual", requests: [] }]],
|
||||||
|
["POST", /^\/certs\/devices$/, (_, b) => [202, { request_id: "pr_dev", kind: "device", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: null, device_id: null, name: b.name, csr_pem: null, not_after: null, message_code: "pki.waiting.manual", message: "Approve it on the server…", approve_command: "ianitor-control pki approve 47 19 83", problem: null }]],
|
||||||
|
["GET", /^\/pki-requests\/pr_dev$/, () => {
|
||||||
|
m.state.requestPolls++;
|
||||||
|
return [200, { request_id: "pr_dev", kind: "device", state: "approved", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: now(), device_id: "dv_1", name: "Mark's phone", csr_pem: null, not_after: null, message_code: "pki.issued", message: "Mark's phone has a certificate.", approve_command: null, problem: null }];
|
||||||
|
}],
|
||||||
|
["POST", /^\/certs\/devices\/dv_1\/bundle$/, () => [200, { download_url: "https://ui.home.test/api/v1/device-bundles/abc", one_time_password: "ABCD-EFGH-JKLM-NPQR", expires_at: later(600), filename: "domi-device.p12", qr_svg: "<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>" }]],
|
||||||
|
["POST", /^\/certs\/intermediate\/renewal$/, () => {
|
||||||
|
m.state.renewal = true;
|
||||||
|
return [202, { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83" }];
|
||||||
|
}],
|
||||||
|
["GET", /^\/settings$/, () => [200, { repo: { name: "ianitor-routes", last_push_at: now() }, watch_seconds: 60 }]],
|
||||||
|
["GET", /^\/tokens$/, () => [200, { items: [] }]],
|
||||||
|
["POST", /^\/tokens$/, (_, b) => [201, { id: "tk_1", name: b.name, token: "ian_tk1_secretvalue", expires_at: later(365 * 86400) }]],
|
||||||
|
["GET", /^\/share-links$/, () => [200, { items: [], epoch: 0 }]],
|
||||||
|
// T4: previews and the team (invented .test names only).
|
||||||
|
["GET", /^\/previews$/, () => [200, {
|
||||||
|
domain: "preview.home.test",
|
||||||
|
items: m.state.previewClosed ? [] : [{ hostname: "fix-42--shop.preview.home.test", url: "https://fix-42--shop.preview.home.test/", project: "team/shop", branch: "fix-42", upstream: "http://10.0.0.7:8080", expires_at: later(86400), state: "live" }],
|
||||||
|
}]],
|
||||||
|
["DELETE", /^\/previews\/fix-42--shop\.preview\.home\.test$/, () => {
|
||||||
|
m.state.previewClosed = true;
|
||||||
|
return [202, { apply: apply("ch_pv", "queued", "Closed the preview of fix-42 (team/shop)", ["fix-42--shop.preview.home.test"]) }];
|
||||||
|
}],
|
||||||
|
["GET", /^\/team$/, () => [200, { me: { id: "m1", name: "Mark", role: "admin", added_at: now(), tessera_root: null, match_code: null }, members: [{ id: "m1", name: "Mark", role: "admin", added_at: now(), tessera_root: null, match_code: null }], invites: [], authelia: false }]],
|
||||||
|
["POST", /^\/team\/invites$/, (_, b) => [201, { invite: { id: "iv1", name: b.name, role: b.role, expires_at: later(7 * 86400) }, link_fragment: "#signin=iin_testcode" }]],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function installMock(): Mock {
|
||||||
|
const m = newMock();
|
||||||
|
const routes = mockRoutes(m);
|
||||||
|
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
|
const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url;
|
||||||
|
const path = url.replace(/^.*\/api\/v1/, "");
|
||||||
|
const method = (init?.method ?? "GET").toUpperCase();
|
||||||
|
const body = init?.body ? JSON.parse(String(init.body)) : {};
|
||||||
|
m.calls.push({ method, path, body });
|
||||||
|
const a = respond(routes, method, path, body);
|
||||||
|
return new Response(a.text, { status: a.status, headers: { "Content-Type": "application/json" } });
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
return m;
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
// jsdom lacks a few browser features the UI uses.
|
||||||
|
|
||||||
|
if (typeof HTMLDialogElement !== "undefined") {
|
||||||
|
const p = HTMLDialogElement.prototype as HTMLDialogElement & Record<string, unknown>;
|
||||||
|
if (!p.showModal) {
|
||||||
|
p.showModal = function (this: HTMLDialogElement) {
|
||||||
|
this.setAttribute("open", "");
|
||||||
|
};
|
||||||
|
p.show = function (this: HTMLDialogElement) {
|
||||||
|
this.setAttribute("open", "");
|
||||||
|
};
|
||||||
|
p.close = function (this: HTMLDialogElement) {
|
||||||
|
this.removeAttribute("open");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const clipboard = { text: "", writeText: async (t: string) => void (clipboard.text = t) };
|
||||||
|
Object.defineProperty(globalThis.navigator, "clipboard", { value: clipboard, configurable: true });
|
||||||
|
(globalThis as unknown as { __clipboard: typeof clipboard }).__clipboard = clipboard;
|
||||||
|
|
||||||
|
if (!("BroadcastChannel" in globalThis)) {
|
||||||
|
(globalThis as unknown as { BroadcastChannel: unknown }).BroadcastChannel = class {
|
||||||
|
onmessage: unknown = null;
|
||||||
|
postMessage() {}
|
||||||
|
close() {}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!("randomUUID" in crypto)) {
|
||||||
|
Object.defineProperty(crypto, "randomUUID", { value: () => Math.random().toString(36).slice(2) });
|
||||||
|
}
|
||||||
|
|
||||||
|
window.open = () => null;
|
||||||
|
HTMLAnchorElement.prototype.click = function () {};
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"extends": "@tsconfig/svelte/tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noImplicitReturns": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"types": ["vite/client"],
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"]
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "src/**/*.svelte", "tests/**/*.ts", "../../packages/ui/src/**/*.ts", "../../packages/ui/src/**/*.svelte"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
import { svelte } from "@sveltejs/vite-plugin-svelte";
|
||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
|
||||||
|
// Dev server: 127.0.0.1 only (CLAUDE.md), never --host 0.0.0.0. /api goes to control's --dev on
|
||||||
|
// 127.0.0.1:7878. In production edge sends Authelia's identity and the per-boot proof; in dev
|
||||||
|
// there is no Authelia, so the dev proxy (never the browser) adds the dev API token from
|
||||||
|
// $IANITOR_DEV_TOKEN, which `ianitor-control --dev` prints.
|
||||||
|
const control = process.env.IANITOR_CONTROL ?? "http://127.0.0.1:7878";
|
||||||
|
const token = process.env.IANITOR_DEV_TOKEN;
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [svelte()],
|
||||||
|
server: {
|
||||||
|
host: "127.0.0.1",
|
||||||
|
port: 5173,
|
||||||
|
strictPort: true,
|
||||||
|
proxy: {
|
||||||
|
"/api": {
|
||||||
|
target: control,
|
||||||
|
changeOrigin: true,
|
||||||
|
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
preview: { host: "127.0.0.1" },
|
||||||
|
build: { outDir: "dist", sourcemap: false, assetsInlineLimit: 0 },
|
||||||
|
resolve: process.env.VITEST ? { conditions: ["browser"] } : undefined,
|
||||||
|
test: {
|
||||||
|
environment: "jsdom",
|
||||||
|
setupFiles: ["./tests/setup.ts"],
|
||||||
|
include: ["tests/**/*.test.ts"],
|
||||||
|
testTimeout: 20000,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
[package]
|
||||||
|
name = "ianitor-control"
|
||||||
|
description = "Ianitor Domi control plane: routes repo, apply with automatic rollback, share links, API tokens, REST API on loopback."
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "ianitor_control"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "ianitor-control"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
# The crash and write-failure hooks of the crash-safety tests (src/crash.rs). The Nix release
|
||||||
|
# build turns them off with --no-default-features.
|
||||||
|
default = ["test-hooks"]
|
||||||
|
test-hooks = []
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
ianitor-core.workspace = true
|
||||||
|
url.workspace = true
|
||||||
|
rustls.workspace = true
|
||||||
|
rustls-pki-types.workspace = true
|
||||||
|
tokio-rustls.workspace = true
|
||||||
|
axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "matched-path"] }
|
||||||
|
utoipa = "5"
|
||||||
|
tokio.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
toml.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
log.workspace = true
|
||||||
|
ring.workspace = true
|
||||||
|
base64.workspace = true
|
||||||
|
http.workspace = true
|
||||||
|
bytes.workspace = true
|
||||||
|
# Device certificate install files (PKCS#12) and their QR codes.
|
||||||
|
p12-keystore = "0.4"
|
||||||
|
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
|
||||||
|
# The offline root CLI asks for its passphrase without echo.
|
||||||
|
rpassword = "7"
|
||||||
|
|
||||||
|
# Windows Server, Caddy mode: the service control manager starts control and the guard.
|
||||||
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
windows-service = "0.8"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
ianitor-testkit.workspace = true
|
||||||
|
p12-keystore = "0.4"
|
||||||
|
ianitor-edge.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,754 @@
|
|||||||
|
// 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 REST + JSON API on loopback (`/api/v1`), with its OpenAPI document generated from the
|
||||||
|
//! handlers (utoipa).
|
||||||
|
//!
|
||||||
|
//! Every request: the `Host` header must name this server (against DNS rebinding); a browser
|
||||||
|
//! write without `X-Ianitor-UI: 1` is refused (CSRF); a valid `Authorization: Bearer` API
|
||||||
|
//! token is required (nothing else identifies the caller: control trusts no `Remote-*`
|
||||||
|
//! header); 120 requests a minute per token. Bodies are at most 64 KiB, JSON, with no
|
||||||
|
//! unknown fields. Errors are one typed envelope with a plain-English message. Logs show
|
||||||
|
//! method, route template, status and time only.
|
||||||
|
|
||||||
|
// An error answer is built once per failed request; boxing it buys nothing.
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
|
pub mod handlers;
|
||||||
|
pub mod pki;
|
||||||
|
pub mod previews;
|
||||||
|
pub mod team;
|
||||||
|
pub mod ui;
|
||||||
|
pub mod views;
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use axum::Router;
|
||||||
|
use axum::body::{Body as AxumBody, Bytes};
|
||||||
|
use axum::extract::{DefaultBodyLimit, FromRequest, MatchedPath, Request, State};
|
||||||
|
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||||
|
use axum::middleware::{self, Next};
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use axum::routing::{delete, get, post};
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
use utoipa::OpenApi;
|
||||||
|
|
||||||
|
pub use views::health_state;
|
||||||
|
|
||||||
|
use crate::engine::{Control, Fail};
|
||||||
|
use crate::messages::{self, Params, message};
|
||||||
|
use crate::tokens::Refusal;
|
||||||
|
use crate::util::{hex, now, random, rfc3339, sha256_hex};
|
||||||
|
use views::{ErrorBody, ErrorEnvelope};
|
||||||
|
|
||||||
|
pub const MAX_BODY: usize = 64 * 1024;
|
||||||
|
const RATE_PER_MINUTE: u32 = 120;
|
||||||
|
|
||||||
|
/// Who is calling: the API token's id and name, and what the token may do.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Actor {
|
||||||
|
pub token_id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub scope: crate::tokens::Scope,
|
||||||
|
/// A team member signed in with a session (`crate::team`): their id, session and role.
|
||||||
|
/// `None` for API tokens and Authelia sign-ins, which may do everything.
|
||||||
|
pub member: Option<String>,
|
||||||
|
pub session: Option<String>,
|
||||||
|
pub role: Option<crate::team::Role>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What only an admin may do (a `member` session gets 403 `team.admin_only`): API tokens,
|
||||||
|
/// the team, the engine and the CA.
|
||||||
|
fn admin_only(method: &str, path: &str) -> bool {
|
||||||
|
let write = !matches!(method, "GET" | "HEAD" | "OPTIONS");
|
||||||
|
path.starts_with("/api/v1/tokens")
|
||||||
|
|| (path.starts_with("/api/v1/team/") && !path.starts_with("/api/v1/team/me/"))
|
||||||
|
|| (write && path == "/api/v1/engine")
|
||||||
|
|| (write && path.starts_with("/api/v1/certs/intermediate"))
|
||||||
|
|| path.starts_with("/api/v1/pki-requests")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The only routes a `previews` token may call (T4: it can never touch another host).
|
||||||
|
fn in_preview_scope(path: &str) -> bool {
|
||||||
|
path == "/api/v1/previews"
|
||||||
|
|| path
|
||||||
|
.strip_prefix("/api/v1/previews/")
|
||||||
|
.is_some_and(|rest| !rest.is_empty() && !rest.contains('/'))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum Stored {
|
||||||
|
/// The first request with this key is still being handled.
|
||||||
|
Pending,
|
||||||
|
Apply(String),
|
||||||
|
Json(u16, serde_json::Value),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Most Idempotency-Keys held at once (each for 24 h).
|
||||||
|
const MAX_IDEM_KEYS: usize = 2000;
|
||||||
|
|
||||||
|
pub struct AppState {
|
||||||
|
pub ctl: Arc<Control>,
|
||||||
|
idem: Mutex<HashMap<String, (String, Stored, u64)>>,
|
||||||
|
rate: Mutex<HashMap<String, (u64, u32)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub fn new(ctl: Arc<Control>) -> Arc<AppState> {
|
||||||
|
Arc::new(AppState {
|
||||||
|
ctl,
|
||||||
|
idem: Mutex::new(HashMap::new()),
|
||||||
|
rate: Mutex::new(HashMap::new()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Count one request against `bucket`; `Err(seconds to wait)` over the limit.
|
||||||
|
pub fn limit(&self, bucket: &str, per_window: u32, window: u64) -> Result<(), u64> {
|
||||||
|
let Ok(mut m) = self.rate.lock() else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let t = now();
|
||||||
|
let slot = t / window;
|
||||||
|
if m.len() > 10_000 {
|
||||||
|
m.retain(|_, (s, _)| *s + 1 >= slot);
|
||||||
|
}
|
||||||
|
let e = m.entry(bucket.to_owned()).or_insert((slot, 0));
|
||||||
|
if e.0 != slot {
|
||||||
|
*e = (slot, 0);
|
||||||
|
}
|
||||||
|
if e.1 >= per_window {
|
||||||
|
return Err((slot + 1) * window - t);
|
||||||
|
}
|
||||||
|
e.1 += 1;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a request with an Idempotency-Key, atomically: `Ok(Some)` replays an earlier
|
||||||
|
/// answer, `Ok(None)` reserves the key (finish with [`AppState::idem_finish`]), `Err` when
|
||||||
|
/// the key was used for another request, is still in progress, or no key can be held.
|
||||||
|
pub fn idem_begin(&self, key: &str, fingerprint: &str) -> Result<Option<Stored>, ApiError> {
|
||||||
|
let mut m = self
|
||||||
|
.idem
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| ApiError::internal("idempotency store"))?;
|
||||||
|
let t = now();
|
||||||
|
match m.get(key) {
|
||||||
|
Some((fp, _, at)) if t.saturating_sub(*at) < 86_400 && fp != fingerprint => {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"request.idempotency",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Some((_, Stored::Pending, at)) if t.saturating_sub(*at) < 86_400 => {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
"request.in_progress",
|
||||||
|
Params::new(),
|
||||||
|
)
|
||||||
|
.retry(1));
|
||||||
|
}
|
||||||
|
Some((_, Stored::Apply(id), at)) if t.saturating_sub(*at) < 86_400 => {
|
||||||
|
return Ok(Some(Stored::Apply(id.clone())));
|
||||||
|
}
|
||||||
|
Some((_, Stored::Json(s, v), at)) if t.saturating_sub(*at) < 86_400 => {
|
||||||
|
return Ok(Some(Stored::Json(*s, v.clone())));
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if m.len() >= MAX_IDEM_KEYS {
|
||||||
|
m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400);
|
||||||
|
}
|
||||||
|
if m.len() >= MAX_IDEM_KEYS {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::TOO_MANY_REQUESTS,
|
||||||
|
"rate.limited",
|
||||||
|
Params::new(),
|
||||||
|
)
|
||||||
|
.retry(60));
|
||||||
|
}
|
||||||
|
m.insert(key.to_owned(), (fingerprint.to_owned(), Stored::Pending, t));
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish a reserved key: remember the answer, or (on `None`, a refusal) free the key.
|
||||||
|
pub fn idem_finish(&self, key: &str, fingerprint: &str, s: Option<Stored>) {
|
||||||
|
if let Ok(mut m) = self.idem.lock() {
|
||||||
|
match s {
|
||||||
|
Some(s) => {
|
||||||
|
m.insert(key.to_owned(), (fingerprint.to_owned(), s, now()));
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
m.remove(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- errors
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ApiError {
|
||||||
|
pub status: StatusCode,
|
||||||
|
pub body: ErrorBody,
|
||||||
|
pub errors: Vec<ErrorBody>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApiError {
|
||||||
|
pub fn new(status: StatusCode, code: &str, params: Params) -> ApiError {
|
||||||
|
ApiError {
|
||||||
|
status,
|
||||||
|
body: ErrorBody {
|
||||||
|
code: code.into(),
|
||||||
|
message: message(code, ¶ms),
|
||||||
|
field: params.get("field").cloned(),
|
||||||
|
params,
|
||||||
|
retry_after_s: None,
|
||||||
|
detail: None,
|
||||||
|
},
|
||||||
|
errors: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn internal(detail: impl Into<String>) -> ApiError {
|
||||||
|
let mut e = ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", Params::new());
|
||||||
|
e.body.detail = Some(detail.into());
|
||||||
|
e
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn retry(mut self, secs: u64) -> ApiError {
|
||||||
|
self.body.retry_after_s = Some(secs);
|
||||||
|
self.body.params.insert("seconds".into(), secs.to_string());
|
||||||
|
self.body.message = message(&self.body.code, &self.body.params);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Fail> for ApiError {
|
||||||
|
fn from(f: Fail) -> ApiError {
|
||||||
|
ApiError {
|
||||||
|
status: StatusCode::from_u16(f.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
||||||
|
body: ErrorBody::from(&f.reason),
|
||||||
|
errors: f.errors.iter().map(ErrorBody::from).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for ApiError {
|
||||||
|
fn into_response(self) -> Response {
|
||||||
|
let retry = self.body.retry_after_s;
|
||||||
|
let env = ErrorEnvelope {
|
||||||
|
error: self.body,
|
||||||
|
errors: self.errors,
|
||||||
|
request_id: String::new(),
|
||||||
|
};
|
||||||
|
let mut r = (self.status, axum::Json(env)).into_response();
|
||||||
|
if let Some(s) = retry
|
||||||
|
&& let Ok(v) = HeaderValue::from_str(&s.to_string())
|
||||||
|
{
|
||||||
|
r.headers_mut().insert(header::RETRY_AFTER, v);
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- JSON bodies
|
||||||
|
|
||||||
|
/// A JSON request body: at most 64 KiB, no unknown fields, errors that never echo values.
|
||||||
|
pub struct Body<T> {
|
||||||
|
pub value: T,
|
||||||
|
pub raw: Bytes,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: DeserializeOwned, S: Send + Sync> FromRequest<S> for Body<T> {
|
||||||
|
type Rejection = ApiError;
|
||||||
|
|
||||||
|
async fn from_request(req: Request, state: &S) -> Result<Self, ApiError> {
|
||||||
|
let json_type = req
|
||||||
|
.headers()
|
||||||
|
.get(header::CONTENT_TYPE)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.is_some_and(|v| v.starts_with("application/json"));
|
||||||
|
let raw = Bytes::from_request(req, state).await.map_err(|_| {
|
||||||
|
ApiError::new(
|
||||||
|
StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
"request.too_large",
|
||||||
|
Params::new(),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let text: &[u8] = if raw.is_empty() { b"{}" } else { &raw };
|
||||||
|
if !raw.is_empty() && !json_type {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||||
|
"request.body",
|
||||||
|
messages::params([("problem", "send it as application/json.".into())]),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
match serde_json::from_slice::<T>(text) {
|
||||||
|
Ok(value) => Ok(Body { value, raw }),
|
||||||
|
Err(e) => Err(body_error(&e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body_error(e: &serde_json::Error) -> ApiError {
|
||||||
|
let m = e.to_string();
|
||||||
|
let quoted = |prefix: &str| -> Option<String> {
|
||||||
|
let rest = m.split(prefix).nth(1)?;
|
||||||
|
Some(rest.split('`').next()?.to_owned())
|
||||||
|
};
|
||||||
|
if let Some(f) = quoted("unknown field `") {
|
||||||
|
// The name is the sender's: repeat it only if it is a plain field name.
|
||||||
|
let plain = !f.is_empty()
|
||||||
|
&& f.len() <= 64
|
||||||
|
&& f.bytes()
|
||||||
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_');
|
||||||
|
let shown = if plain {
|
||||||
|
f
|
||||||
|
} else {
|
||||||
|
"(a field name)".to_owned()
|
||||||
|
};
|
||||||
|
let mut err = ApiError::new(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"request.body_unknown_field",
|
||||||
|
messages::params([("field", shown.clone())]),
|
||||||
|
);
|
||||||
|
err.body.field = plain.then_some(shown);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
if let Some(f) = quoted("missing field `") {
|
||||||
|
return ApiError::new(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"request.body",
|
||||||
|
messages::params([
|
||||||
|
("problem", format!("the field \"{f}\" is missing.")),
|
||||||
|
("field", f),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Other serde messages can quote the value sent; say only where the problem is.
|
||||||
|
let what = match e.classify() {
|
||||||
|
serde_json::error::Category::Syntax | serde_json::error::Category::Eof => "it is not JSON",
|
||||||
|
_ => "a value has the wrong type or form",
|
||||||
|
};
|
||||||
|
ApiError::new(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"request.body",
|
||||||
|
messages::params([(
|
||||||
|
"problem",
|
||||||
|
format!("{what} (line {}, column {}).", e.line(), e.column()),
|
||||||
|
)]),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- middleware
|
||||||
|
|
||||||
|
pub(crate) fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
|
||||||
|
let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let port = ctl.cfg.listen.port();
|
||||||
|
let ok = [
|
||||||
|
ctl.cfg.listen.to_string(),
|
||||||
|
format!("localhost:{port}"),
|
||||||
|
format!("127.0.0.1:{port}"),
|
||||||
|
format!("[::1]:{port}"),
|
||||||
|
];
|
||||||
|
// The admin host the engine forwards the UI on, with any port: behind Docker's or a
|
||||||
|
// router's port mapping the visitor's port is not the engine's (T4). The name is what
|
||||||
|
// keeps a rebound DNS name out.
|
||||||
|
let ui = ctl.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
|
||||||
|
let ui_ok = ui.is_some_and(|u| {
|
||||||
|
let name = match host.rsplit_once(':') {
|
||||||
|
Some((n, p)) if !p.is_empty() && p.bytes().all(|c| c.is_ascii_digit()) => n,
|
||||||
|
_ => host,
|
||||||
|
};
|
||||||
|
name.eq_ignore_ascii_case(u)
|
||||||
|
});
|
||||||
|
ui_ok
|
||||||
|
|| ok.iter().any(|o| o.eq_ignore_ascii_case(host))
|
||||||
|
|| ctl
|
||||||
|
.cfg
|
||||||
|
.allowed_hosts
|
||||||
|
.iter()
|
||||||
|
.any(|a| a.eq_ignore_ascii_case(host))
|
||||||
|
}
|
||||||
|
|
||||||
|
enum UiIdentity {
|
||||||
|
/// No sign-in headers: an API-token request.
|
||||||
|
None,
|
||||||
|
/// `Remote-*` or a proof header without the right proof.
|
||||||
|
Forged,
|
||||||
|
/// The right proof but no usable `Remote-User`.
|
||||||
|
NoUser,
|
||||||
|
/// The Authelia user name, and the name to show (`Remote-Name` when it is usable).
|
||||||
|
User(String, String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity {
|
||||||
|
let names_user = headers.keys().any(|k| k.as_str().starts_with("remote-"));
|
||||||
|
let proof = headers.get("x-ianitor-proof");
|
||||||
|
if !names_user && proof.is_none() {
|
||||||
|
return UiIdentity::None;
|
||||||
|
}
|
||||||
|
let ok = match (proof, &ctl.ui_proof) {
|
||||||
|
(Some(p), Some(want)) => crate::util::ct_eq(p.as_bytes(), want),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if !ok {
|
||||||
|
return UiIdentity::Forged;
|
||||||
|
}
|
||||||
|
let users: Vec<&HeaderValue> = headers.get_all("remote-user").iter().collect();
|
||||||
|
match users.as_slice() {
|
||||||
|
[one] => match one.to_str() {
|
||||||
|
Ok(u)
|
||||||
|
if !u.is_empty()
|
||||||
|
&& u.len() <= 64
|
||||||
|
&& u.bytes().all(|c| c.is_ascii_graphic() && c != b':') =>
|
||||||
|
{
|
||||||
|
let display = headers
|
||||||
|
.get("remote-name")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|n| {
|
||||||
|
!n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control)
|
||||||
|
})
|
||||||
|
.unwrap_or(u)
|
||||||
|
.to_owned();
|
||||||
|
UiIdentity::User(u.to_owned(), display)
|
||||||
|
}
|
||||||
|
_ => UiIdentity::NoUser,
|
||||||
|
},
|
||||||
|
_ => UiIdentity::NoUser,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Host check, CSRF check, token, rate limit; logs method, route template, status, time.
|
||||||
|
async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
|
||||||
|
let started = Instant::now();
|
||||||
|
let method = req.method().clone();
|
||||||
|
let route = req
|
||||||
|
.extensions()
|
||||||
|
.get::<MatchedPath>()
|
||||||
|
.map(|p| p.as_str().to_owned())
|
||||||
|
.unwrap_or_else(|| "(no route)".into());
|
||||||
|
let resp = async {
|
||||||
|
if !host_allowed(&st.ctl, req.headers()) {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"request.host",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let browser = req.headers().contains_key(header::ORIGIN)
|
||||||
|
|| req.headers().contains_key("sec-fetch-site");
|
||||||
|
let write = !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS");
|
||||||
|
let ui = req
|
||||||
|
.headers()
|
||||||
|
.get("x-ianitor-ui")
|
||||||
|
.is_some_and(|v| v.as_bytes() == b"1");
|
||||||
|
if browser && write && !ui {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"request.csrf",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// The web UI, through edge on the admin host (docs/api.md, "Sign-in"): only a request
|
||||||
|
// with the per-boot proof edge adds is identified by its Remote-User. Any other
|
||||||
|
// request that names a user is refused, so a local process cannot claim to be one.
|
||||||
|
match ui_identity(&st.ctl, req.headers()) {
|
||||||
|
UiIdentity::None => {}
|
||||||
|
UiIdentity::Forged => {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
"ui.no_proof",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
UiIdentity::NoUser => {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
"ui.no_user",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
UiIdentity::User(user, display) => {
|
||||||
|
// Cookie-based sign-in: every write carries the UI header, browser or not.
|
||||||
|
if write && !ui {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"request.csrf",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
st.limit(&format!("user:{user}"), RATE_PER_MINUTE, 60)
|
||||||
|
.map_err(|s| {
|
||||||
|
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new())
|
||||||
|
.retry(s)
|
||||||
|
})?;
|
||||||
|
req.extensions_mut().insert(Actor {
|
||||||
|
token_id: format!("user:{user}"),
|
||||||
|
name: display,
|
||||||
|
scope: crate::tokens::Scope::Full,
|
||||||
|
member: None,
|
||||||
|
session: None,
|
||||||
|
role: None,
|
||||||
|
});
|
||||||
|
return Ok(next.run(req).await);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A team session (crate::team): the cookie, when no API token is given.
|
||||||
|
if !req.headers().contains_key(header::AUTHORIZATION)
|
||||||
|
&& let Some(value) = team::session_cookie(req.headers())
|
||||||
|
{
|
||||||
|
let ctl = st.ctl.clone();
|
||||||
|
let found = tokio::task::spawn_blocking(move || ctl.team.check(&value))
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.flatten();
|
||||||
|
let Some((member, session)) = found else {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
"session.unknown",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let same_site = req
|
||||||
|
.headers()
|
||||||
|
.get("sec-fetch-site")
|
||||||
|
.is_none_or(|v| matches!(v.as_bytes(), b"same-origin" | b"none"));
|
||||||
|
if write && (!ui || !same_site) {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"request.csrf",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if member.role != crate::team::Role::Admin
|
||||||
|
&& admin_only(method.as_str(), req.uri().path())
|
||||||
|
{
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"team.admin_only",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
st.limit(&format!("member:{}", member.id), RATE_PER_MINUTE, 60)
|
||||||
|
.map_err(|s| {
|
||||||
|
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new())
|
||||||
|
.retry(s)
|
||||||
|
})?;
|
||||||
|
req.extensions_mut().insert(Actor {
|
||||||
|
token_id: format!("member:{}", member.id),
|
||||||
|
name: member.name.clone(),
|
||||||
|
scope: crate::tokens::Scope::Full,
|
||||||
|
member: Some(member.id),
|
||||||
|
session: Some(session.id),
|
||||||
|
role: Some(member.role),
|
||||||
|
});
|
||||||
|
return Ok(next.run(req).await);
|
||||||
|
}
|
||||||
|
let auth = req
|
||||||
|
.headers()
|
||||||
|
.get(header::AUTHORIZATION)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(str::to_owned);
|
||||||
|
// The token store takes a file lock: off the async threads.
|
||||||
|
let ctl = st.ctl.clone();
|
||||||
|
let checked = tokio::task::spawn_blocking(move || ctl.tokens.check(auth.as_deref()))
|
||||||
|
.await
|
||||||
|
.unwrap_or(Err(Refusal::Unknown));
|
||||||
|
let tok = checked.map_err(|r| {
|
||||||
|
let (code, params) = match r {
|
||||||
|
Refusal::Missing => ("token.missing", Params::new()),
|
||||||
|
Refusal::Unknown => ("token.unknown", Params::new()),
|
||||||
|
Refusal::Expired(t) => (
|
||||||
|
"token.expired",
|
||||||
|
messages::params([("date", ianitor_core::time::long_date(t))]),
|
||||||
|
),
|
||||||
|
Refusal::Revoked(t) => (
|
||||||
|
"token.revoked",
|
||||||
|
messages::params([("date", ianitor_core::time::long_date(t))]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
ApiError::new(StatusCode::UNAUTHORIZED, code, params)
|
||||||
|
})?;
|
||||||
|
if tok.scope == crate::tokens::Scope::Previews && !in_preview_scope(req.uri().path()) {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"token.scope",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60)
|
||||||
|
.map_err(|s| {
|
||||||
|
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
|
||||||
|
})?;
|
||||||
|
req.extensions_mut().insert(Actor {
|
||||||
|
token_id: tok.id,
|
||||||
|
name: tok.name,
|
||||||
|
scope: tok.scope,
|
||||||
|
member: None,
|
||||||
|
session: None,
|
||||||
|
role: None,
|
||||||
|
});
|
||||||
|
Ok(next.run(req).await)
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
let resp = resp.unwrap_or_else(IntoResponse::into_response);
|
||||||
|
log::info!(target: "ianitor::api", "{method} {route} {} {} ms", resp.status().as_u16(), started.elapsed().as_millis());
|
||||||
|
resp
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds `server_time` to every JSON object answer and `request_id` to error envelopes.
|
||||||
|
async fn finish(req: Request, next: Next) -> Response {
|
||||||
|
let request_id = random::<8>().map(|b| hex(&b)).unwrap_or_default();
|
||||||
|
let resp = next.run(req).await;
|
||||||
|
let json = resp
|
||||||
|
.headers()
|
||||||
|
.get(header::CONTENT_TYPE)
|
||||||
|
.is_some_and(|v| v.as_bytes().starts_with(b"application/json"));
|
||||||
|
let (mut parts, body) = resp.into_parts();
|
||||||
|
if let Ok(v) = HeaderValue::from_str(&request_id) {
|
||||||
|
parts.headers.insert("x-request-id", v);
|
||||||
|
}
|
||||||
|
if !json {
|
||||||
|
return Response::from_parts(parts, body);
|
||||||
|
}
|
||||||
|
let Ok(bytes) = axum::body::to_bytes(body, 16 << 20).await else {
|
||||||
|
return Response::from_parts(parts, AxumBody::empty());
|
||||||
|
};
|
||||||
|
let out = match serde_json::from_slice::<serde_json::Value>(&bytes) {
|
||||||
|
Ok(serde_json::Value::Object(mut m)) => {
|
||||||
|
m.insert("server_time".into(), rfc3339(now()).into());
|
||||||
|
if m.get("error").is_some_and(serde_json::Value::is_object) {
|
||||||
|
m.insert("request_id".into(), request_id.into());
|
||||||
|
}
|
||||||
|
serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec())
|
||||||
|
}
|
||||||
|
_ => bytes.to_vec(),
|
||||||
|
};
|
||||||
|
parts.headers.remove(header::CONTENT_LENGTH);
|
||||||
|
Response::from_parts(parts, AxumBody::from(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn not_found() -> ApiError {
|
||||||
|
ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn method_not_allowed() -> ApiError {
|
||||||
|
ApiError::new(
|
||||||
|
StatusCode::METHOD_NOT_ALLOWED,
|
||||||
|
"request.method",
|
||||||
|
Params::new(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fingerprint(method: &str, path: &str, raw: &[u8]) -> String {
|
||||||
|
sha256_hex(format!("{method} {path} {}", sha256_hex(raw)).as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn router(st: Arc<AppState>) -> Router {
|
||||||
|
use handlers as h;
|
||||||
|
let api = Router::new()
|
||||||
|
.route("/api/v1/overview", get(h::overview))
|
||||||
|
.route("/api/v1/hosts", get(h::list_hosts).post(h::create_host))
|
||||||
|
.route("/api/v1/hosts/validate", post(h::validate_host))
|
||||||
|
.route(
|
||||||
|
"/api/v1/hosts/{hostname}",
|
||||||
|
get(h::get_host)
|
||||||
|
.put(h::update_host)
|
||||||
|
.patch(h::patch_host)
|
||||||
|
.delete(h::delete_host),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/hosts/{hostname}/share-links",
|
||||||
|
post(h::mint_share_link),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/hosts/{hostname}/certificate/retry",
|
||||||
|
post(h::retry_certificate),
|
||||||
|
)
|
||||||
|
.route("/api/v1/applies", get(h::list_applies))
|
||||||
|
.route(
|
||||||
|
"/api/v1/applies/{id}",
|
||||||
|
get(h::get_apply).delete(h::cancel_apply),
|
||||||
|
)
|
||||||
|
.route("/api/v1/history", get(h::history))
|
||||||
|
.route("/api/v1/history/{change_id}", get(h::history_entry))
|
||||||
|
.route(
|
||||||
|
"/api/v1/history/{change_id}/restore-preview",
|
||||||
|
get(h::restore_preview),
|
||||||
|
)
|
||||||
|
.route("/api/v1/undo", get(h::get_undo).post(h::undo))
|
||||||
|
.route("/api/v1/restore", post(h::restore))
|
||||||
|
.route("/api/v1/repo/push", post(h::push_now))
|
||||||
|
.route("/api/v1/settings", get(h::settings))
|
||||||
|
.route("/api/v1/tokens", get(h::list_tokens).post(h::create_token))
|
||||||
|
.route(
|
||||||
|
"/api/v1/tokens/{id}",
|
||||||
|
delete(h::revoke_token).patch(h::rename_token),
|
||||||
|
)
|
||||||
|
.route("/api/v1/share-links", get(h::list_share_links))
|
||||||
|
.route(
|
||||||
|
"/api/v1/share-links/stop-all",
|
||||||
|
post(h::stop_all_share_links),
|
||||||
|
)
|
||||||
|
.route("/api/v1/share-links/{id}", delete(h::stop_share_link))
|
||||||
|
.route("/api/v1/certs", get(pki::get_certs))
|
||||||
|
.route("/api/v1/certs/devices", post(pki::request_device))
|
||||||
|
.route("/api/v1/certs/devices/{id}", delete(pki::revoke_device))
|
||||||
|
.route("/api/v1/certs/devices/{id}/bundle", post(pki::make_bundle))
|
||||||
|
.route("/api/v1/certs/intermediate/renewal", post(pki::renew))
|
||||||
|
.route(
|
||||||
|
"/api/v1/pki-requests/{id}",
|
||||||
|
get(pki::get_request).delete(pki::cancel_request),
|
||||||
|
)
|
||||||
|
.route("/api/v1/pki-requests/{id}/csr", get(pki::get_csr))
|
||||||
|
.route("/api/v1/pki-requests/{id}/ext", get(pki::get_ext))
|
||||||
|
.route(
|
||||||
|
"/api/v1/pki-requests/{id}/certificate",
|
||||||
|
axum::routing::put(pki::put_certificate),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/engine",
|
||||||
|
get(pki::get_engine).post(pki::switch_engine),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/previews",
|
||||||
|
get(previews::list_previews).post(previews::open_preview),
|
||||||
|
)
|
||||||
|
.route("/api/v1/previews/close", post(previews::close_preview))
|
||||||
|
.route(
|
||||||
|
"/api/v1/previews/{hostname}",
|
||||||
|
get(previews::get_preview).delete(previews::kill_preview),
|
||||||
|
)
|
||||||
|
.route("/api/v1/team", get(team::get_team))
|
||||||
|
.route("/api/v1/team/invites", post(team::invite))
|
||||||
|
.route("/api/v1/team/invites/{id}", delete(team::cancel_invite))
|
||||||
|
.route("/api/v1/team/members/{id}", delete(team::remove_member))
|
||||||
|
.route("/api/v1/team/me/root", axum::routing::put(team::set_root))
|
||||||
|
.route("/api/v1/session/end", post(team::sign_out))
|
||||||
|
.route("/api/v1/health", get(h::health))
|
||||||
|
.route("/api/v1/openapi.json", get(h::openapi))
|
||||||
|
.method_not_allowed_fallback(method_not_allowed)
|
||||||
|
.fallback(not_found)
|
||||||
|
.layer(middleware::from_fn_with_state(st.clone(), guard))
|
||||||
|
.layer(DefaultBodyLimit::max(MAX_BODY))
|
||||||
|
.with_state(st.clone());
|
||||||
|
// In front of the guard: the built UI (static files, no token: they hold no data) and
|
||||||
|
// the one-time device downloads (the link is the secret). Both still check the Host.
|
||||||
|
api.layer(middleware::from_fn_with_state(st, ui::front))
|
||||||
|
.layer(middleware::from_fn(finish))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The OpenAPI document.
|
||||||
|
pub fn openapi_json() -> String {
|
||||||
|
handlers::ApiDoc::openapi()
|
||||||
|
.to_pretty_json()
|
||||||
|
.unwrap_or_else(|_| "{}".into())
|
||||||
|
}
|
||||||
@@ -0,0 +1,839 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Certificates (docs/ui-api.md §1.7, §1.8, §3.6) and the engine switch (§1.9).
|
||||||
|
|
||||||
|
// An error answer is built once per failed request; boxing it buys nothing.
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Extension;
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::http::{HeaderValue, StatusCode, header};
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
|
use super::views::Blocked;
|
||||||
|
use super::{Actor, ApiError, AppState, Body};
|
||||||
|
use crate::engine::Control;
|
||||||
|
use crate::messages::{self, Params, message};
|
||||||
|
use crate::pki::{Device, PkiFail, Request};
|
||||||
|
use crate::pki_ctl::pki_fail;
|
||||||
|
use crate::switch::engine_name;
|
||||||
|
use crate::util::{now, rfc3339};
|
||||||
|
|
||||||
|
type Shared = State<Arc<AppState>>;
|
||||||
|
|
||||||
|
fn json<T: serde::Serialize>(status: StatusCode, v: &T) -> Response {
|
||||||
|
(status, axum::Json(v)).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plain_id(s: &str) -> bool {
|
||||||
|
!s.is_empty() && s.len() <= 64 && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn not_found(code: &str) -> ApiError {
|
||||||
|
ApiError::new(StatusCode::NOT_FOUND, code, Params::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run blocking PKI work (key unlock, file writes) off the async threads.
|
||||||
|
async fn blocking<T: Send + 'static>(
|
||||||
|
st: &Arc<AppState>,
|
||||||
|
f: impl FnOnce(&Control) -> Result<T, PkiFail> + Send + 'static,
|
||||||
|
) -> Result<T, ApiError> {
|
||||||
|
let c = st.ctl.clone();
|
||||||
|
if c.pki.is_none() {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
"pki.not_configured",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
tokio::task::spawn_blocking(move || f(&c))
|
||||||
|
.await
|
||||||
|
.map_err(|e| ApiError::internal(e.to_string()))?
|
||||||
|
.map_err(|e| ApiError::from(pki_fail(e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pki(c: &Control) -> Result<&crate::pki::Pki, PkiFail> {
|
||||||
|
c.pki.as_ref().ok_or(PkiFail::Code("pki.not_configured"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- views
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct PkiRequestView {
|
||||||
|
pub request_id: String,
|
||||||
|
/// `device` or `intermediate`.
|
||||||
|
pub kind: String,
|
||||||
|
/// `waiting`, `approved`, `denied`, `expired`, `cancelled` or `failed`.
|
||||||
|
pub state: String,
|
||||||
|
pub match_code: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub expires_at: String,
|
||||||
|
pub approved_at: Option<String>,
|
||||||
|
pub device_id: Option<String>,
|
||||||
|
pub name: Option<String>,
|
||||||
|
/// Renewals: the request to sign offline (also `GET /pki-requests/{id}/csr`).
|
||||||
|
pub csr_pem: Option<String>,
|
||||||
|
/// Renewals: SHA-256 of the request (DER, lowercase hex), what
|
||||||
|
/// `openssl req -in X.csr -outform DER | openssl dgst -sha256` prints on the offline computer.
|
||||||
|
pub csr_sha256: Option<String>,
|
||||||
|
/// Renewals, once installed: the new intermediate's expiry.
|
||||||
|
pub not_after: Option<String>,
|
||||||
|
/// What to tell the user now (`pki.waiting.manual`, `pki.renew.manual`, `pki.denied`, …).
|
||||||
|
pub message_code: String,
|
||||||
|
pub message: String,
|
||||||
|
/// The command that approves it on the server (manual approval).
|
||||||
|
pub approve_command: Option<String>,
|
||||||
|
/// Renewals: the base name of the files (`<base>.csr`, `<base>.ext`, `<base>.crt`).
|
||||||
|
pub file_base: Option<String>,
|
||||||
|
/// Why it failed, when it did.
|
||||||
|
pub problem: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_view(c: &Control, r: &Request) -> PkiRequestView {
|
||||||
|
let (message_code, message_text) = match r.state.as_str() {
|
||||||
|
"waiting" => c.waiting_message(&r.kind, &r.match_code),
|
||||||
|
"approved" if r.kind == "intermediate" => {
|
||||||
|
let date = r
|
||||||
|
.not_after
|
||||||
|
.map(|t| ianitor_core::time::long_date(t.max(0) as u64))
|
||||||
|
.unwrap_or_default();
|
||||||
|
(
|
||||||
|
"pki.renewed".to_owned(),
|
||||||
|
message("pki.renewed", &messages::params([("date", date)])),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
"approved" => (
|
||||||
|
"pki.issued".to_owned(),
|
||||||
|
message(
|
||||||
|
"pki.issued",
|
||||||
|
&messages::params([("name", r.name.clone().unwrap_or_default())]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
"denied" => (
|
||||||
|
"pki.denied".to_owned(),
|
||||||
|
message("pki.denied", &Params::new()),
|
||||||
|
),
|
||||||
|
"expired" => (
|
||||||
|
"pki.expired".to_owned(),
|
||||||
|
message("pki.expired", &Params::new()),
|
||||||
|
),
|
||||||
|
"cancelled" => (
|
||||||
|
"pki.cancelled".to_owned(),
|
||||||
|
"Cancelled. Nothing was issued.".to_owned(),
|
||||||
|
),
|
||||||
|
_ => ("internal".to_owned(), message("internal", &Params::new())),
|
||||||
|
};
|
||||||
|
let manual = c.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual");
|
||||||
|
PkiRequestView {
|
||||||
|
request_id: r.id.clone(),
|
||||||
|
kind: r.kind.clone(),
|
||||||
|
state: r.state.clone(),
|
||||||
|
match_code: r.match_code.clone(),
|
||||||
|
created_at: rfc3339(r.created_at),
|
||||||
|
expires_at: rfc3339(r.expires_at),
|
||||||
|
approved_at: r.approved_at.map(rfc3339),
|
||||||
|
device_id: r.device_id.clone(),
|
||||||
|
name: r.name.clone(),
|
||||||
|
csr_pem: r.csr_pem.clone(),
|
||||||
|
csr_sha256: r
|
||||||
|
.csr_pem
|
||||||
|
.as_deref()
|
||||||
|
.and_then(|c| ianitor_core::pki::csr_der(c).ok())
|
||||||
|
.map(|d| ianitor_core::pki::sha256_hex(&d)),
|
||||||
|
not_after: r.not_after.map(|t| rfc3339(t.max(0) as u64)),
|
||||||
|
message_code,
|
||||||
|
message: message_text,
|
||||||
|
approve_command: (r.state == "waiting" && manual).then(|| {
|
||||||
|
if r.kind == "intermediate" {
|
||||||
|
ianitor_core::pki::openssl_sign_command(&file_base(r))
|
||||||
|
} else {
|
||||||
|
format!("ianitor-control pki approve {}", r.match_code)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
file_base: (r.kind == "intermediate").then(|| file_base(r)),
|
||||||
|
problem: r.error.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `domi-intermediate-2026-11-07`, from the day the request was made.
|
||||||
|
pub fn file_base(r: &Request) -> String {
|
||||||
|
format!(
|
||||||
|
"domi-intermediate-{}",
|
||||||
|
rfc3339(r.created_at).get(..10).unwrap_or("request")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct IntermediateView {
|
||||||
|
/// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`.
|
||||||
|
pub state: String,
|
||||||
|
pub subject: Option<String>,
|
||||||
|
pub not_after: Option<String>,
|
||||||
|
pub days_left: Option<i64>,
|
||||||
|
pub renewal: Option<PkiRequestView>,
|
||||||
|
/// The banner text for `due`, `urgent`, `expired` and `missing`; `null` when `ok`.
|
||||||
|
pub banner: Option<Blocked>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn intermediate_view(c: &Control) -> Option<IntermediateView> {
|
||||||
|
let p = c.pki.as_ref()?;
|
||||||
|
let s = p.status(now());
|
||||||
|
let date = s
|
||||||
|
.not_after
|
||||||
|
.map(|t| ianitor_core::time::long_date(t.max(0) as u64))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let days = s.days_left.unwrap_or(0).to_string();
|
||||||
|
let banner = match s.state {
|
||||||
|
"due" => Some("pki.renew_due"),
|
||||||
|
"urgent" => Some("pki.renew_urgent"),
|
||||||
|
"expired" => Some("pki.intermediate_expired"),
|
||||||
|
"missing" => Some("pki.no_intermediate"),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
.map(|code| Blocked {
|
||||||
|
code: code.into(),
|
||||||
|
message: message(
|
||||||
|
code,
|
||||||
|
&messages::params([("days", days.clone()), ("date", date.clone())]),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
Some(IntermediateView {
|
||||||
|
state: s.state.into(),
|
||||||
|
subject: s.subject,
|
||||||
|
not_after: s.not_after.map(|t| rfc3339(t.max(0) as u64)),
|
||||||
|
days_left: s.days_left,
|
||||||
|
renewal: s.renewal.as_ref().map(|r| request_view(c, r)),
|
||||||
|
banner,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct RootView {
|
||||||
|
/// The root key is never on this server.
|
||||||
|
pub offline: bool,
|
||||||
|
pub subject: String,
|
||||||
|
pub not_after: String,
|
||||||
|
pub sha256: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct DeviceView {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
/// `phone`, `computer` or `app`.
|
||||||
|
pub kind: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub not_after: String,
|
||||||
|
/// `valid`, `revoked` or `expired`.
|
||||||
|
pub state: String,
|
||||||
|
pub revoked_at: Option<String>,
|
||||||
|
pub serial: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device_view(d: &Device, t: u64) -> DeviceView {
|
||||||
|
DeviceView {
|
||||||
|
id: d.id.clone(),
|
||||||
|
name: d.name.clone(),
|
||||||
|
kind: d.kind.clone(),
|
||||||
|
created_at: rfc3339(d.created_at),
|
||||||
|
not_after: rfc3339(d.not_after.max(0) as u64),
|
||||||
|
state: d.state(t).into(),
|
||||||
|
revoked_at: d.revoked_at.map(rfc3339),
|
||||||
|
serial: d.serial.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct CertsView {
|
||||||
|
pub intermediate: Option<IntermediateView>,
|
||||||
|
pub root: RootView,
|
||||||
|
pub devices: Vec<DeviceView>,
|
||||||
|
pub device_lifetime_days: u32,
|
||||||
|
/// When a device certificate issued now would end: a year, but never past the
|
||||||
|
/// intermediate's end (decision Q7). None without an intermediate.
|
||||||
|
pub device_valid_until: Option<String>,
|
||||||
|
pub server_lifetime_days: u32,
|
||||||
|
/// `manual` (on the server, until Custos can) or `custos`.
|
||||||
|
pub approval: String,
|
||||||
|
/// Open device requests.
|
||||||
|
pub requests: Vec<PkiRequestView>,
|
||||||
|
/// Set while the device list is not in force (could not be written or handed to the
|
||||||
|
/// proxy); Ianitor retries every few seconds.
|
||||||
|
pub devices_problem: Option<Blocked>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- handlers
|
||||||
|
|
||||||
|
/// The certificates screen.
|
||||||
|
#[utoipa::path(get, path = "/api/v1/certs", tag = "certs",
|
||||||
|
responses((status = 200, body = CertsView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn get_certs(State(st): Shared) -> Result<Response, ApiError> {
|
||||||
|
let view = blocking(&st, |c| {
|
||||||
|
let p = pki(c)?;
|
||||||
|
let t = now();
|
||||||
|
let root = ianitor_core::pki::inspect(p.root_pem())?;
|
||||||
|
let requests = p_requests(c, t)?;
|
||||||
|
Ok(CertsView {
|
||||||
|
intermediate: intermediate_view(c),
|
||||||
|
root: RootView {
|
||||||
|
offline: true,
|
||||||
|
subject: root.subject_cn,
|
||||||
|
not_after: rfc3339(root.not_after.max(0) as u64),
|
||||||
|
sha256: root.sha256_hex,
|
||||||
|
},
|
||||||
|
devices: p
|
||||||
|
.devices()?
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.map(|d| device_view(d, t))
|
||||||
|
.collect(),
|
||||||
|
device_lifetime_days: ianitor_core::pki::DEVICE_DAYS,
|
||||||
|
device_valid_until: p.intermediate_info().map(|i| {
|
||||||
|
let end = (t as i64 + i64::from(ianitor_core::pki::DEVICE_DAYS) * 86_400)
|
||||||
|
.min(i.not_after);
|
||||||
|
rfc3339(end.max(0) as u64)
|
||||||
|
}),
|
||||||
|
server_lifetime_days: ianitor_core::pki::SERVER_DAYS,
|
||||||
|
approval: c
|
||||||
|
.cfg
|
||||||
|
.pki
|
||||||
|
.as_ref()
|
||||||
|
.map(|p| p.approval.clone())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
requests,
|
||||||
|
devices_problem: c
|
||||||
|
.devices_problem
|
||||||
|
.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|p| p.clone())
|
||||||
|
.map(|_| Blocked {
|
||||||
|
code: "pki.devices_unwritten".into(),
|
||||||
|
message: message("pki.devices_unwritten", &Params::new()),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(json(StatusCode::OK, &view))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn p_requests(c: &Control, t: u64) -> Result<Vec<PkiRequestView>, PkiFail> {
|
||||||
|
let path = crate::pki::requests_path(&c.cfg.state_dir);
|
||||||
|
let rs: Vec<Request> = crate::util::read_json(&path)
|
||||||
|
.map_err(PkiFail::Internal)?
|
||||||
|
.unwrap_or_default();
|
||||||
|
Ok(rs
|
||||||
|
.iter()
|
||||||
|
.filter(|r| r.kind == "device" && r.state == "waiting" && r.expires_at > t)
|
||||||
|
.map(|r| request_view(c, r))
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct DeviceRequestBody {
|
||||||
|
pub name: String,
|
||||||
|
/// `phone`, `computer` or `app`.
|
||||||
|
pub kind: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ask for a device certificate; it is issued once the request is approved with its code.
|
||||||
|
#[utoipa::path(post, path = "/api/v1/certs/devices", tag = "certs", request_body = DeviceRequestBody,
|
||||||
|
responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn request_device(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
body: Body<DeviceRequestBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
st.limit(&format!("pki:{}", actor.token_id), 20, 3600)
|
||||||
|
.map_err(|s| {
|
||||||
|
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
|
||||||
|
})?;
|
||||||
|
let b = body.value;
|
||||||
|
let name_for_err = b.name.clone();
|
||||||
|
let r = blocking(&st, move |c| {
|
||||||
|
let r = pki(c)?.request_device(&b.name, &b.kind, now(), &actor.name)?;
|
||||||
|
Ok(request_view(c, &r))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|mut e| {
|
||||||
|
if e.body.code == "pki.device_name_taken" || e.body.code == "pki.device_name" {
|
||||||
|
e.body.field = Some("name".into());
|
||||||
|
e.body
|
||||||
|
.params
|
||||||
|
.insert("name".into(), name_for_err.chars().take(64).collect());
|
||||||
|
} else if e.body.code == "pki.device_kind" {
|
||||||
|
e.body.field = Some("kind".into());
|
||||||
|
}
|
||||||
|
e
|
||||||
|
})?;
|
||||||
|
log::info!(target: "ianitor::pki", "device certificate requested ({})", r.request_id);
|
||||||
|
Ok(json(StatusCode::ACCEPTED, &r))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One approval request.
|
||||||
|
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}", tag = "certs",
|
||||||
|
responses((status = 200, body = PkiRequestView), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn get_request(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
|
||||||
|
if !plain_id(&id) {
|
||||||
|
return Err(not_found("pki.request_not_found"));
|
||||||
|
}
|
||||||
|
let v = blocking(&st, move |c| {
|
||||||
|
let r = pki(c)?
|
||||||
|
.request(&id, now())?
|
||||||
|
.ok_or(PkiFail::Code("pki.request_not_found"))?;
|
||||||
|
Ok(request_view(c, &r))
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(json(StatusCode::OK, &v))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel a request that waits.
|
||||||
|
#[utoipa::path(delete, path = "/api/v1/pki-requests/{id}", tag = "certs",
|
||||||
|
responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn cancel_request(
|
||||||
|
State(st): Shared,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
if !plain_id(&id) {
|
||||||
|
return Err(not_found("pki.request_not_found"));
|
||||||
|
}
|
||||||
|
blocking(&st, move |c| {
|
||||||
|
pki(c)?
|
||||||
|
.cancel(&id)?
|
||||||
|
.map(|_| ())
|
||||||
|
.ok_or(PkiFail::Code("pki.request_not_found"))
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(StatusCode::NO_CONTENT.into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A renewal's CSR, as a file to carry to the offline machine.
|
||||||
|
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/csr", tag = "certs",
|
||||||
|
responses((status = 200, description = "PEM PKCS#10"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn get_csr(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
|
||||||
|
if !plain_id(&id) {
|
||||||
|
return Err(not_found("pki.request_not_found"));
|
||||||
|
}
|
||||||
|
let csr = blocking(&st, move |c| {
|
||||||
|
pki(c)?
|
||||||
|
.request(&id, now())?
|
||||||
|
.and_then(|r| r.csr_pem.clone().map(|c| (c, file_base(&r))))
|
||||||
|
.ok_or(PkiFail::Code("pki.request_not_found"))
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let (csr, base) = csr;
|
||||||
|
let mut r = csr.into_response();
|
||||||
|
r.headers_mut().insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
HeaderValue::from_static("application/pkcs10"),
|
||||||
|
);
|
||||||
|
if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{base}.csr\"")) {
|
||||||
|
r.headers_mut().insert(header::CONTENT_DISPOSITION, v);
|
||||||
|
}
|
||||||
|
Ok(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct CertificateBody {
|
||||||
|
/// The intermediate certificate signed by the Domi root (PEM).
|
||||||
|
pub certificate_pem: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Install the signed intermediate for an open renewal.
|
||||||
|
#[utoipa::path(put, path = "/api/v1/pki-requests/{id}/certificate", tag = "certs", request_body = CertificateBody,
|
||||||
|
responses((status = 200, body = PkiRequestView), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn put_certificate(
|
||||||
|
State(st): Shared,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
body: Body<CertificateBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
if !plain_id(&id) {
|
||||||
|
return Err(not_found("pki.request_not_found"));
|
||||||
|
}
|
||||||
|
let pem = body.value.certificate_pem;
|
||||||
|
if pem.len() > 16 * 1024 {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"pki.bad_certificate",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let v = blocking(&st, move |c| {
|
||||||
|
let r = pki(c)?.install_intermediate(&id, &pem, now())?;
|
||||||
|
Ok(request_view(c, &r))
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let c = st.ctl.clone();
|
||||||
|
tokio::spawn(async move { c.refresh_certificates(true).await });
|
||||||
|
Ok(json(StatusCode::OK, &v))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the renewal of the intermediate (or set up the first one).
|
||||||
|
#[utoipa::path(post, path = "/api/v1/certs/intermediate/renewal", tag = "certs",
|
||||||
|
responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn renew(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let v = blocking(&st, move |c| {
|
||||||
|
let r = pki(c)?.request_renewal(now(), &actor.name)?;
|
||||||
|
Ok(request_view(c, &r))
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(json(StatusCode::ACCEPTED, &v))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Revoke a device: it is off the allow list at once.
|
||||||
|
#[utoipa::path(delete, path = "/api/v1/certs/devices/{id}", tag = "certs",
|
||||||
|
responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn revoke_device(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
if !plain_id(&id) {
|
||||||
|
return Err(not_found("pki.device_not_found"));
|
||||||
|
}
|
||||||
|
let d = blocking(&st, move |c| {
|
||||||
|
pki(c)?
|
||||||
|
.revoke(&id, now())?
|
||||||
|
.ok_or(PkiFail::Code("pki.device_not_found"))
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
log::info!(target: "ianitor::pki", "device {} revoked by {}", d.id, actor.token_id);
|
||||||
|
// The revocation is recorded; it is in force only once the engines have the new list.
|
||||||
|
if let Err(e) = st.ctl.devices_changed().await {
|
||||||
|
let mut err = ApiError::new(
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE,
|
||||||
|
"pki.devices_unwritten",
|
||||||
|
Params::new(),
|
||||||
|
);
|
||||||
|
err.body.detail = Some(e);
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
Ok(StatusCode::NO_CONTENT.into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct BundleBody {
|
||||||
|
/// `p12` (a file to download) or `qr` (the same link as a QR code).
|
||||||
|
#[serde(default = "p12")]
|
||||||
|
pub format: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn p12() -> String {
|
||||||
|
"p12".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct BundleView {
|
||||||
|
/// Works once, for 10 minutes.
|
||||||
|
pub download_url: String,
|
||||||
|
/// Asked for when the file is installed. Shown once.
|
||||||
|
pub one_time_password: String,
|
||||||
|
pub expires_at: String,
|
||||||
|
pub filename: String,
|
||||||
|
/// `format = "qr"`: the link as an SVG QR code.
|
||||||
|
pub qr_svg: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A one-time install file for a device (G15): PKCS#12, behind a link that works once.
|
||||||
|
#[utoipa::path(post, path = "/api/v1/certs/devices/{id}/bundle", tag = "certs", request_body = BundleBody,
|
||||||
|
responses((status = 200, body = BundleView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn make_bundle(
|
||||||
|
State(st): Shared,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
body: Body<BundleBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
if !plain_id(&id) {
|
||||||
|
return Err(not_found("pki.device_not_found"));
|
||||||
|
}
|
||||||
|
let format = body.value.format;
|
||||||
|
if format != "p12" && format != "qr" {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
"request.body",
|
||||||
|
messages::params([("problem", "format must be \"p12\" or \"qr\".".into())]),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let (token, password, expires) =
|
||||||
|
blocking(&st, move |c| pki(c)?.make_bundle(&id, now())).await?;
|
||||||
|
let url = bundle_url(&st, &token).await;
|
||||||
|
let qr_svg = if format == "qr" {
|
||||||
|
Some(crate::pki::qr_svg(&url).map_err(|e| ApiError::from(pki_fail(e)))?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&BundleView {
|
||||||
|
download_url: url,
|
||||||
|
one_time_password: password,
|
||||||
|
expires_at: rfc3339(expires),
|
||||||
|
filename: "domi-device.p12".into(),
|
||||||
|
qr_svg,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a device downloads its file: through edge on the admin host when there is one
|
||||||
|
/// (as a share link when that host has share links on, so a device without a sign-in can
|
||||||
|
/// reach it; the link covers only this one-time path), else control's own address.
|
||||||
|
async fn bundle_url(st: &AppState, token: &str) -> String {
|
||||||
|
let c = &st.ctl;
|
||||||
|
let path = format!("/api/v1/device-bundles/{token}");
|
||||||
|
let Some(ui) = c.cfg.ui.as_ref().and_then(|u| u.hostname.clone()) else {
|
||||||
|
return format!("http://{}{path}", c.cfg.listen);
|
||||||
|
};
|
||||||
|
let port = c.cfg.compile.https_listen.port();
|
||||||
|
let authority = if port == 443 {
|
||||||
|
ui.clone()
|
||||||
|
} else {
|
||||||
|
format!("{ui}:{port}")
|
||||||
|
};
|
||||||
|
let shares_on = c
|
||||||
|
.head_model()
|
||||||
|
.ok()
|
||||||
|
.and_then(|(_, _, m)| {
|
||||||
|
m.hosts()
|
||||||
|
.iter()
|
||||||
|
.find(|h| h.hostname.as_str() == ui)
|
||||||
|
.map(|h| h.share_links)
|
||||||
|
})
|
||||||
|
.unwrap_or(false);
|
||||||
|
if shares_on
|
||||||
|
&& c.engine_running() != "caddy"
|
||||||
|
&& let Some(key) = &c.share_key
|
||||||
|
&& let Ok(m) = c.shares.mint(
|
||||||
|
key,
|
||||||
|
&ui,
|
||||||
|
&path,
|
||||||
|
crate::shares::MIN_EXPIRY,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
"device install",
|
||||||
|
)
|
||||||
|
{
|
||||||
|
return format!(
|
||||||
|
"https://{authority}{}?{}={}",
|
||||||
|
m.record.path_prefix,
|
||||||
|
ianitor_core::share::QUERY_PARAM,
|
||||||
|
m.token
|
||||||
|
);
|
||||||
|
}
|
||||||
|
format!("https://{authority}{path}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET` on a one-time link: a small page with a Download button that posts back. Link
|
||||||
|
/// previews and prefetchers only ever GET, so they cannot use up the download.
|
||||||
|
pub async fn bundle_page(st: Arc<AppState>, token: String) -> Response {
|
||||||
|
let valid = token.len() == 64 && token.bytes().all(|c| c.is_ascii_hexdigit());
|
||||||
|
let name = if valid {
|
||||||
|
let ctl = st.ctl.clone();
|
||||||
|
tokio::task::spawn_blocking(move || {
|
||||||
|
ctl.pki.as_ref().and_then(|p| p.peek_bundle(&token, now()))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let (status, body) = match name {
|
||||||
|
Some(n) => (
|
||||||
|
StatusCode::OK,
|
||||||
|
format!(
|
||||||
|
"<h1>Install the certificate for {}</h1>\
|
||||||
|
<p>This link works once. After the download, open the file and enter the \
|
||||||
|
one-time password shown in Ianitor.</p>\
|
||||||
|
<form method=\"post\"><button type=\"submit\">Download domi-device.p12</button></form>",
|
||||||
|
html_escape(&n)
|
||||||
|
),
|
||||||
|
),
|
||||||
|
None => (
|
||||||
|
StatusCode::GONE,
|
||||||
|
format!(
|
||||||
|
"<h1>This link has been used</h1><p>{}</p>",
|
||||||
|
html_escape(&message("pki.bundle_used", &Params::new()))
|
||||||
|
),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
let page = format!(
|
||||||
|
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
|
||||||
|
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
|
||||||
|
<meta name=\"robots\" content=\"noindex\"><title>Ianitor: device certificate</title>\
|
||||||
|
<style>body{{margin:0;padding:24px 16px;background:#0f1115;color:#e6e8ee;\
|
||||||
|
font:16px/1.5 system-ui,sans-serif}}main{{max-width:32rem;margin:0 auto}}\
|
||||||
|
h1{{font-size:1.25rem}}button{{font:inherit;padding:10px 16px;border-radius:8px;\
|
||||||
|
border:0;background:#7aa2ff;color:#0f1115;cursor:pointer}}\
|
||||||
|
button:focus-visible{{outline:2px solid #e6e8ee;outline-offset:2px}}</style>\
|
||||||
|
</head><body><main>{body}</main></body></html>"
|
||||||
|
);
|
||||||
|
let mut r = (status, page).into_response();
|
||||||
|
let h = r.headers_mut();
|
||||||
|
h.insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
HeaderValue::from_static("text/html; charset=utf-8"),
|
||||||
|
);
|
||||||
|
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||||
|
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
|
||||||
|
h.insert(
|
||||||
|
"content-security-policy",
|
||||||
|
HeaderValue::from_static(
|
||||||
|
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
fn html_escape(s: &str) -> String {
|
||||||
|
let mut o = String::with_capacity(s.len());
|
||||||
|
for c in s.chars() {
|
||||||
|
match c {
|
||||||
|
'&' => o.push_str("&"),
|
||||||
|
'<' => o.push_str("<"),
|
||||||
|
'>' => o.push_str(">"),
|
||||||
|
'"' => o.push_str("""),
|
||||||
|
'\'' => o.push_str("'"),
|
||||||
|
c => o.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one-time download itself (`POST`, from the link's page). The link is the secret: no
|
||||||
|
/// token or sign-in is needed, and it works once.
|
||||||
|
#[utoipa::path(post, path = "/api/v1/device-bundles/{token}", tag = "certs",
|
||||||
|
responses((status = 200, description = "application/x-pkcs12"), (status = 410, body = super::views::ErrorEnvelope)))]
|
||||||
|
pub async fn download_bundle(
|
||||||
|
State(st): Shared,
|
||||||
|
Path(token): Path<String>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
if token.len() != 64 || !token.bytes().all(|c| c.is_ascii_hexdigit()) {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::GONE,
|
||||||
|
"pki.bundle_used",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let (bytes, _name) = blocking(&st, move |c| pki(c)?.take_bundle(&token, now())).await?;
|
||||||
|
log::info!(target: "ianitor::pki", "a device install file was downloaded");
|
||||||
|
let mut r = bytes.into_response();
|
||||||
|
let h = r.headers_mut();
|
||||||
|
h.insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
HeaderValue::from_static("application/x-pkcs12"),
|
||||||
|
);
|
||||||
|
h.insert(
|
||||||
|
header::CONTENT_DISPOSITION,
|
||||||
|
HeaderValue::from_static("attachment; filename=\"domi-device.p12\""),
|
||||||
|
);
|
||||||
|
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||||
|
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
|
||||||
|
Ok(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- engine
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct EngineSwitchView {
|
||||||
|
/// `pingora` or `caddy`.
|
||||||
|
pub running: String,
|
||||||
|
/// `running`, `switching` or `stopped`.
|
||||||
|
pub state: String,
|
||||||
|
pub target: Option<String>,
|
||||||
|
pub since: String,
|
||||||
|
/// Whether this server lets control switch (an `[engine]` section and its units).
|
||||||
|
pub switchable: bool,
|
||||||
|
/// Why the last switch did not happen.
|
||||||
|
pub last_error: Option<crate::records::Reason>,
|
||||||
|
/// What changes while Caddy serves.
|
||||||
|
pub notes: Vec<Blocked>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn engine_view(c: &Control) -> EngineSwitchView {
|
||||||
|
let e = c.engine_state();
|
||||||
|
let notes = if e.running == "caddy" {
|
||||||
|
["share.engine_caddy"]
|
||||||
|
.iter()
|
||||||
|
.map(|code| Blocked {
|
||||||
|
code: (*code).into(),
|
||||||
|
message: message(code, &Params::new()),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
EngineSwitchView {
|
||||||
|
running: e.running,
|
||||||
|
state: e.state,
|
||||||
|
target: e.target,
|
||||||
|
since: rfc3339(e.since),
|
||||||
|
switchable: c.engine_cfg().is_some() && c.units.is_some(),
|
||||||
|
last_error: e.last_error,
|
||||||
|
notes,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which engine serves.
|
||||||
|
#[utoipa::path(get, path = "/api/v1/engine", tag = "engine",
|
||||||
|
responses((status = 200, body = EngineSwitchView)), security(("bearer" = [])))]
|
||||||
|
pub async fn get_engine(State(st): Shared) -> Response {
|
||||||
|
json(StatusCode::OK, &engine_view(&st.ctl))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EngineBody {
|
||||||
|
/// `pingora` or `caddy`.
|
||||||
|
pub target: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Switch the engine. Answers at once; poll `GET /engine` until `state` is `running`.
|
||||||
|
#[utoipa::path(post, path = "/api/v1/engine", tag = "engine", request_body = EngineBody,
|
||||||
|
responses((status = 202, body = EngineSwitchView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn switch_engine(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
body: Body<EngineBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let target = body.value.target;
|
||||||
|
st.ctl.request_switch(&target).map_err(ApiError::from)?;
|
||||||
|
log::info!(target: "ianitor::engine", "switch to {} asked by {}", engine_name(&target), actor.token_id);
|
||||||
|
Ok(json(StatusCode::ACCEPTED, &engine_view(&st.ctl)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The openssl extensions file for signing a renewal by hand (the same profile Custos will
|
||||||
|
/// use; docs/pki.md).
|
||||||
|
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/ext", tag = "certs",
|
||||||
|
responses((status = 200, description = "openssl -extfile"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn get_ext(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
|
||||||
|
if !plain_id(&id) {
|
||||||
|
return Err(not_found("pki.request_not_found"));
|
||||||
|
}
|
||||||
|
let r = blocking(&st, move |c| {
|
||||||
|
pki(c)?
|
||||||
|
.request(&id, now())?
|
||||||
|
.filter(|r| r.kind == "intermediate")
|
||||||
|
.ok_or(PkiFail::Code("pki.request_not_found"))
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let mut resp = ianitor_core::pki::INTERMEDIATE_OPENSSL_EXT.into_response();
|
||||||
|
resp.headers_mut().insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
HeaderValue::from_static("text/plain; charset=utf-8"),
|
||||||
|
);
|
||||||
|
if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{}.ext\"", file_base(&r)))
|
||||||
|
{
|
||||||
|
resp.headers_mut().insert(header::CONTENT_DISPOSITION, v);
|
||||||
|
}
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! `/api/v1/previews`: Fabrica's branch previews (T4). The only routes a `previews` token may
|
||||||
|
//! call (the guard in `api` refuses every other route for it).
|
||||||
|
|
||||||
|
// An error answer is built once per failed request; boxing it buys nothing.
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Extension;
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
|
use super::views::{ApplyView, apply_view};
|
||||||
|
use super::{Actor, ApiError, AppState, Body};
|
||||||
|
use crate::messages::Params;
|
||||||
|
use crate::util::rfc3339;
|
||||||
|
|
||||||
|
type Shared = State<Arc<AppState>>;
|
||||||
|
|
||||||
|
fn json<T: Serialize>(status: StatusCode, v: &T) -> Response {
|
||||||
|
(status, axum::Json(v)).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PreviewOpen {
|
||||||
|
/// Fabrica's project, e.g. `mnovak/Arca` or `github:acme/web`.
|
||||||
|
pub project: String,
|
||||||
|
/// The git branch, as the git host names it.
|
||||||
|
pub branch: String,
|
||||||
|
/// Where the branch's build runs, e.g. `http://10.0.0.5:8080` (must be in `[previews] upstreams`).
|
||||||
|
pub upstream: String,
|
||||||
|
/// Seconds until the preview closes by itself (default from `[previews]`).
|
||||||
|
pub ttl: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PreviewClose {
|
||||||
|
pub project: String,
|
||||||
|
pub branch: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewView {
|
||||||
|
pub hostname: String,
|
||||||
|
/// `https://<hostname>/`
|
||||||
|
pub url: String,
|
||||||
|
pub project: String,
|
||||||
|
pub branch: String,
|
||||||
|
pub upstream: String,
|
||||||
|
pub expires_at: String,
|
||||||
|
/// `applying`, `live` or `failed`.
|
||||||
|
pub state: String,
|
||||||
|
/// Why it failed, in plain English.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub problem: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewOpened {
|
||||||
|
pub preview: PreviewView,
|
||||||
|
pub apply: ApplyView,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewOne {
|
||||||
|
pub preview: PreviewView,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewList {
|
||||||
|
pub items: Vec<PreviewView>,
|
||||||
|
/// The domain previews live under; absent when previews are off.
|
||||||
|
pub domain: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct PreviewClosed {
|
||||||
|
pub apply: ApplyView,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view(st: &AppState, p: &crate::previews::Listed) -> PreviewView {
|
||||||
|
let (state, problem) = st
|
||||||
|
.ctl
|
||||||
|
.preview_state(&p.hostname)
|
||||||
|
.unwrap_or(("live".into(), None));
|
||||||
|
PreviewView {
|
||||||
|
url: format!("https://{}/", p.hostname),
|
||||||
|
hostname: p.hostname.clone(),
|
||||||
|
project: p.project.clone(),
|
||||||
|
branch: p.branch.clone(),
|
||||||
|
upstream: p.upstream.clone(),
|
||||||
|
expires_at: rfc3339(p.expires_at),
|
||||||
|
state,
|
||||||
|
problem,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every open preview.
|
||||||
|
#[utoipa::path(get, path = "/api/v1/previews", tag = "previews",
|
||||||
|
responses((status = 200, body = PreviewList)), security(("bearer" = [])))]
|
||||||
|
pub async fn list_previews(State(st): Shared) -> Result<Response, ApiError> {
|
||||||
|
let domain = st.ctl.cfg.previews.as_ref().map(|p| p.domain.clone());
|
||||||
|
let items = if domain.is_some() {
|
||||||
|
st.ctl.previews()?.iter().map(|p| view(&st, p)).collect()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
Ok(json(StatusCode::OK, &PreviewList { items, domain }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a branch's preview, or move it to a new upstream and lifetime. The host is
|
||||||
|
/// `<branch>--<project>.<preview domain>`; it is live when its apply is kept.
|
||||||
|
#[utoipa::path(post, path = "/api/v1/previews", tag = "previews", request_body = PreviewOpen,
|
||||||
|
responses((status = 202, body = PreviewOpened), (status = 403, body = super::views::ErrorEnvelope),
|
||||||
|
(status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)),
|
||||||
|
security(("bearer" = [])))]
|
||||||
|
pub async fn open_preview(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
body: Body<PreviewOpen>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let b = body.value;
|
||||||
|
let (hostname, expires_at, rec) =
|
||||||
|
st.ctl
|
||||||
|
.open_preview(&b.project, &b.branch, &b.upstream, b.ttl, &actor.name)?;
|
||||||
|
let preview = PreviewView {
|
||||||
|
url: format!("https://{hostname}/"),
|
||||||
|
hostname,
|
||||||
|
project: b.project,
|
||||||
|
branch: b.branch,
|
||||||
|
upstream: b.upstream,
|
||||||
|
expires_at: rfc3339(expires_at),
|
||||||
|
state: "applying".into(),
|
||||||
|
problem: None,
|
||||||
|
};
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::ACCEPTED,
|
||||||
|
&PreviewOpened {
|
||||||
|
preview,
|
||||||
|
apply: apply_view(&st.ctl, &rec),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One preview and where it stands (Fabrica polls this after opening one).
|
||||||
|
#[utoipa::path(get, path = "/api/v1/previews/{hostname}", tag = "previews",
|
||||||
|
params(("hostname" = String, Path)),
|
||||||
|
responses((status = 200, body = PreviewOne), (status = 404, body = super::views::ErrorEnvelope)),
|
||||||
|
security(("bearer" = [])))]
|
||||||
|
pub async fn get_preview(
|
||||||
|
State(st): Shared,
|
||||||
|
Path(hostname): Path<String>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
st.ctl.previews_cfg()?;
|
||||||
|
let not_found = || ApiError::new(StatusCode::NOT_FOUND, "preview.not_found", Params::new());
|
||||||
|
if let Some(p) = st
|
||||||
|
.ctl
|
||||||
|
.previews()?
|
||||||
|
.into_iter()
|
||||||
|
.find(|p| p.hostname == hostname)
|
||||||
|
{
|
||||||
|
return Ok(json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&PreviewOne {
|
||||||
|
preview: view(&st, &p),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Not at the head: a preview whose apply is still running or failed.
|
||||||
|
let (state, problem) = st.ctl.preview_state(&hostname).ok_or_else(not_found)?;
|
||||||
|
let rec = st
|
||||||
|
.ctl
|
||||||
|
.records()
|
||||||
|
.into_iter()
|
||||||
|
.rev()
|
||||||
|
.find(|r| r.hosts.contains(&hostname))
|
||||||
|
.ok_or_else(not_found)?;
|
||||||
|
let pv = rec
|
||||||
|
.attempted_host
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|h| h.preview.clone())
|
||||||
|
.ok_or_else(not_found)?;
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&PreviewOne {
|
||||||
|
preview: PreviewView {
|
||||||
|
url: format!("https://{hostname}/"),
|
||||||
|
hostname,
|
||||||
|
project: pv.project,
|
||||||
|
branch: pv.branch,
|
||||||
|
upstream: rec
|
||||||
|
.attempted_host
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|h| h.upstreams.first().cloned())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
expires_at: rfc3339(u64::try_from(pv.expires_at).unwrap_or(0)),
|
||||||
|
state,
|
||||||
|
problem,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a preview now (the previews screen's Close, or Fabrica after a merge).
|
||||||
|
#[utoipa::path(delete, path = "/api/v1/previews/{hostname}", tag = "previews",
|
||||||
|
params(("hostname" = String, Path)),
|
||||||
|
responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)),
|
||||||
|
security(("bearer" = [])))]
|
||||||
|
pub async fn kill_preview(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
Path(hostname): Path<String>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?;
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::ACCEPTED,
|
||||||
|
&PreviewClosed {
|
||||||
|
apply: apply_view(&st.ctl, &rec),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a branch's preview by project and branch (Fabrica, when the branch is merged or
|
||||||
|
/// deleted).
|
||||||
|
#[utoipa::path(post, path = "/api/v1/previews/close", tag = "previews", request_body = PreviewClose,
|
||||||
|
responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)),
|
||||||
|
security(("bearer" = [])))]
|
||||||
|
pub async fn close_preview(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
body: Body<PreviewClose>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let b = body.value;
|
||||||
|
let p = st.ctl.previews_cfg()?;
|
||||||
|
let hostname = ianitor_core::preview::hostname(&b.project, &b.branch, &p.domain)
|
||||||
|
.map_err(crate::previews::name_fail)?;
|
||||||
|
let mine = st
|
||||||
|
.ctl
|
||||||
|
.previews()?
|
||||||
|
.into_iter()
|
||||||
|
.any(|x| x.hostname == hostname && x.project == b.project && x.branch == b.branch);
|
||||||
|
if !mine {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
"preview.not_found",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?;
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::ACCEPTED,
|
||||||
|
&PreviewClosed {
|
||||||
|
apply: apply_view(&st.ctl, &rec),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
@@ -0,0 +1,351 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Team sign-in and the team list (`crate::team`). `POST /api/v1/session` is the one call
|
||||||
|
//! without a token or session: it redeems a setup or invite link. Everything else here goes
|
||||||
|
//! through the guard; inviting and removing people needs the admin role.
|
||||||
|
|
||||||
|
// An error answer is built once per failed request; boxing it buys nothing.
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Extension;
|
||||||
|
use axum::extract::{Path, Request, State};
|
||||||
|
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
|
use super::{Actor, ApiError, AppState, Body};
|
||||||
|
use crate::messages::Params;
|
||||||
|
use crate::team::{COOKIE, Member, Role, SESSION_SECS, match_code};
|
||||||
|
use crate::util::rfc3339;
|
||||||
|
|
||||||
|
type Shared = State<Arc<AppState>>;
|
||||||
|
|
||||||
|
fn json<T: Serialize>(status: StatusCode, v: &T) -> Response {
|
||||||
|
(status, axum::Json(v)).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refused(code: &'static str) -> ApiError {
|
||||||
|
let status = match code {
|
||||||
|
"internal" => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"session.code" => StatusCode::UNAUTHORIZED,
|
||||||
|
"team.not_found" => StatusCode::NOT_FOUND,
|
||||||
|
"team.last_admin" | "team.full" => StatusCode::CONFLICT,
|
||||||
|
_ => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
};
|
||||||
|
ApiError::new(status, code, Params::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session cookie's value from a request, if any.
|
||||||
|
pub fn session_cookie(headers: &HeaderMap) -> Option<String> {
|
||||||
|
headers
|
||||||
|
.get_all(header::COOKIE)
|
||||||
|
.iter()
|
||||||
|
.filter_map(|v| v.to_str().ok())
|
||||||
|
.flat_map(|v| v.split(';'))
|
||||||
|
.filter_map(|kv| kv.trim().split_once('='))
|
||||||
|
.find(|(k, _)| *k == COOKIE)
|
||||||
|
.map(|(_, v)| v.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct SignIn {
|
||||||
|
/// The code from a setup or invite link (`#signin=<code>`).
|
||||||
|
pub code: String,
|
||||||
|
/// Your name (setup links only; an invite already names you).
|
||||||
|
pub name: Option<String>,
|
||||||
|
/// What to call this browser in the sessions list.
|
||||||
|
pub device: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct MemberView {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
/// `admin` or `member`.
|
||||||
|
pub role: String,
|
||||||
|
pub added_at: String,
|
||||||
|
/// The member's Tessera root and its match code, when they recorded it.
|
||||||
|
pub tessera_root: Option<String>,
|
||||||
|
pub match_code: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&Member> for MemberView {
|
||||||
|
fn from(m: &Member) -> Self {
|
||||||
|
MemberView {
|
||||||
|
id: m.id.clone(),
|
||||||
|
name: m.name.clone(),
|
||||||
|
role: m.role.as_str().into(),
|
||||||
|
added_at: rfc3339(m.added_at),
|
||||||
|
tessera_root: m.tessera_root.clone(),
|
||||||
|
match_code: m.tessera_root.as_deref().and_then(match_code),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct SignedIn {
|
||||||
|
pub member: MemberView,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Redeem a setup or invite link: sets the session cookie. No token needed (this is the
|
||||||
|
/// door). At most 20 tries a minute for the whole server.
|
||||||
|
pub async fn sign_in(st: Arc<AppState>, req: Request) -> Response {
|
||||||
|
async {
|
||||||
|
if st.limit("signin", 20, 60).is_err() {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::TOO_MANY_REQUESTS,
|
||||||
|
"rate.limited",
|
||||||
|
Params::new(),
|
||||||
|
)
|
||||||
|
.retry(60));
|
||||||
|
}
|
||||||
|
// Only the UI's own page signs in (the custom header needs a CORS preflight that
|
||||||
|
// control never answers), and never a cross-site page.
|
||||||
|
let h = req.headers();
|
||||||
|
let ui = h.get("x-ianitor-ui").is_some_and(|v| v.as_bytes() == b"1");
|
||||||
|
let site_ok = h
|
||||||
|
.get("sec-fetch-site")
|
||||||
|
.is_none_or(|v| matches!(v.as_bytes(), b"same-origin" | b"none"));
|
||||||
|
if !ui || !site_ok {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"request.csrf",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let body = <Body<SignIn> as axum::extract::FromRequest<()>>::from_request(req, &()).await?;
|
||||||
|
let b = body.value;
|
||||||
|
let team = st.ctl.team.clone();
|
||||||
|
let device = b.device.unwrap_or_else(|| "Browser".into());
|
||||||
|
let (member, value) =
|
||||||
|
tokio::task::spawn_blocking(move || team.redeem(&b.code, b.name.as_deref(), &device))
|
||||||
|
.await
|
||||||
|
.map_err(|_| ApiError::internal("sign-in"))?
|
||||||
|
.map_err(|r| refused(r.0))?;
|
||||||
|
log::info!(target: "ianitor::team", "{} ({}) signed in", member.name, member.role.as_str());
|
||||||
|
let mut resp = json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&SignedIn {
|
||||||
|
member: MemberView::from(&member),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let cookie = format!(
|
||||||
|
"{COOKIE}={value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age={SESSION_SECS}"
|
||||||
|
);
|
||||||
|
if let Ok(v) = HeaderValue::from_str(&cookie) {
|
||||||
|
resp.headers_mut().insert(header::SET_COOKIE, v);
|
||||||
|
}
|
||||||
|
resp.headers_mut()
|
||||||
|
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(IntoResponse::into_response)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sign this browser out.
|
||||||
|
#[utoipa::path(post, path = "/api/v1/session/end", tag = "team",
|
||||||
|
responses((status = 200, body = super::views::Done)), security(("bearer" = [])))]
|
||||||
|
pub async fn sign_out(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
if let Some(id) = &actor.session {
|
||||||
|
st.ctl.team.end_session(id).map_err(ApiError::internal)?;
|
||||||
|
}
|
||||||
|
let mut resp = json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&super::views::Done {
|
||||||
|
message: "Done.".into(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if let Ok(v) = HeaderValue::from_str(&format!(
|
||||||
|
"{COOKIE}=; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=0"
|
||||||
|
)) {
|
||||||
|
resp.headers_mut().insert(header::SET_COOKIE, v);
|
||||||
|
}
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct InviteView {
|
||||||
|
pub id: String,
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub role: String,
|
||||||
|
pub expires_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct TeamView {
|
||||||
|
/// Who is asking; absent for an API token.
|
||||||
|
pub me: Option<MemberView>,
|
||||||
|
pub members: Vec<MemberView>,
|
||||||
|
pub invites: Vec<InviteView>,
|
||||||
|
/// Whether Authelia signs people in on this server instead.
|
||||||
|
pub authelia: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The team: members, open invites, and who you are.
|
||||||
|
#[utoipa::path(get, path = "/api/v1/team", tag = "team",
|
||||||
|
responses((status = 200, body = TeamView)), security(("bearer" = [])))]
|
||||||
|
pub async fn get_team(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let members = st.ctl.team.members().map_err(ApiError::internal)?;
|
||||||
|
let invites = st
|
||||||
|
.ctl
|
||||||
|
.team
|
||||||
|
.codes()
|
||||||
|
.map_err(ApiError::internal)?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|c| c.kind == "invite")
|
||||||
|
.map(|c| InviteView {
|
||||||
|
id: c.id,
|
||||||
|
name: c.name,
|
||||||
|
role: c.role.as_str().into(),
|
||||||
|
expires_at: rfc3339(c.expires_at),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let me = actor
|
||||||
|
.member
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|id| members.iter().find(|m| &m.id == id))
|
||||||
|
.map(MemberView::from);
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&TeamView {
|
||||||
|
me,
|
||||||
|
members: members.iter().map(MemberView::from).collect(),
|
||||||
|
invites,
|
||||||
|
authelia: st.ctl.ui_proof.is_some(),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct InviteBody {
|
||||||
|
pub name: String,
|
||||||
|
/// `admin` or `member` (default).
|
||||||
|
pub role: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct InviteMade {
|
||||||
|
pub invite: InviteView,
|
||||||
|
/// Send this to the person: `<the UI's address>/#signin=<code>`. Shown once.
|
||||||
|
pub link_fragment: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invite someone (admin). The link is shown once.
|
||||||
|
#[utoipa::path(post, path = "/api/v1/team/invites", tag = "team", request_body = InviteBody,
|
||||||
|
responses((status = 201, body = InviteMade), (status = 403, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn invite(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
body: Body<InviteBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let role = match body.value.role.as_deref() {
|
||||||
|
None => Role::Member,
|
||||||
|
Some(r) => Role::parse(r).ok_or_else(|| refused("team.role"))?,
|
||||||
|
};
|
||||||
|
let (code, value) = st
|
||||||
|
.ctl
|
||||||
|
.team
|
||||||
|
.invite(&body.value.name, role, &actor.name)
|
||||||
|
.map_err(|r| refused(r.0))?;
|
||||||
|
log::info!(target: "ianitor::team", "{} invited {} as {}", actor.name, code.name.clone().unwrap_or_default(), role.as_str());
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::CREATED,
|
||||||
|
&InviteMade {
|
||||||
|
invite: InviteView {
|
||||||
|
id: code.id,
|
||||||
|
name: code.name,
|
||||||
|
role: role.as_str().into(),
|
||||||
|
expires_at: rfc3339(code.expires_at),
|
||||||
|
},
|
||||||
|
link_fragment: format!("#signin={value}"),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel an invite that was not used (admin).
|
||||||
|
#[utoipa::path(delete, path = "/api/v1/team/invites/{id}", tag = "team", params(("id" = String, Path)),
|
||||||
|
responses((status = 200, body = super::views::Done)), security(("bearer" = [])))]
|
||||||
|
pub async fn cancel_invite(
|
||||||
|
State(st): Shared,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
if !st.ctl.team.cancel_invite(&id).map_err(ApiError::internal)? {
|
||||||
|
return Err(refused("team.not_found"));
|
||||||
|
}
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&super::views::Done {
|
||||||
|
message: "Done.".into(),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a member and sign them out everywhere (admin). The last admin stays.
|
||||||
|
#[utoipa::path(delete, path = "/api/v1/team/members/{id}", tag = "team", params(("id" = String, Path)),
|
||||||
|
responses((status = 200, body = super::views::Done), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
||||||
|
pub async fn remove_member(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
match st.ctl.team.remove(&id).map_err(|r| refused(r.0))? {
|
||||||
|
Some(m) => {
|
||||||
|
log::info!(target: "ianitor::team", "{} removed {}", actor.name, m.name);
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&super::views::Done {
|
||||||
|
message: "Done.".into(),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
None => Err(refused("team.not_found")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct RootBody {
|
||||||
|
/// Your Tessera root (base64url, as Custos shows it under Domi identity), or null.
|
||||||
|
pub tessera_root: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record your own Tessera root, so the team list shows its match code.
|
||||||
|
#[utoipa::path(put, path = "/api/v1/team/me/root", tag = "team", request_body = RootBody,
|
||||||
|
responses((status = 200, body = super::views::Done)), security(("bearer" = [])))]
|
||||||
|
pub async fn set_root(
|
||||||
|
State(st): Shared,
|
||||||
|
Extension(actor): Extension<Actor>,
|
||||||
|
body: Body<RootBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let Some(me) = &actor.member else {
|
||||||
|
return Err(ApiError::new(
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"team.session_only",
|
||||||
|
Params::new(),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
st.ctl
|
||||||
|
.team
|
||||||
|
.set_root(me, body.value.tessera_root.as_deref())
|
||||||
|
.map_err(|r| refused(r.0))?;
|
||||||
|
Ok(json(
|
||||||
|
StatusCode::OK,
|
||||||
|
&super::views::Done {
|
||||||
|
message: "Done.".into(),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! In front of the API guard: the built web UI (`[ui] static_dir`) and the one-time device
|
||||||
|
//! downloads. The UI's files hold no data (it reads everything from the API, which the guard
|
||||||
|
//! protects), so they need no token; the Host check still applies against DNS rebinding.
|
||||||
|
|
||||||
|
use std::path::{Component, Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::body::Body as AxumBody;
|
||||||
|
use axum::extract::{Path as AxPath, Request, State};
|
||||||
|
use axum::http::{HeaderValue, StatusCode, header};
|
||||||
|
use axum::middleware::Next;
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
|
||||||
|
use super::{ApiError, AppState, host_allowed};
|
||||||
|
use crate::messages::Params;
|
||||||
|
|
||||||
|
const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; \
|
||||||
|
script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
|
||||||
|
|
||||||
|
pub async fn front(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Response {
|
||||||
|
let path = req.uri().path().to_owned();
|
||||||
|
if let Some(token) = path.strip_prefix("/api/v1/device-bundles/") {
|
||||||
|
if !host_allowed(&st.ctl, req.headers()) {
|
||||||
|
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new())
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
|
let token = token.to_owned();
|
||||||
|
// GET shows the page; only its button (POST) uses the link up.
|
||||||
|
return match req.method().as_str() {
|
||||||
|
"GET" | "HEAD" => super::pki::bundle_page(st, token).await,
|
||||||
|
"POST" => super::pki::download_bundle(State(st), AxPath(token))
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(IntoResponse::into_response),
|
||||||
|
_ => ApiError::new(
|
||||||
|
StatusCode::METHOD_NOT_ALLOWED,
|
||||||
|
"request.method",
|
||||||
|
Params::new(),
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// The door: redeeming a setup or invite link needs no token (crate::team).
|
||||||
|
if path == "/api/v1/session" {
|
||||||
|
if !host_allowed(&st.ctl, req.headers()) {
|
||||||
|
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new())
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
|
if req.method() != "POST" {
|
||||||
|
return ApiError::new(
|
||||||
|
StatusCode::METHOD_NOT_ALLOWED,
|
||||||
|
"request.method",
|
||||||
|
Params::new(),
|
||||||
|
)
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
|
return super::team::sign_in(st, req).await;
|
||||||
|
}
|
||||||
|
if path.starts_with("/api/") || path == "/api" {
|
||||||
|
return next.run(req).await;
|
||||||
|
}
|
||||||
|
if !host_allowed(&st.ctl, req.headers()) {
|
||||||
|
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()).into_response();
|
||||||
|
}
|
||||||
|
let Some(dir) = st.ctl.cfg.ui.as_ref().and_then(|u| u.static_dir.clone()) else {
|
||||||
|
return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
|
||||||
|
.into_response();
|
||||||
|
};
|
||||||
|
if !matches!(req.method().as_str(), "GET" | "HEAD") {
|
||||||
|
return ApiError::new(
|
||||||
|
StatusCode::METHOD_NOT_ALLOWED,
|
||||||
|
"request.method",
|
||||||
|
Params::new(),
|
||||||
|
)
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
|
serve_static(&dir, &path).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A file from the UI build. Paths with `..`, odd characters or hidden names are refused;
|
||||||
|
/// a path without a file extension is the single-page app (`index.html`).
|
||||||
|
async fn serve_static(dir: &Path, url_path: &str) -> Response {
|
||||||
|
let rel = url_path.trim_start_matches('/');
|
||||||
|
let clean = !rel.contains('\\')
|
||||||
|
&& rel
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c))
|
||||||
|
&& Path::new(rel)
|
||||||
|
.components()
|
||||||
|
.all(|c| matches!(c, Component::Normal(n) if !n.to_string_lossy().starts_with('.')));
|
||||||
|
if !clean {
|
||||||
|
return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
|
let has_ext = Path::new(rel).extension().is_some();
|
||||||
|
let file: PathBuf = if rel.is_empty() || !has_ext {
|
||||||
|
dir.join("index.html")
|
||||||
|
} else {
|
||||||
|
dir.join(rel)
|
||||||
|
};
|
||||||
|
let Ok(bytes) = tokio::fs::read(&file).await else {
|
||||||
|
return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new())
|
||||||
|
.into_response();
|
||||||
|
};
|
||||||
|
let ctype = match file.extension().and_then(|e| e.to_str()).unwrap_or("") {
|
||||||
|
"html" => "text/html; charset=utf-8",
|
||||||
|
"js" | "mjs" => "text/javascript; charset=utf-8",
|
||||||
|
"css" => "text/css; charset=utf-8",
|
||||||
|
"svg" => "image/svg+xml",
|
||||||
|
"png" => "image/png",
|
||||||
|
"ico" => "image/x-icon",
|
||||||
|
"woff2" => "font/woff2",
|
||||||
|
"json" | "webmanifest" => "application/json",
|
||||||
|
"txt" => "text/plain; charset=utf-8",
|
||||||
|
_ => "application/octet-stream",
|
||||||
|
};
|
||||||
|
let immutable = rel.starts_with("assets/") || rel.starts_with("_app/immutable/");
|
||||||
|
let mut r = Response::new(AxumBody::from(bytes));
|
||||||
|
let h = r.headers_mut();
|
||||||
|
h.insert(header::CONTENT_TYPE, HeaderValue::from_static(ctype));
|
||||||
|
h.insert(
|
||||||
|
header::CACHE_CONTROL,
|
||||||
|
HeaderValue::from_static(if immutable {
|
||||||
|
"public, max-age=31536000, immutable"
|
||||||
|
} else {
|
||||||
|
"no-cache"
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
h.insert("content-security-policy", HeaderValue::from_static(CSP));
|
||||||
|
h.insert(
|
||||||
|
"x-content-type-options",
|
||||||
|
HeaderValue::from_static("nosniff"),
|
||||||
|
);
|
||||||
|
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
|
||||||
|
h.insert("x-frame-options", HeaderValue::from_static("DENY"));
|
||||||
|
r
|
||||||
|
}
|
||||||
@@ -0,0 +1,844 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Response shapes (docs/ui-api.md §1, §2), built from control's state. Times are RFC 3339
|
||||||
|
//! UTC; every JSON object answer also gets `server_time` from the API layer.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
|
use crate::edgelink::{EdgeStatus, HostStatus};
|
||||||
|
use crate::engine::Control;
|
||||||
|
use crate::hostspec::HostSpec;
|
||||||
|
use crate::messages::{self, message};
|
||||||
|
use crate::records::{ApplyRecord, FieldError, Reason, Step, WatchHost};
|
||||||
|
use crate::util::{now, rfc3339};
|
||||||
|
|
||||||
|
fn t(x: Option<u64>) -> Option<String> {
|
||||||
|
x.map(rfc3339)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn short(id: &Option<String>) -> Option<String> {
|
||||||
|
id.as_ref().map(|c| c.chars().take(7).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One error, as the UI shows it (docs/ui-api.md §0).
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||||
|
pub struct ErrorBody {
|
||||||
|
/// Stable code, e.g. `host.upstream.no_port`.
|
||||||
|
pub code: String,
|
||||||
|
/// Plain English, shown as is.
|
||||||
|
pub message: String,
|
||||||
|
/// The form field, e.g. `upstreams[0]`.
|
||||||
|
pub field: Option<String>,
|
||||||
|
pub params: BTreeMap<String, String>,
|
||||||
|
pub retry_after_s: Option<u64>,
|
||||||
|
/// Technical detail, behind "Show details". Never a secret.
|
||||||
|
pub detail: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&FieldError> for ErrorBody {
|
||||||
|
fn from(e: &FieldError) -> Self {
|
||||||
|
ErrorBody {
|
||||||
|
code: e.code.clone(),
|
||||||
|
message: e.message.clone(),
|
||||||
|
field: e.field.clone(),
|
||||||
|
params: e.params.clone(),
|
||||||
|
retry_after_s: None,
|
||||||
|
detail: e.detail.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&Reason> for ErrorBody {
|
||||||
|
fn from(r: &Reason) -> Self {
|
||||||
|
ErrorBody {
|
||||||
|
code: r.code.clone(),
|
||||||
|
message: r.message.clone(),
|
||||||
|
field: r.field.clone(),
|
||||||
|
params: r.params.clone(),
|
||||||
|
retry_after_s: None,
|
||||||
|
detail: r.detail.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct ErrorEnvelope {
|
||||||
|
pub error: ErrorBody,
|
||||||
|
pub errors: Vec<ErrorBody>,
|
||||||
|
pub request_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- applies
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct WaitingFor {
|
||||||
|
pub apply_id: String,
|
||||||
|
pub summary: String,
|
||||||
|
pub seconds_left: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct QueueView {
|
||||||
|
pub position: usize,
|
||||||
|
pub waiting_for: Option<WaitingFor>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct WatchView {
|
||||||
|
pub ends_at: String,
|
||||||
|
pub seconds_left: u64,
|
||||||
|
pub hosts: Vec<WatchHost>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct PushView {
|
||||||
|
/// `pushed`, `pending` or `failed`.
|
||||||
|
pub state: String,
|
||||||
|
pub at: Option<String>,
|
||||||
|
pub error_code: Option<String>,
|
||||||
|
pub next_try_at: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct ApplyView {
|
||||||
|
pub id: String,
|
||||||
|
pub change_id: String,
|
||||||
|
/// `add`, `edit`, `remove`, `undo`, `restore` or `share_links`.
|
||||||
|
pub kind: String,
|
||||||
|
pub summary: String,
|
||||||
|
pub hosts: Vec<String>,
|
||||||
|
/// `queued`, `validating`, `applying`, `watching`, `kept`, `reverted`, `failed` or
|
||||||
|
/// `needs_attention`.
|
||||||
|
pub state: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub started_at: Option<String>,
|
||||||
|
pub finished_at: Option<String>,
|
||||||
|
pub steps: Vec<Step>,
|
||||||
|
pub queue: Option<QueueView>,
|
||||||
|
pub watch: Option<WatchView>,
|
||||||
|
pub reason: Option<Reason>,
|
||||||
|
pub errors: Vec<ErrorBody>,
|
||||||
|
pub commit_short: Option<String>,
|
||||||
|
pub commit: Option<String>,
|
||||||
|
pub push: Option<PushView>,
|
||||||
|
pub undo_of: Option<String>,
|
||||||
|
pub restore_of: Option<String>,
|
||||||
|
pub effect: Option<String>,
|
||||||
|
pub attempted_host: Option<HostSpec>,
|
||||||
|
pub actor: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct ApplyAccepted {
|
||||||
|
pub apply: ApplyView,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply_view(c: &Control, r: &ApplyRecord) -> ApplyView {
|
||||||
|
let n = now();
|
||||||
|
let queue = (r.state == "queued").then(|| {
|
||||||
|
let position = c.queue_position(&r.id).unwrap_or(1);
|
||||||
|
let running = c.records().into_iter().rev().find(|x| x.is_running());
|
||||||
|
QueueView {
|
||||||
|
position,
|
||||||
|
waiting_for: running.map(|x| WaitingFor {
|
||||||
|
apply_id: x.id.clone(),
|
||||||
|
summary: x.summary.clone(),
|
||||||
|
seconds_left: x.watch.as_ref().map(|w| w.ends.saturating_sub(n)),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let push = (r.state == "kept" && r.commit.is_some()).then(|| {
|
||||||
|
let p = c.push_state();
|
||||||
|
let step = r
|
||||||
|
.steps
|
||||||
|
.iter()
|
||||||
|
.find(|s| s.key == "push")
|
||||||
|
.map(|s| s.state.as_str())
|
||||||
|
.unwrap_or("pending");
|
||||||
|
PushView {
|
||||||
|
state: match step {
|
||||||
|
"done" => "pushed",
|
||||||
|
"failed" => "failed",
|
||||||
|
_ if c.cfg.routes.remote.is_none() => "pending",
|
||||||
|
_ if p.error_code.is_some() => "failed",
|
||||||
|
_ => "pending",
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
at: t(p.last_push_at),
|
||||||
|
error_code: p.error_code.clone(),
|
||||||
|
next_try_at: t(p.next_try_at),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ApplyView {
|
||||||
|
id: r.id.clone(),
|
||||||
|
change_id: r.id.clone(),
|
||||||
|
kind: r.kind.clone(),
|
||||||
|
summary: r.summary.clone(),
|
||||||
|
hosts: r.hosts.clone(),
|
||||||
|
state: r.state.clone(),
|
||||||
|
created_at: rfc3339(r.created),
|
||||||
|
started_at: t(r.started),
|
||||||
|
finished_at: t(r.finished),
|
||||||
|
steps: r.steps.clone(),
|
||||||
|
queue,
|
||||||
|
watch: r.watch.as_ref().map(|w| WatchView {
|
||||||
|
ends_at: rfc3339(w.ends),
|
||||||
|
seconds_left: if r.state == "watching" {
|
||||||
|
w.ends.saturating_sub(n)
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
},
|
||||||
|
hosts: w.hosts.clone(),
|
||||||
|
}),
|
||||||
|
reason: r.reason.clone(),
|
||||||
|
errors: r.errors.iter().map(ErrorBody::from).collect(),
|
||||||
|
commit_short: short(&r.commit),
|
||||||
|
commit: r.commit.clone(),
|
||||||
|
push,
|
||||||
|
undo_of: r.undo_of.clone(),
|
||||||
|
restore_of: r.restore_of.clone(),
|
||||||
|
effect: r.effect.clone(),
|
||||||
|
attempted_host: r.attempted_host.clone(),
|
||||||
|
actor: r.actor.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- health
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct Failure {
|
||||||
|
pub kind: String,
|
||||||
|
pub upstream: String,
|
||||||
|
pub count: u32,
|
||||||
|
pub of: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct UpstreamHealth {
|
||||||
|
pub url: String,
|
||||||
|
/// `healthy`, `down` or `pending`.
|
||||||
|
pub state: String,
|
||||||
|
pub last_check_at: Option<String>,
|
||||||
|
pub latency_ms: Option<u64>,
|
||||||
|
pub failure_kind: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct HealthView {
|
||||||
|
/// `healthy`, `degraded`, `down`, `unknown` or `pending`.
|
||||||
|
pub state: String,
|
||||||
|
pub last_check_at: Option<String>,
|
||||||
|
pub latency_ms: Option<u64>,
|
||||||
|
pub since: Option<String>,
|
||||||
|
pub failure: Option<Failure>,
|
||||||
|
pub upstreams: Vec<UpstreamHealth>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct CertView {
|
||||||
|
/// `ok`, `pending` or `failed`.
|
||||||
|
pub state: String,
|
||||||
|
pub not_after: Option<String>,
|
||||||
|
pub error_code: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The health word for a host (docs/ui-api.md §1.1): `unknown` without a health check,
|
||||||
|
/// `pending` before the first check, `healthy` when every upstream passed its last check and
|
||||||
|
/// its recent ones, `degraded` when some fail or results are mixed, `down` when none passed.
|
||||||
|
pub fn health_state(h: &HostStatus) -> &'static str {
|
||||||
|
if !h.health_check {
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
let checks: Vec<Vec<&crate::edgelink::Check>> = h
|
||||||
|
.upstreams
|
||||||
|
.iter()
|
||||||
|
.map(|u| {
|
||||||
|
u.checks
|
||||||
|
.iter()
|
||||||
|
.filter(|c| c.source == "health_check")
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if checks.iter().all(|c| c.is_empty()) {
|
||||||
|
return "pending";
|
||||||
|
}
|
||||||
|
let last_ok: Vec<bool> = checks
|
||||||
|
.iter()
|
||||||
|
.map(|c| c.last().is_some_and(|x| x.ok))
|
||||||
|
.collect();
|
||||||
|
if !last_ok.iter().any(|x| *x) {
|
||||||
|
return "down";
|
||||||
|
}
|
||||||
|
let mixed = checks
|
||||||
|
.iter()
|
||||||
|
.any(|c| c.iter().any(|x| x.ok) && c.iter().any(|x| !x.ok));
|
||||||
|
if last_ok.iter().all(|x| *x) && !mixed {
|
||||||
|
"healthy"
|
||||||
|
} else {
|
||||||
|
"degraded"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scheme_url(spec: Option<&HostSpec>, address: &str) -> String {
|
||||||
|
let scheme = spec
|
||||||
|
.and_then(|s| s.upstreams.first())
|
||||||
|
.and_then(|u| u.split_once("://").map(|(s, _)| s.to_owned()))
|
||||||
|
.unwrap_or_else(|| "http".into());
|
||||||
|
format!("{scheme}://{address}")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn health_view(
|
||||||
|
status: Option<&HostStatus>,
|
||||||
|
spec: Option<&HostSpec>,
|
||||||
|
since: Option<(&'static str, u64)>,
|
||||||
|
) -> HealthView {
|
||||||
|
let Some(h) = status else {
|
||||||
|
return HealthView {
|
||||||
|
state: if spec.is_some_and(|s| s.health_check.is_none()) {
|
||||||
|
"unknown"
|
||||||
|
} else {
|
||||||
|
"pending"
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
last_check_at: None,
|
||||||
|
latency_ms: None,
|
||||||
|
since: None,
|
||||||
|
failure: None,
|
||||||
|
upstreams: Vec::new(),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
let state = health_state(h);
|
||||||
|
let mut last_at = None;
|
||||||
|
let mut latency = None;
|
||||||
|
let mut failure: Option<Failure> = None;
|
||||||
|
let ups = h
|
||||||
|
.upstreams
|
||||||
|
.iter()
|
||||||
|
.map(|u| {
|
||||||
|
let checks: Vec<_> = u
|
||||||
|
.checks
|
||||||
|
.iter()
|
||||||
|
.filter(|c| c.source == "health_check")
|
||||||
|
.collect();
|
||||||
|
let last = checks.last();
|
||||||
|
if let Some(l) = last {
|
||||||
|
last_at = last_at.max(Some(l.at));
|
||||||
|
if l.ok {
|
||||||
|
latency = match (latency, l.latency_ms) {
|
||||||
|
(Some(a), Some(b)) => Some(u64::min(a, b)),
|
||||||
|
(a, b) => a.or(b),
|
||||||
|
};
|
||||||
|
} else if failure.is_none() {
|
||||||
|
failure = Some(Failure {
|
||||||
|
kind: l.kind.clone().unwrap_or_else(|| "bad_answer".into()),
|
||||||
|
upstream: scheme_url(spec, &u.address),
|
||||||
|
count: checks.iter().filter(|c| !c.ok).count() as u32,
|
||||||
|
of: checks.len() as u32,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
UpstreamHealth {
|
||||||
|
url: scheme_url(spec, &u.address),
|
||||||
|
state: match last {
|
||||||
|
None => "pending",
|
||||||
|
Some(l) if l.ok => "healthy",
|
||||||
|
Some(_) => "down",
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
last_check_at: last.map(|l| rfc3339(l.at)),
|
||||||
|
latency_ms: last.and_then(|l| l.latency_ms),
|
||||||
|
failure_kind: last.and_then(|l| l.kind.clone()),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
HealthView {
|
||||||
|
state: state.into(),
|
||||||
|
last_check_at: t(last_at),
|
||||||
|
latency_ms: latency,
|
||||||
|
since: since
|
||||||
|
.filter(|(s, _)| *s == state)
|
||||||
|
.map(|(_, at)| rfc3339(at)),
|
||||||
|
failure: if matches!(state, "down" | "degraded") {
|
||||||
|
failure
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
},
|
||||||
|
upstreams: if h.health_check { ups } else { Vec::new() },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cert_view(status: Option<&HostStatus>, spec: Option<&HostSpec>) -> CertView {
|
||||||
|
match status {
|
||||||
|
Some(h) => CertView {
|
||||||
|
state: h.certificate.state.clone(),
|
||||||
|
not_after: h
|
||||||
|
.certificate
|
||||||
|
.not_after
|
||||||
|
.and_then(|x| u64::try_from(x).ok())
|
||||||
|
.map(rfc3339),
|
||||||
|
error_code: (h.certificate.state == "failed").then(|| "cert.failed".into()),
|
||||||
|
},
|
||||||
|
None => CertView {
|
||||||
|
state: if spec.is_some_and(|s| s.tls == "domi") {
|
||||||
|
"ok"
|
||||||
|
} else {
|
||||||
|
"pending"
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
not_after: None,
|
||||||
|
error_code: None,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- hosts and overview
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct HostRow {
|
||||||
|
pub hostname: String,
|
||||||
|
pub upstreams: Vec<String>,
|
||||||
|
pub tls: String,
|
||||||
|
pub auth: String,
|
||||||
|
pub websockets: bool,
|
||||||
|
pub share_links: bool,
|
||||||
|
/// Visitors need a Domi device certificate.
|
||||||
|
pub device_certs: bool,
|
||||||
|
pub added_at: Option<String>,
|
||||||
|
pub health: HealthView,
|
||||||
|
pub certificate: CertView,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct HostDetail {
|
||||||
|
pub host: HostSpec,
|
||||||
|
/// The routes commit this was read from; send it back as `base_rev`.
|
||||||
|
pub rev: String,
|
||||||
|
/// The host file as committed.
|
||||||
|
pub toml: String,
|
||||||
|
pub health: HealthView,
|
||||||
|
pub certificate: CertView,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct HostList {
|
||||||
|
pub rev: String,
|
||||||
|
pub hosts: Vec<HostRow>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, ToSchema)]
|
||||||
|
pub struct Counts {
|
||||||
|
pub hosts: usize,
|
||||||
|
pub healthy: usize,
|
||||||
|
pub degraded: usize,
|
||||||
|
pub down: usize,
|
||||||
|
pub unknown: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct EngineView {
|
||||||
|
/// `pingora` or `caddy`.
|
||||||
|
pub running: String,
|
||||||
|
/// `running`, `switching` or `stopped` (control cannot reach it).
|
||||||
|
pub state: String,
|
||||||
|
pub since: Option<String>,
|
||||||
|
/// The engine a running switch goes to.
|
||||||
|
pub target: Option<String>,
|
||||||
|
/// Whether control can switch on this server (`[engine]` in control.toml).
|
||||||
|
pub switchable: bool,
|
||||||
|
/// The fallback's config: when it was written and whether it is the current tree's.
|
||||||
|
pub fallback_ready: Option<FallbackReady>,
|
||||||
|
/// Why the last switch did not happen.
|
||||||
|
pub last_error: Option<Reason>,
|
||||||
|
/// What is different while Caddy serves (`engine.caddy`, `share.engine_caddy`).
|
||||||
|
pub notes: Vec<Blocked>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct FallbackReady {
|
||||||
|
pub built_at: Option<String>,
|
||||||
|
/// caddy.json is the compiled current tree.
|
||||||
|
pub current: bool,
|
||||||
|
/// Hosts in the current routes, and how many of them behave the same on Caddy as far as
|
||||||
|
/// Ianitor knows (the differential tests' known differences, applied to these hosts).
|
||||||
|
pub compared: u32,
|
||||||
|
pub matched: u32,
|
||||||
|
/// What is different on Caddy, in plain English (per host first, then for every host).
|
||||||
|
pub differences: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct UndoTarget {
|
||||||
|
pub change_id: String,
|
||||||
|
pub summary: String,
|
||||||
|
pub kept_at: Option<String>,
|
||||||
|
pub commit_short: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct Blocked {
|
||||||
|
pub code: String,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct UndoView {
|
||||||
|
pub available: bool,
|
||||||
|
pub target: Option<UndoTarget>,
|
||||||
|
/// What Undo does, e.g. "Removes recipes.home.example".
|
||||||
|
pub effect: Option<String>,
|
||||||
|
pub blocked: Option<Blocked>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct ActiveApply {
|
||||||
|
pub id: String,
|
||||||
|
pub state: String,
|
||||||
|
pub summary: String,
|
||||||
|
pub seconds_left: Option<u64>,
|
||||||
|
/// `add`, `edit`, `remove`, `undo`, `restore`, `share_links`: the UI writes the heading.
|
||||||
|
pub kind: String,
|
||||||
|
pub hosts: Vec<String>,
|
||||||
|
/// When the health watch ends (only while watching), for a local countdown.
|
||||||
|
pub watch_ends_at: Option<String>,
|
||||||
|
pub queued: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct RepoView {
|
||||||
|
pub name: String,
|
||||||
|
pub last_push_at: Option<String>,
|
||||||
|
pub unpushed: u64,
|
||||||
|
pub push_error_code: Option<String>,
|
||||||
|
pub remote_configured: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct SiteView {
|
||||||
|
pub forward_auth_configured: bool,
|
||||||
|
pub acme_configured: bool,
|
||||||
|
pub secrets: Vec<String>,
|
||||||
|
pub watch_seconds: u64,
|
||||||
|
pub share_links_available: bool,
|
||||||
|
/// Authelia's logout address, for "Sign out" (`[ui] logout_url`); `null` hides the link.
|
||||||
|
pub auth_logout_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct Overview {
|
||||||
|
pub counts: Counts,
|
||||||
|
pub hosts: Vec<HostRow>,
|
||||||
|
pub engine: EngineView,
|
||||||
|
pub last_apply: Option<ApplyView>,
|
||||||
|
pub undo: UndoView,
|
||||||
|
pub active_apply: Option<ActiveApply>,
|
||||||
|
pub repo: Option<RepoView>,
|
||||||
|
/// The Domi intermediate; `null` when the Domi CA is not set up (`[pki]`).
|
||||||
|
pub intermediate: Option<super::pki::IntermediateView>,
|
||||||
|
pub site: Option<SiteView>,
|
||||||
|
pub paused: Option<Blocked>,
|
||||||
|
/// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`,
|
||||||
|
/// `repo.unreadable`, …), so the UI can offer the right action.
|
||||||
|
pub paused_reason: Option<String>,
|
||||||
|
/// The technical detail behind the pause, for "Show details" (never a secret).
|
||||||
|
pub paused_detail: Option<String>,
|
||||||
|
/// Set when control cannot read health from edge (`health.unavailable`).
|
||||||
|
pub health_error: Option<Blocked>,
|
||||||
|
pub rev: Option<String>,
|
||||||
|
/// Who is looking: the Authelia user (through edge) or the API token's name.
|
||||||
|
pub viewer: Option<Viewer>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct Viewer {
|
||||||
|
pub name: String,
|
||||||
|
/// `authelia` or `token`.
|
||||||
|
pub via: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn added_at(c: &Control, hostname: &str) -> Option<String> {
|
||||||
|
c.records()
|
||||||
|
.iter()
|
||||||
|
.find(|r| r.kind == "add" && r.state == "kept" && r.hosts.iter().any(|h| h == hostname))
|
||||||
|
.and_then(|r| r.finished)
|
||||||
|
.map(rfc3339)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn undo_view(c: &Control) -> UndoView {
|
||||||
|
let blocked = if let Some(p) = c.effective_pause() {
|
||||||
|
Some(Blocked {
|
||||||
|
code: "undo.paused".into(),
|
||||||
|
message: message("undo.paused", &messages::Params::new()) + " " + &p.message,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
c.records()
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find(|r| r.is_running() && r.kind == "undo")
|
||||||
|
.map(|r| {
|
||||||
|
let left = r
|
||||||
|
.watch
|
||||||
|
.as_ref()
|
||||||
|
.map(|w| w.ends.saturating_sub(now()))
|
||||||
|
.unwrap_or(0);
|
||||||
|
Blocked {
|
||||||
|
code: "undo.watching".into(),
|
||||||
|
message: message(
|
||||||
|
"undo.watching",
|
||||||
|
&messages::params([("seconds", left.to_string())]),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
|
match c.undo_target() {
|
||||||
|
None => UndoView {
|
||||||
|
available: false,
|
||||||
|
target: None,
|
||||||
|
effect: None,
|
||||||
|
blocked: Some(blocked.unwrap_or(Blocked {
|
||||||
|
code: "undo.nothing".into(),
|
||||||
|
message: message("undo.nothing", &messages::Params::new()),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
Some(t) => {
|
||||||
|
let effect = undo_effect(c, &t);
|
||||||
|
UndoView {
|
||||||
|
available: blocked.is_none(),
|
||||||
|
target: Some(UndoTarget {
|
||||||
|
change_id: t.id.clone(),
|
||||||
|
summary: t.summary.clone(),
|
||||||
|
kept_at: t.finished.map(rfc3339),
|
||||||
|
commit_short: short(&t.commit),
|
||||||
|
}),
|
||||||
|
effect,
|
||||||
|
blocked,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What undoing `t` would do: from its tree back to the tree before it.
|
||||||
|
pub fn undo_effect(c: &Control, t: &ApplyRecord) -> Option<String> {
|
||||||
|
let (commit, base) = (t.commit.as_ref()?, t.base.as_ref()?);
|
||||||
|
let from = c.repo.tree(commit).ok()?;
|
||||||
|
let to = c.repo.tree(base).ok()?;
|
||||||
|
let mut parts = Vec::new();
|
||||||
|
let mut names: std::collections::BTreeSet<String> = from.hostnames().into_iter().collect();
|
||||||
|
names.extend(to.hostnames());
|
||||||
|
for h in names {
|
||||||
|
match (from.host(&h), to.host(&h)) {
|
||||||
|
(Some(a), Some(b)) if a != b => parts.push(format!("Changes {h} back")),
|
||||||
|
(Some(_), None) => parts.push(format!("Removes {h}")),
|
||||||
|
(None, Some(_)) => parts.push(format!("Adds {h} back")),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(if parts.is_empty() {
|
||||||
|
"Changes the site settings back".into()
|
||||||
|
} else {
|
||||||
|
parts.join("; ")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn host_rows(
|
||||||
|
c: &Control,
|
||||||
|
tree: &crate::repo::RouteTree,
|
||||||
|
status: Option<&EdgeStatus>,
|
||||||
|
since: &std::collections::HashMap<String, (&'static str, u64)>,
|
||||||
|
) -> Vec<HostRow> {
|
||||||
|
tree.hostnames()
|
||||||
|
.into_iter()
|
||||||
|
.map(|h| {
|
||||||
|
let spec = tree.host(&h).and_then(|t| HostSpec::from_toml(t).ok());
|
||||||
|
let st = status.and_then(|s| s.hosts.iter().find(|x| x.hostname == h));
|
||||||
|
HostRow {
|
||||||
|
upstreams: spec
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.upstreams.clone())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
tls: spec.as_ref().map(|s| s.tls.clone()).unwrap_or_default(),
|
||||||
|
auth: spec.as_ref().map(|s| s.auth.clone()).unwrap_or_default(),
|
||||||
|
websockets: spec.as_ref().is_none_or(|s| s.websockets),
|
||||||
|
share_links: spec.as_ref().is_some_and(|s| s.share_links),
|
||||||
|
device_certs: spec.as_ref().is_some_and(|s| s.device_certs),
|
||||||
|
added_at: added_at(c, &h),
|
||||||
|
health: health_view(st, spec.as_ref(), since.get(&h).copied()),
|
||||||
|
certificate: cert_view(st, spec.as_ref()),
|
||||||
|
hostname: h,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- history
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct HistoryEntry {
|
||||||
|
pub change_id: String,
|
||||||
|
pub summary: String,
|
||||||
|
pub kind: String,
|
||||||
|
pub state: String,
|
||||||
|
pub at: String,
|
||||||
|
pub commit_short: Option<String>,
|
||||||
|
pub hosts: Vec<String>,
|
||||||
|
pub reason_short: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct History {
|
||||||
|
pub entries: Vec<HistoryEntry>,
|
||||||
|
/// Pass as `before` for older entries.
|
||||||
|
pub next_before: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn history_row(r: &ApplyRecord) -> HistoryEntry {
|
||||||
|
HistoryEntry {
|
||||||
|
change_id: r.id.clone(),
|
||||||
|
summary: r.summary.clone(),
|
||||||
|
kind: r.kind.clone(),
|
||||||
|
state: r.state.clone(),
|
||||||
|
at: rfc3339(r.finished.unwrap_or(r.created)),
|
||||||
|
commit_short: short(&r.commit),
|
||||||
|
hosts: r.hosts.clone(),
|
||||||
|
reason_short: r.reason.as_ref().filter(|_| r.state != "kept").map(|x| {
|
||||||
|
x.params
|
||||||
|
.get("kind")
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| x.code.rsplit('.').next().unwrap_or("").replace('_', " "))
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct FieldChange {
|
||||||
|
pub field: String,
|
||||||
|
pub from: String,
|
||||||
|
pub to: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct HostChange {
|
||||||
|
pub hostname: String,
|
||||||
|
/// `added`, `removed` or `changed`.
|
||||||
|
pub effect: String,
|
||||||
|
pub fields: Vec<FieldChange>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct RestorePreview {
|
||||||
|
pub restorable: bool,
|
||||||
|
pub same_as_current: bool,
|
||||||
|
pub changes: Vec<HostChange>,
|
||||||
|
pub blocked: Option<Blocked>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- tokens, shares, settings
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct TokenView {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub last_used_at: Option<String>,
|
||||||
|
pub expires_at: Option<String>,
|
||||||
|
pub revoked_at: Option<String>,
|
||||||
|
/// `full` or `previews`.
|
||||||
|
pub scope: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&crate::tokens::TokenRecord> for TokenView {
|
||||||
|
fn from(r: &crate::tokens::TokenRecord) -> Self {
|
||||||
|
TokenView {
|
||||||
|
id: r.id.clone(),
|
||||||
|
name: r.name.clone(),
|
||||||
|
created_at: rfc3339(r.created_at),
|
||||||
|
last_used_at: t(r.last_used_at),
|
||||||
|
expires_at: t(r.expires_at),
|
||||||
|
revoked_at: t(r.revoked_at),
|
||||||
|
scope: r.scope.as_str().into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct TokenList {
|
||||||
|
pub items: Vec<TokenView>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct CreatedToken {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
/// Shown once; Ianitor keeps only its hash.
|
||||||
|
pub token: String,
|
||||||
|
pub expires_at: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct ShareLinkView {
|
||||||
|
pub id: String,
|
||||||
|
pub hostname: String,
|
||||||
|
pub path_prefix: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub expires_at: String,
|
||||||
|
pub has_password: bool,
|
||||||
|
/// `active`, `expired` or `stopped`.
|
||||||
|
pub state: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct ShareLinkList {
|
||||||
|
pub items: Vec<ShareLinkView>,
|
||||||
|
pub epoch: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct MintedLink {
|
||||||
|
pub id: String,
|
||||||
|
/// Contains the token; shown once.
|
||||||
|
pub url: String,
|
||||||
|
pub expires_at: String,
|
||||||
|
pub path_prefix: String,
|
||||||
|
pub has_password: bool,
|
||||||
|
/// `host.share.no_signin` when the host needs no sign-in anyway.
|
||||||
|
pub warning: Option<Blocked>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct StoppedAll {
|
||||||
|
pub epoch: u32,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct Settings {
|
||||||
|
pub repo: RepoView,
|
||||||
|
pub watch_seconds: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct EdgeHealth {
|
||||||
|
pub attached: bool,
|
||||||
|
pub reachable: bool,
|
||||||
|
pub config_sha256: Option<String>,
|
||||||
|
pub trial_running: bool,
|
||||||
|
pub error: Option<String>,
|
||||||
|
pub read_at: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct HealthReport {
|
||||||
|
pub edge: EdgeHealth,
|
||||||
|
pub paused: Option<Blocked>,
|
||||||
|
pub queued: usize,
|
||||||
|
pub hosts: Vec<HostRow>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
||||||
|
pub struct Done {
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! The deadline of a trial under Caddy (QC round 2, B2; the Phase 2 guarantee that an
|
||||||
|
//! unconfirmed change never outlives control). Edge drops a trial by itself when control does
|
||||||
|
//! not confirm it in time; Caddy has no such clock, so two things outside control's own process
|
||||||
|
//! stand in for it:
|
||||||
|
//!
|
||||||
|
//! - `ianitor-control caddy-revert` (systemd `ExecStopPost=` of ianitor-control, so it runs
|
||||||
|
//! after every stop, a crash included): with a trial out, Caddy goes back to caddy.json (the
|
||||||
|
//! last good config) at once;
|
||||||
|
//! - `ianitor-control caddy-guard` (its own unit next to caddy-fallback, so a hung control is
|
||||||
|
//! covered too): once a second, it reverts a trial whose deadline has passed.
|
||||||
|
//!
|
||||||
|
//! Control *arms* the deadline (`caddy-trial.json` in its state dir) before it loads a trial,
|
||||||
|
//! and *claims* it (an atomic rename) right after its journal says `confirmed`; the guard
|
||||||
|
//! takes it with the same kind of rename (to `.reverting`, then `.expired` once Caddy is
|
||||||
|
//! verified on caddy.json; given back if the load fails, so it is tried again). A crash between
|
||||||
|
//! `confirmed` and the claim leaves both: the guard and caddy-revert see `confirmed` and leave
|
||||||
|
//! the trial to recovery, which promotes it. Whoever renames first wins, so a trial is either confirmed by control or
|
||||||
|
//! reverted by the guard, never both. caddy.json itself is only ever written with a confirmed
|
||||||
|
//! config, so loading it is always safe.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::config::Config;
|
||||||
|
use crate::records::Journal;
|
||||||
|
use crate::util::{read_json, write_json};
|
||||||
|
|
||||||
|
pub const DEADLINE_FILE: &str = "caddy-trial.json";
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct TrialDeadline {
|
||||||
|
pub apply_id: String,
|
||||||
|
/// Unix seconds.
|
||||||
|
pub deadline: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path(state_dir: &Path, suffix: &str) -> PathBuf {
|
||||||
|
state_dir.join(format!("{DEADLINE_FILE}{suffix}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Before a trial goes into Caddy.
|
||||||
|
pub fn arm(state_dir: &Path, apply_id: &str, deadline: u64) -> Result<(), String> {
|
||||||
|
write_json(
|
||||||
|
&path(state_dir, ""),
|
||||||
|
&TrialDeadline {
|
||||||
|
apply_id: apply_id.to_owned(),
|
||||||
|
deadline,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Control, before it confirms: `true` if it got the deadline first (the guard has not
|
||||||
|
/// reverted the trial), `false` if the guard did.
|
||||||
|
pub fn claim(state_dir: &Path) -> bool {
|
||||||
|
let claimed = path(state_dir, ".claimed");
|
||||||
|
if std::fs::rename(path(state_dir, ""), &claimed).is_err() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_file(claimed);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After a trial is reverted (or at start): nothing is out any more.
|
||||||
|
pub fn disarm(state_dir: &Path) {
|
||||||
|
for s in ["", ".claimed", ".expired", ".reverting"] {
|
||||||
|
let _ = std::fs::remove_file(path(state_dir, s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn armed(state_dir: &Path) -> Option<TrialDeadline> {
|
||||||
|
read_json(&path(state_dir, "")).ok().flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether control's journal says the change is confirmed (then it is being promoted and
|
||||||
|
/// caddy.json will hold it; nothing to revert).
|
||||||
|
fn confirmed(state_dir: &Path) -> bool {
|
||||||
|
read_json::<Journal>(&state_dir.join("journal.json"))
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.is_some_and(|j| j.stage == "confirmed" || j.stage == "promoted")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What to do now, for a deadline file as found (pure, for the tests).
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum Verdict {
|
||||||
|
Nothing,
|
||||||
|
Revert,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verdict(armed: Option<&TrialDeadline>, confirmed: bool, now: u64, at_stop: bool) -> Verdict {
|
||||||
|
match armed {
|
||||||
|
Some(d) if !confirmed && (at_stop || now > d.deadline) => Verdict::Revert,
|
||||||
|
_ => Verdict::Nothing,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether Caddy is the engine that serves (the engine file; Pingora without `[engine]`).
|
||||||
|
fn caddy_serves(cfg: &Config) -> bool {
|
||||||
|
cfg.engine
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|e| crate::switch::read_engine_file(&e.file) == "caddy")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A revert that stopped half way (the guard died while loading) counts as armed again.
|
||||||
|
fn resume_half_done(dir: &Path) {
|
||||||
|
let reverting = path(dir, ".reverting");
|
||||||
|
if reverting.exists() && !path(dir, "").exists() {
|
||||||
|
let _ = std::fs::rename(reverting, path(dir, ""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Take the deadline away from control (rename to `.reverting`), load the last good
|
||||||
|
/// caddy.json and check that Caddy runs it; only then is the deadline marked expired. If the
|
||||||
|
/// load fails, the deadline is given back, so the next try (or control's own claim, while
|
||||||
|
/// Caddy still runs the trial) decides.
|
||||||
|
async fn revert(cfg: &Config, why: &str) -> Result<bool, String> {
|
||||||
|
let dir = &cfg.state_dir;
|
||||||
|
let reverting = path(dir, ".reverting");
|
||||||
|
if std::fs::rename(path(dir, ""), &reverting).is_err() {
|
||||||
|
// Control claimed it a moment ago: it confirms; nothing to do.
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let loaded = async {
|
||||||
|
let sock = crate::caddy_link::Admin::from_compile(cfg.caddy_compile())
|
||||||
|
.ok_or("no caddy_admin_socket (or loopback caddy_admin) is configured")?;
|
||||||
|
let text = std::fs::read(&cfg.caddy.config)
|
||||||
|
.map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?;
|
||||||
|
crate::caddy_link::load(&sock, &text).await?;
|
||||||
|
if !crate::caddy_link::runs(&sock, &text).await? {
|
||||||
|
return Err("Caddy took caddy.json but does not run it".to_owned());
|
||||||
|
}
|
||||||
|
Ok::<_, String>(())
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
match loaded {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = std::fs::rename(&reverting, path(dir, ".expired"));
|
||||||
|
log::warn!(target: "ianitor::caddy-guard", "{why}: Caddy is back on the last good config");
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let _ = std::fs::rename(&reverting, path(dir, ""));
|
||||||
|
Err(format!("{why}, but Caddy could not be put back yet: {e}"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ianitor-control caddy-revert`: after control stops, a trial still out goes back at once
|
||||||
|
/// (retried a few times, 1, 2, 4 and 8 s apart). With another engine serving there is no
|
||||||
|
/// Caddy trial: a deadline left behind is cleared and nothing fails.
|
||||||
|
pub async fn revert_after_stop(cfg: &Config) -> Result<bool, String> {
|
||||||
|
let dir = &cfg.state_dir;
|
||||||
|
if !caddy_serves(cfg) {
|
||||||
|
disarm(dir);
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
resume_half_done(dir);
|
||||||
|
let mut wait = 1;
|
||||||
|
loop {
|
||||||
|
let r = match verdict(
|
||||||
|
armed(dir).as_ref(),
|
||||||
|
confirmed(dir),
|
||||||
|
crate::util::now(),
|
||||||
|
true,
|
||||||
|
) {
|
||||||
|
Verdict::Revert => revert(cfg, "control stopped with a trial loaded into Caddy").await,
|
||||||
|
Verdict::Nothing => Ok(false),
|
||||||
|
};
|
||||||
|
match r {
|
||||||
|
Err(e) if wait <= 8 => {
|
||||||
|
log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {wait} s");
|
||||||
|
tokio::time::sleep(std::time::Duration::from_secs(wait)).await;
|
||||||
|
wait *= 2;
|
||||||
|
}
|
||||||
|
other => return other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One tick of `ianitor-control caddy-guard`.
|
||||||
|
pub async fn tick(cfg: &Config) -> Result<bool, String> {
|
||||||
|
let dir = &cfg.state_dir;
|
||||||
|
if !caddy_serves(cfg) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
resume_half_done(dir);
|
||||||
|
match verdict(
|
||||||
|
armed(dir).as_ref(),
|
||||||
|
confirmed(dir),
|
||||||
|
crate::util::now(),
|
||||||
|
false,
|
||||||
|
) {
|
||||||
|
Verdict::Revert => revert(cfg, "a trial under Caddy passed its deadline unconfirmed").await,
|
||||||
|
Verdict::Nothing => Ok(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ianitor-control caddy-guard`: forever, once a second; after a failed revert it tries
|
||||||
|
/// again with a growing pause (2, 4, … 30 s).
|
||||||
|
pub async fn run(cfg: Config) -> Result<(), String> {
|
||||||
|
log::info!(target: "ianitor::caddy-guard", "watching {} for trials under Caddy", cfg.state_dir.display());
|
||||||
|
let mut pause = 1u64;
|
||||||
|
loop {
|
||||||
|
match tick(&cfg).await {
|
||||||
|
Ok(_) => pause = 1,
|
||||||
|
Err(e) => {
|
||||||
|
pause = (pause * 2).min(30);
|
||||||
|
log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {pause} s");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_secs(pause)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn d(deadline: u64) -> TrialDeadline {
|
||||||
|
TrialDeadline {
|
||||||
|
apply_id: "ch_1".into(),
|
||||||
|
deadline,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_guard_reverts_only_an_unconfirmed_trial_past_its_deadline() {
|
||||||
|
assert_eq!(verdict(None, false, 100, false), Verdict::Nothing);
|
||||||
|
assert_eq!(verdict(Some(&d(100)), false, 100, false), Verdict::Nothing);
|
||||||
|
assert_eq!(verdict(Some(&d(100)), false, 101, false), Verdict::Revert);
|
||||||
|
assert_eq!(verdict(Some(&d(100)), true, 500, false), Verdict::Nothing);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn after_a_stop_an_unconfirmed_trial_goes_back_at_once() {
|
||||||
|
assert_eq!(verdict(Some(&d(1000)), false, 1, true), Verdict::Revert);
|
||||||
|
assert_eq!(verdict(Some(&d(1000)), true, 1, true), Verdict::Nothing);
|
||||||
|
assert_eq!(verdict(None, false, 1, true), Verdict::Nothing);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn control_and_the_guard_cannot_both_have_the_deadline() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("ianitor-guard-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
arm(&dir, "ch_1", 10).unwrap();
|
||||||
|
assert_eq!(armed(&dir), Some(d(10)));
|
||||||
|
// The guard took it (as `revert` does): control's claim fails.
|
||||||
|
std::fs::rename(path(&dir, ""), path(&dir, ".expired")).unwrap();
|
||||||
|
assert!(!claim(&dir));
|
||||||
|
disarm(&dir);
|
||||||
|
// Control claims first: nothing is left for the guard.
|
||||||
|
arm(&dir, "ch_1", 10).unwrap();
|
||||||
|
assert!(claim(&dir));
|
||||||
|
assert!(armed(&dir).is_none());
|
||||||
|
assert!(std::fs::rename(path(&dir, ""), path(&dir, ".expired")).is_err());
|
||||||
|
disarm(&dir);
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,422 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep
|
||||||
|
//! working under Caddy): loading a config through Caddy's admin API on its Unix socket, or on
|
||||||
|
//! loopback TCP where there are no Unix sockets (Windows Caddy mode, T4)
|
||||||
|
//! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host
|
||||||
|
//! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch,
|
||||||
|
//! judged like edge's), and the certificate Caddy serves.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
|
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||||
|
|
||||||
|
/// Where Caddy's admin API listens: a Unix socket (Linux, mode 0660), or loopback TCP
|
||||||
|
/// (Windows, where control and Caddy are the only services and the port is on 127.0.0.1).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum Admin {
|
||||||
|
Unix(PathBuf),
|
||||||
|
Tcp(SocketAddr),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Admin {
|
||||||
|
/// From the compile facts: the socket when there is one, else a loopback TCP address.
|
||||||
|
pub fn from_compile(c: &crate::config::Compile) -> Option<Admin> {
|
||||||
|
match (&c.caddy_admin_socket, c.caddy_admin) {
|
||||||
|
(Some(s), _) => Some(Admin::Unix(PathBuf::from(s))),
|
||||||
|
(None, Some(a)) if a.ip().is_loopback() => Some(Admin::Tcp(a)),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `Host` header Caddy's admin API accepts (its origin check).
|
||||||
|
fn host(&self) -> String {
|
||||||
|
match self {
|
||||||
|
Admin::Unix(_) => "localhost".into(),
|
||||||
|
Admin::Tcp(a) => a.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&Path> for Admin {
|
||||||
|
fn from(p: &Path) -> Admin {
|
||||||
|
Admin::Unix(p.to_owned())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn exchange(admin: &Admin, request: &[u8]) -> std::io::Result<Vec<u8>> {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
match admin {
|
||||||
|
#[cfg(unix)]
|
||||||
|
Admin::Unix(p) => {
|
||||||
|
let mut s = tokio::net::UnixStream::connect(p).await?;
|
||||||
|
s.write_all(request).await?;
|
||||||
|
s.read_to_end(&mut buf).await?;
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
Admin::Unix(_) => {
|
||||||
|
return Err(std::io::Error::other(
|
||||||
|
"Caddy's admin socket needs Unix; set caddy_admin = \"127.0.0.1:2019\" instead",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Admin::Tcp(a) => {
|
||||||
|
let mut s = tokio::net::TcpStream::connect(a).await?;
|
||||||
|
s.write_all(request).await?;
|
||||||
|
s.read_to_end(&mut buf).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). `request` has
|
||||||
|
/// `{host}` where the Host header value goes.
|
||||||
|
async fn admin(admin: &Admin, request: &[u8]) -> Result<(u16, Vec<u8>), String> {
|
||||||
|
let host = admin.host();
|
||||||
|
let request = {
|
||||||
|
let split = request
|
||||||
|
.windows(4)
|
||||||
|
.position(|w| w == b"\r\n\r\n")
|
||||||
|
.unwrap_or(request.len());
|
||||||
|
let head = String::from_utf8_lossy(&request[..split]).replace("{host}", &host);
|
||||||
|
let mut r = head.into_bytes();
|
||||||
|
r.extend_from_slice(&request[split..]);
|
||||||
|
r
|
||||||
|
};
|
||||||
|
let buf = tokio::time::timeout(TIMEOUT, exchange(admin, &request))
|
||||||
|
.await
|
||||||
|
.map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())?
|
||||||
|
.map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?;
|
||||||
|
let split = buf
|
||||||
|
.windows(4)
|
||||||
|
.position(|w| w == b"\r\n\r\n")
|
||||||
|
.ok_or("no answer from Caddy's admin API")?;
|
||||||
|
let head = String::from_utf8_lossy(&buf[..split]);
|
||||||
|
let status: u16 = head
|
||||||
|
.split(' ')
|
||||||
|
.nth(1)
|
||||||
|
.and_then(|s| s.parse().ok())
|
||||||
|
.ok_or("no answer from Caddy's admin API")?;
|
||||||
|
Ok((status, buf[split + 4..].to_vec()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the
|
||||||
|
/// old one). `Cache-Control: must-revalidate` makes Caddy load it even when it is the same as
|
||||||
|
/// the running one, so certificate and device files are read again (without it an identical
|
||||||
|
/// config is a no-op: QC round 2, B1; `qc_reloading_the_same_caddy_json_rereads_the_certificate_files`).
|
||||||
|
pub async fn load(socket: &Admin, config: &[u8]) -> Result<(), String> {
|
||||||
|
let mut req = format!(
|
||||||
|
"POST /load HTTP/1.0\r\nHost: {{host}}\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n",
|
||||||
|
config.len()
|
||||||
|
)
|
||||||
|
.into_bytes();
|
||||||
|
req.extend_from_slice(config);
|
||||||
|
let (status, body) = admin(socket, &req).await?;
|
||||||
|
if (200..300).contains(&status) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(format!(
|
||||||
|
"Caddy refused the config ({status}): {}",
|
||||||
|
String::from_utf8_lossy(&body)
|
||||||
|
.trim()
|
||||||
|
.chars()
|
||||||
|
.take(400)
|
||||||
|
.collect::<String>()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The config Caddy runs now.
|
||||||
|
pub async fn running_config(socket: &Admin) -> Result<serde_json::Value, String> {
|
||||||
|
let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: {host}\r\n\r\n").await?;
|
||||||
|
if status != 200 {
|
||||||
|
return Err(format!(
|
||||||
|
"Caddy's admin API answered {status} to GET /config/"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
serde_json::from_slice(&body).map_err(|e| format!("Caddy's running config is not JSON: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter).
|
||||||
|
pub async fn runs(socket: &Admin, config: &[u8]) -> Result<bool, String> {
|
||||||
|
let want: serde_json::Value =
|
||||||
|
serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?;
|
||||||
|
Ok(running_config(socket).await? == want)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum Probe {
|
||||||
|
/// The status Caddy answered with (its own 502/503 when the upstream is down).
|
||||||
|
Status(u16),
|
||||||
|
/// No answer at all (connection, TLS or timeout).
|
||||||
|
NoAnswer(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The probe does not check Caddy's certificate: it talks to this machine's own listener
|
||||||
|
/// on loopback to see whether the *upstream* answers through it, nothing else.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct AnyCert;
|
||||||
|
|
||||||
|
impl rustls::client::danger::ServerCertVerifier for AnyCert {
|
||||||
|
fn verify_server_cert(
|
||||||
|
&self,
|
||||||
|
_end_entity: &rustls_pki_types::CertificateDer<'_>,
|
||||||
|
_intermediates: &[rustls_pki_types::CertificateDer<'_>],
|
||||||
|
_server_name: &rustls_pki_types::ServerName<'_>,
|
||||||
|
_ocsp: &[u8],
|
||||||
|
_now: rustls_pki_types::UnixTime,
|
||||||
|
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
|
||||||
|
Ok(rustls::client::danger::ServerCertVerified::assertion())
|
||||||
|
}
|
||||||
|
fn verify_tls12_signature(
|
||||||
|
&self,
|
||||||
|
_message: &[u8],
|
||||||
|
_cert: &rustls_pki_types::CertificateDer<'_>,
|
||||||
|
_dss: &rustls::DigitallySignedStruct,
|
||||||
|
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||||
|
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
|
||||||
|
}
|
||||||
|
fn verify_tls13_signature(
|
||||||
|
&self,
|
||||||
|
_message: &[u8],
|
||||||
|
_cert: &rustls_pki_types::CertificateDer<'_>,
|
||||||
|
_dss: &rustls::DigitallySignedStruct,
|
||||||
|
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||||
|
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
|
||||||
|
}
|
||||||
|
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
||||||
|
rustls::crypto::ring::default_provider()
|
||||||
|
.signature_verification_algorithms
|
||||||
|
.supported_schemes()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn probe(addr: SocketAddr, host: &str, path: &str) -> Probe {
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
let started = Instant::now();
|
||||||
|
let run = async {
|
||||||
|
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||||
|
let cfg = rustls::ClientConfig::builder_with_provider(provider)
|
||||||
|
.with_safe_default_protocol_versions()
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.dangerous()
|
||||||
|
.with_custom_certificate_verifier(Arc::new(AnyCert))
|
||||||
|
.with_no_client_auth();
|
||||||
|
let name =
|
||||||
|
rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?;
|
||||||
|
let tcp = tokio::net::TcpStream::connect(addr)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let mut tls = tokio_rustls::TlsConnector::from(Arc::new(cfg))
|
||||||
|
.connect(name, tcp)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let req = format!(
|
||||||
|
"GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: ianitor-watch\r\nConnection: close\r\n\r\n"
|
||||||
|
);
|
||||||
|
tls.write_all(req.as_bytes())
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let mut head = [0u8; 64];
|
||||||
|
let mut n = 0;
|
||||||
|
while n < 13 {
|
||||||
|
let k = tls.read(&mut head[n..]).await.map_err(|e| e.to_string())?;
|
||||||
|
if k == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
n += k;
|
||||||
|
}
|
||||||
|
let line = String::from_utf8_lossy(&head[..n]);
|
||||||
|
line.split(' ')
|
||||||
|
.nth(1)
|
||||||
|
.and_then(|s| s.parse::<u16>().ok())
|
||||||
|
.ok_or_else(|| "no HTTP status".to_owned())
|
||||||
|
};
|
||||||
|
match tokio::time::timeout(Duration::from_secs(5), run).await {
|
||||||
|
Ok(Ok(s)) => Probe::Status(s),
|
||||||
|
Ok(Err(e)) => Probe::NoAnswer(e),
|
||||||
|
Err(_) => Probe::NoAnswer(format!(
|
||||||
|
"no answer within {} s",
|
||||||
|
started.elapsed().as_secs()
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SHA-256 (hex) of the leaf certificate Caddy serves for this name: after a reload, whether
|
||||||
|
/// Caddy really read the certificate files again (the backstop for B1).
|
||||||
|
pub async fn served_cert_sha256(addr: SocketAddr, host: &str) -> Result<String, String> {
|
||||||
|
let run = async {
|
||||||
|
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||||
|
let cfg = rustls::ClientConfig::builder_with_provider(provider)
|
||||||
|
.with_safe_default_protocol_versions()
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.dangerous()
|
||||||
|
.with_custom_certificate_verifier(Arc::new(AnyCert))
|
||||||
|
.with_no_client_auth();
|
||||||
|
let name =
|
||||||
|
rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?;
|
||||||
|
let tcp = tokio::net::TcpStream::connect(addr)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let tls = tokio_rustls::TlsConnector::from(Arc::new(cfg))
|
||||||
|
.connect(name, tcp)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let (_, conn) = tls.get_ref();
|
||||||
|
let leaf = conn
|
||||||
|
.peer_certificates()
|
||||||
|
.and_then(|c| c.first())
|
||||||
|
.ok_or("Caddy sent no certificate")?;
|
||||||
|
Ok::<_, String>(crate::util::sha256_hex(leaf.as_ref()))
|
||||||
|
};
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), run)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "Caddy did not finish the handshake within 5 s".to_owned())?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One health probe of an upstream, made by control while Caddy serves, with edge's rules
|
||||||
|
/// (crates/edge/src/health.rs): a host with a health check gets `GET <path>` with the upstream
|
||||||
|
/// address as Host and passes on 2xx; a host without one gets `GET /` with its own name as
|
||||||
|
/// Host and passes on any answer below 500. 5 s timeout. `kind` uses edge's words.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct UpstreamProbe {
|
||||||
|
pub ok: bool,
|
||||||
|
pub kind: Option<&'static str>,
|
||||||
|
pub status: Option<u16>,
|
||||||
|
pub latency_ms: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_kind(status: u16) -> &'static str {
|
||||||
|
match status {
|
||||||
|
300..=399 => "redirect",
|
||||||
|
401 | 403 => "sign_in",
|
||||||
|
404 => "not_found",
|
||||||
|
500..=599 => "server_error",
|
||||||
|
_ => "bad_answer",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn io_kind(e: &std::io::Error) -> &'static str {
|
||||||
|
use std::io::ErrorKind as K;
|
||||||
|
match e.kind() {
|
||||||
|
K::ConnectionRefused | K::ConnectionReset | K::ConnectionAborted | K::BrokenPipe => {
|
||||||
|
"refused"
|
||||||
|
}
|
||||||
|
K::TimedOut => "timeout",
|
||||||
|
_ if e.to_string().contains("lookup") => "name",
|
||||||
|
_ => "refused",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The roots an `https://` upstream is checked against: the system bundle (`SSL_CERT_FILE`,
|
||||||
|
/// else the usual Debian/NixOS path), read once.
|
||||||
|
fn system_roots() -> Arc<rustls::RootCertStore> {
|
||||||
|
static ROOTS: std::sync::OnceLock<Arc<rustls::RootCertStore>> = std::sync::OnceLock::new();
|
||||||
|
ROOTS
|
||||||
|
.get_or_init(|| {
|
||||||
|
let mut store = rustls::RootCertStore::empty();
|
||||||
|
let path = std::env::var("SSL_CERT_FILE")
|
||||||
|
.unwrap_or_else(|_| "/etc/ssl/certs/ca-certificates.crt".into());
|
||||||
|
if let Ok(pem) = std::fs::read_to_string(path) {
|
||||||
|
for der in ianitor_core::pki::chain_der(&pem).unwrap_or_default() {
|
||||||
|
let _ = store.add(rustls_pki_types::CertificateDer::from(der));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Arc::new(store)
|
||||||
|
})
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn probe_upstream(
|
||||||
|
u: &ianitor_core::Upstream,
|
||||||
|
path: &str,
|
||||||
|
host_header: &str,
|
||||||
|
watch_only: bool,
|
||||||
|
) -> UpstreamProbe {
|
||||||
|
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||||
|
let started = Instant::now();
|
||||||
|
let fail = |kind: &'static str| UpstreamProbe {
|
||||||
|
ok: false,
|
||||||
|
kind: Some(kind),
|
||||||
|
status: None,
|
||||||
|
latency_ms: None,
|
||||||
|
};
|
||||||
|
async fn ask<S: AsyncRead + AsyncWrite + Unpin>(
|
||||||
|
mut s: S,
|
||||||
|
req: &[u8],
|
||||||
|
) -> Result<Option<u16>, std::io::Error> {
|
||||||
|
s.write_all(req).await?;
|
||||||
|
let mut head = [0u8; 64];
|
||||||
|
let mut n = 0;
|
||||||
|
while n < 13 {
|
||||||
|
let k = s.read(&mut head[n..]).await?;
|
||||||
|
if k == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
n += k;
|
||||||
|
}
|
||||||
|
Ok(String::from_utf8_lossy(&head[..n])
|
||||||
|
.split(' ')
|
||||||
|
.nth(1)
|
||||||
|
.and_then(|x| x.parse::<u16>().ok()))
|
||||||
|
}
|
||||||
|
let req = format!(
|
||||||
|
"GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n"
|
||||||
|
);
|
||||||
|
let run = async {
|
||||||
|
let tcp = match tokio::net::TcpStream::connect(u.authority()).await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => return Err(io_kind(&e)),
|
||||||
|
};
|
||||||
|
if u.scheme == ianitor_core::Scheme::Https {
|
||||||
|
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||||
|
let Ok(b) = rustls::ClientConfig::builder_with_provider(provider)
|
||||||
|
.with_safe_default_protocol_versions()
|
||||||
|
else {
|
||||||
|
return Err("tls");
|
||||||
|
};
|
||||||
|
let cfg = b
|
||||||
|
.with_root_certificates(system_roots())
|
||||||
|
.with_no_client_auth();
|
||||||
|
let Ok(name) = rustls_pki_types::ServerName::try_from(u.host_str()) else {
|
||||||
|
return Err("name");
|
||||||
|
};
|
||||||
|
let tls = match tokio_rustls::TlsConnector::from(Arc::new(cfg))
|
||||||
|
.connect(name, tcp)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(_) => return Err("tls"),
|
||||||
|
};
|
||||||
|
ask(tls, req.as_bytes()).await.map_err(|e| io_kind(&e))
|
||||||
|
} else {
|
||||||
|
ask(tcp, req.as_bytes()).await.map_err(|e| io_kind(&e))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match tokio::time::timeout(Duration::from_secs(5), run).await {
|
||||||
|
Err(_) => fail("timeout"),
|
||||||
|
Ok(Err(kind)) => fail(kind),
|
||||||
|
Ok(Ok(None)) => fail("bad_answer"),
|
||||||
|
Ok(Ok(Some(status))) => {
|
||||||
|
let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||||
|
let ok = if watch_only {
|
||||||
|
(100..500).contains(&status)
|
||||||
|
} else {
|
||||||
|
(200..300).contains(&status)
|
||||||
|
};
|
||||||
|
UpstreamProbe {
|
||||||
|
ok,
|
||||||
|
kind: (!ok).then(|| status_kind(status)),
|
||||||
|
status: Some(status),
|
||||||
|
latency_ms: Some(latency),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,450 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! `control.toml`: where control keeps its state, the routes repository, the files it writes
|
||||||
|
//! for edge and Caddy, and the deployment facts both compilers need. Written by the NixOS
|
||||||
|
//! module; never holds a secret (secrets are credential *names* in `$CREDENTIALS_DIRECTORY`).
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use ianitor_core::compile::CompileOptions;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Config {
|
||||||
|
/// The API listens here. Only loopback addresses are accepted.
|
||||||
|
#[serde(default = "default_listen")]
|
||||||
|
pub listen: SocketAddr,
|
||||||
|
/// Extra `Host` header values the API accepts (besides the listen address, `localhost`
|
||||||
|
/// and `127.0.0.1` on its port), e.g. the admin host edge forwards to control in phase 3.
|
||||||
|
#[serde(default)]
|
||||||
|
pub allowed_hosts: Vec<String>,
|
||||||
|
/// Tokens, share links, apply records, the apply journal.
|
||||||
|
pub state_dir: PathBuf,
|
||||||
|
/// Overrides `$CREDENTIALS_DIRECTORY` (dev mode and tests only).
|
||||||
|
pub credentials_dir: Option<PathBuf>,
|
||||||
|
/// The `git` binary.
|
||||||
|
#[serde(default = "default_git")]
|
||||||
|
pub git: PathBuf,
|
||||||
|
/// How long the health watch after an apply lasts.
|
||||||
|
#[serde(default = "default_watch")]
|
||||||
|
pub watch_secs: u64,
|
||||||
|
/// How often watched hosts are probed during the watch.
|
||||||
|
#[serde(default = "default_every")]
|
||||||
|
pub watch_every_secs: u64,
|
||||||
|
/// Extra time edge waits for a confirmation after the watch before it reverts by itself.
|
||||||
|
#[serde(default = "default_margin")]
|
||||||
|
pub trial_margin_secs: u64,
|
||||||
|
/// How often control reads health from edge for the overview.
|
||||||
|
#[serde(default = "default_poll")]
|
||||||
|
pub health_poll_secs: u64,
|
||||||
|
pub routes: Routes,
|
||||||
|
pub edge: Edge,
|
||||||
|
pub caddy: Caddy,
|
||||||
|
/// Deployment facts for both compilers.
|
||||||
|
pub compile: Compile,
|
||||||
|
/// Different facts for the Caddy output (only tests need this: both engines side by side).
|
||||||
|
pub compile_caddy: Option<Compile>,
|
||||||
|
/// The Domi CA; without it `tls = "domi"` certificates are expected in `cert_dir` already
|
||||||
|
/// and the certificate screens say the CA is not set up.
|
||||||
|
#[serde(default)]
|
||||||
|
pub pki: Option<PkiConfig>,
|
||||||
|
/// The web UI behind edge (sign-in through Authelia, see docs/api.md).
|
||||||
|
#[serde(default)]
|
||||||
|
pub ui: Option<UiConfig>,
|
||||||
|
/// Switching between Pingora and the Caddy fallback at runtime.
|
||||||
|
#[serde(default)]
|
||||||
|
pub engine: Option<EngineConfig>,
|
||||||
|
/// Branch previews for Fabrica (`POST /api/v1/previews`); off without it.
|
||||||
|
#[serde(default)]
|
||||||
|
pub previews: Option<PreviewsConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `[previews]`: where branch previews live and what they may point at.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PreviewsConfig {
|
||||||
|
/// Previews are `<branch>--<project>.<domain>`; a wildcard DNS record points here.
|
||||||
|
pub domain: String,
|
||||||
|
/// `domi` (the Domi CA, internal) or `letsencrypt` (public; one certificate per preview).
|
||||||
|
#[serde(default = "default_preview_tls")]
|
||||||
|
pub tls: String,
|
||||||
|
/// `none` (anyone with the address) or `forward-auth` (behind the site's sign-in).
|
||||||
|
#[serde(default = "default_preview_auth")]
|
||||||
|
pub auth: String,
|
||||||
|
/// Where previews may send traffic: `10.0.0.0/8`, `127.0.0.1:20000-29999`, `app.internal`,
|
||||||
|
/// `*.svc.internal:8080`. Nothing else is accepted; control's own port and Caddy's admin
|
||||||
|
/// port never are. Empty: every preview is refused.
|
||||||
|
#[serde(default)]
|
||||||
|
pub upstreams: Vec<String>,
|
||||||
|
#[serde(default = "default_preview_ttl")]
|
||||||
|
pub default_ttl_secs: u64,
|
||||||
|
#[serde(default = "default_preview_min_ttl")]
|
||||||
|
pub min_ttl_secs: u64,
|
||||||
|
#[serde(default = "default_preview_max_ttl")]
|
||||||
|
pub max_ttl_secs: u64,
|
||||||
|
#[serde(default = "default_preview_max")]
|
||||||
|
pub max_previews: usize,
|
||||||
|
/// How often expired previews are looked for.
|
||||||
|
#[serde(default = "default_preview_sweep")]
|
||||||
|
pub sweep_secs: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_preview_tls() -> String {
|
||||||
|
"domi".into()
|
||||||
|
}
|
||||||
|
fn default_preview_auth() -> String {
|
||||||
|
"none".into()
|
||||||
|
}
|
||||||
|
fn default_preview_ttl() -> u64 {
|
||||||
|
72 * 3600
|
||||||
|
}
|
||||||
|
fn default_preview_min_ttl() -> u64 {
|
||||||
|
300
|
||||||
|
}
|
||||||
|
fn default_preview_max_ttl() -> u64 {
|
||||||
|
30 * 86_400
|
||||||
|
}
|
||||||
|
fn default_preview_max() -> usize {
|
||||||
|
100
|
||||||
|
}
|
||||||
|
fn default_preview_sweep() -> u64 {
|
||||||
|
30
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Routes {
|
||||||
|
/// The routes repository (bare). Created with an empty `ianitor.toml` when missing.
|
||||||
|
pub repo: PathBuf,
|
||||||
|
#[serde(default = "default_branch")]
|
||||||
|
pub branch: String,
|
||||||
|
/// Where kept changes are pushed (a URL or a path); none means no push.
|
||||||
|
pub remote: Option<String>,
|
||||||
|
/// Shown in the UI ("Last pushed to <name>").
|
||||||
|
#[serde(default = "default_remote_name")]
|
||||||
|
pub remote_name: String,
|
||||||
|
/// User name for HTTPS pushes.
|
||||||
|
#[serde(default = "default_push_user")]
|
||||||
|
pub push_username: String,
|
||||||
|
/// Credential (file name in `$CREDENTIALS_DIRECTORY`) holding the push password or token.
|
||||||
|
pub push_credential: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Edge {
|
||||||
|
/// The edge config file; only ever holds a config that passed its watch.
|
||||||
|
pub config: PathBuf,
|
||||||
|
/// The trial file edge loads during an apply (default `<config>.trial`).
|
||||||
|
pub trial: Option<PathBuf>,
|
||||||
|
/// Edge's admin socket; without it control applies without reload or health watch
|
||||||
|
/// (dev mode without an edge).
|
||||||
|
pub admin_socket: Option<PathBuf>,
|
||||||
|
/// The share-link revocation file edge reads.
|
||||||
|
pub share_revocations: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Caddy {
|
||||||
|
/// The Caddy JSON the caddy-fallback unit reads.
|
||||||
|
pub config: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Compile {
|
||||||
|
pub http_listen: SocketAddr,
|
||||||
|
pub https_listen: SocketAddr,
|
||||||
|
pub cert_dir: String,
|
||||||
|
pub state_dir: String,
|
||||||
|
pub access_log: String,
|
||||||
|
pub caddy_credentials_dir: String,
|
||||||
|
pub caddy_admin: Option<SocketAddr>,
|
||||||
|
/// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves.
|
||||||
|
#[serde(default)]
|
||||||
|
pub caddy_admin_socket: Option<String>,
|
||||||
|
/// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy).
|
||||||
|
#[serde(default)]
|
||||||
|
pub trusted_proxies: Vec<std::net::IpAddr>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Compile {
|
||||||
|
pub fn options(&self) -> CompileOptions {
|
||||||
|
use ianitor_core::compile::windows_path as w;
|
||||||
|
CompileOptions {
|
||||||
|
http_listen: self.http_listen,
|
||||||
|
https_listen: self.https_listen,
|
||||||
|
cert_dir: w(&self.cert_dir),
|
||||||
|
state_dir: w(&self.state_dir),
|
||||||
|
access_log: w(&self.access_log),
|
||||||
|
caddy_credentials_dir: w(&self.caddy_credentials_dir),
|
||||||
|
caddy_admin: self.caddy_admin,
|
||||||
|
caddy_admin_socket: self.caddy_admin_socket.clone(),
|
||||||
|
trusted_proxies: self.trusted_proxies.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_listen() -> SocketAddr {
|
||||||
|
SocketAddr::from(([127, 0, 0, 1], 7878))
|
||||||
|
}
|
||||||
|
fn default_git() -> PathBuf {
|
||||||
|
PathBuf::from("git")
|
||||||
|
}
|
||||||
|
fn default_watch() -> u64 {
|
||||||
|
60
|
||||||
|
}
|
||||||
|
fn default_every() -> u64 {
|
||||||
|
5
|
||||||
|
}
|
||||||
|
fn default_margin() -> u64 {
|
||||||
|
30
|
||||||
|
}
|
||||||
|
fn default_poll() -> u64 {
|
||||||
|
2
|
||||||
|
}
|
||||||
|
fn default_branch() -> String {
|
||||||
|
"main".into()
|
||||||
|
}
|
||||||
|
fn default_remote_name() -> String {
|
||||||
|
"Gitea".into()
|
||||||
|
}
|
||||||
|
fn default_push_user() -> String {
|
||||||
|
"ianitor".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
#[error("cannot read {path}: {source}")]
|
||||||
|
Read {
|
||||||
|
path: PathBuf,
|
||||||
|
source: std::io::Error,
|
||||||
|
},
|
||||||
|
#[error("{path} is not a valid control config: {message}")]
|
||||||
|
Parse { path: PathBuf, message: String },
|
||||||
|
#[error("control config: {0}")]
|
||||||
|
Invalid(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
pub fn load(path: &Path) -> Result<Config, ConfigError> {
|
||||||
|
let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
|
||||||
|
path: path.to_owned(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
let c: Config = toml::from_str(&text).map_err(|e| ConfigError::Parse {
|
||||||
|
path: path.to_owned(),
|
||||||
|
message: e.message().to_owned(),
|
||||||
|
})?;
|
||||||
|
c.check()?;
|
||||||
|
Ok(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check(&self) -> Result<(), ConfigError> {
|
||||||
|
if !self.listen.ip().is_loopback() {
|
||||||
|
return Err(ConfigError::Invalid(format!(
|
||||||
|
"listen = {} is not a loopback address; ianitor-control only listens on 127.0.0.1 or ::1",
|
||||||
|
self.listen
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if !(1..=3600).contains(&self.watch_secs) {
|
||||||
|
return Err(ConfigError::Invalid("watch_secs must be 1 to 3600".into()));
|
||||||
|
}
|
||||||
|
if !(1..=60).contains(&self.watch_every_secs)
|
||||||
|
|| !(1..=600).contains(&self.trial_margin_secs)
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"watch_every_secs must be 1 to 60 and trial_margin_secs 1 to 600".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if self.routes.branch.is_empty()
|
||||||
|
|| !self
|
||||||
|
.routes
|
||||||
|
.branch
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c))
|
||||||
|
|| self.routes.branch.starts_with(['-', '.', '/'])
|
||||||
|
|| self.routes.branch.contains("..")
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"routes.branch is not a plain branch name".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(r) = &self.routes.remote
|
||||||
|
&& (r.starts_with('-') || r.is_empty())
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid("routes.remote is not usable".into()));
|
||||||
|
}
|
||||||
|
if let Some(c) = &self.routes.push_credential
|
||||||
|
&& !valid_credential_name(c)
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"routes.push_credential must be a plain credential name".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// The keys at rest are only as strong as this; only test builds may lower it.
|
||||||
|
if let Some(p) = &self.pki
|
||||||
|
&& p.kdf_iterations < MIN_KDF_ITERATIONS
|
||||||
|
&& !cfg!(feature = "test-hooks")
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid(format!(
|
||||||
|
"pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if let Some(p) = &self.previews {
|
||||||
|
crate::previews::check_config(p, self).map_err(ConfigError::Invalid)?;
|
||||||
|
}
|
||||||
|
if let Some(m) = empty_model() {
|
||||||
|
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
|
||||||
|
ianitor_core::compile::edge(&m, &c.options())
|
||||||
|
.map_err(|e| ConfigError::Invalid(e.to_string()))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn trial_path(&self) -> PathBuf {
|
||||||
|
self.edge
|
||||||
|
.trial
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| suffixed(&self.edge.config, ".trial"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn caddy_trial_path(&self) -> PathBuf {
|
||||||
|
suffixed(&self.caddy.config, ".trial")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn caddy_compile(&self) -> &Compile {
|
||||||
|
self.compile_caddy.as_ref().unwrap_or(&self.compile)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn credentials_dir(&self) -> Option<PathBuf> {
|
||||||
|
self.credentials_dir
|
||||||
|
.clone()
|
||||||
|
.or_else(|| std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read a credential by name (trailing newline dropped). Never logged.
|
||||||
|
pub fn credential(&self, name: &str) -> Option<Vec<u8>> {
|
||||||
|
if !valid_credential_name(name) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let raw = std::fs::read(self.credentials_dir()?.join(name)).ok()?;
|
||||||
|
let t = raw
|
||||||
|
.strip_suffix(b"\r\n")
|
||||||
|
.or_else(|| raw.strip_suffix(b"\n"))
|
||||||
|
.unwrap_or(&raw);
|
||||||
|
(!t.is_empty()).then(|| t.to_vec())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn valid_credential_name(n: &str) -> bool {
|
||||||
|
!n.is_empty()
|
||||||
|
&& n.len() <= 64
|
||||||
|
&& n.bytes()
|
||||||
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_' || c == b'-')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn suffixed(p: &Path, suffix: &str) -> PathBuf {
|
||||||
|
let mut name = p.file_name().unwrap_or_default().to_os_string();
|
||||||
|
name.push(suffix);
|
||||||
|
p.with_file_name(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn empty_model() -> Option<ianitor_core::Model> {
|
||||||
|
ianitor_core::load(
|
||||||
|
&ianitor_core::SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
},
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The PBKDF2 floor for keys at rest (OWASP 2023 for PBKDF2-HMAC-SHA256).
|
||||||
|
pub const MIN_KDF_ITERATIONS: u32 = 600_000;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PkiConfig {
|
||||||
|
/// The Domi root certificate (public; may be a Nix store path). The root key is never on
|
||||||
|
/// the server.
|
||||||
|
pub root_cert: PathBuf,
|
||||||
|
/// Credential with the password that encrypts the intermediate and device keys at rest.
|
||||||
|
#[serde(default = "default_pki_password")]
|
||||||
|
pub password_credential: String,
|
||||||
|
/// How requests are approved: `manual` (`ianitor-control pki approve <code>` on the
|
||||||
|
/// server) until Custos can (docs/custos-ticket.md).
|
||||||
|
#[serde(default = "default_approval")]
|
||||||
|
pub approval: String,
|
||||||
|
/// PBKDF2 iterations for the keys control encrypts (only tests lower it).
|
||||||
|
#[serde(default = "default_kdf")]
|
||||||
|
pub kdf_iterations: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct UiConfig {
|
||||||
|
/// The admin host edge serves the UI on (a host in the routes repository with
|
||||||
|
/// `auth = "forward-auth"`, upstream this API, and the proof header rule). Added to
|
||||||
|
/// `allowed_hosts`; used for device install links.
|
||||||
|
pub hostname: Option<String>,
|
||||||
|
/// Credential holding the per-boot secret edge adds as `X-Ianitor-Proof` on the admin
|
||||||
|
/// host. With it, a request carrying the proof is identified by its `Remote-User`.
|
||||||
|
pub proof_credential: Option<String>,
|
||||||
|
/// The built web UI (served at `/`).
|
||||||
|
pub static_dir: Option<PathBuf>,
|
||||||
|
/// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out".
|
||||||
|
#[serde(default)]
|
||||||
|
pub logout_url: Option<String>,
|
||||||
|
/// Without Authelia (T4): control keeps the admin host in the routes repository itself,
|
||||||
|
/// as a plain host to this API with this certificate (`letsencrypt` or `domi`); people
|
||||||
|
/// sign in with team links (crate::team). Unset: the admin host is managed by hand
|
||||||
|
/// (the NixOS module's Authelia setup).
|
||||||
|
#[serde(default)]
|
||||||
|
pub admin_tls: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EngineConfig {
|
||||||
|
/// Which engine runs at boot: `pingora` or `caddy` (read by the engine-select unit).
|
||||||
|
pub file: PathBuf,
|
||||||
|
/// `systemctl` (through the polkit rule for exactly the two units) or `none`.
|
||||||
|
#[serde(default = "default_units")]
|
||||||
|
pub units: String,
|
||||||
|
#[serde(default = "default_systemctl")]
|
||||||
|
pub systemctl: PathBuf,
|
||||||
|
#[serde(default = "default_edge_unit")]
|
||||||
|
pub edge_unit: String,
|
||||||
|
#[serde(default = "default_caddy_unit")]
|
||||||
|
pub caddy_unit: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_pki_password() -> String {
|
||||||
|
"pki-password".into()
|
||||||
|
}
|
||||||
|
fn default_approval() -> String {
|
||||||
|
"manual".into()
|
||||||
|
}
|
||||||
|
fn default_kdf() -> u32 {
|
||||||
|
ianitor_core::pki::KEY_KDF_ITERATIONS
|
||||||
|
}
|
||||||
|
fn default_units() -> String {
|
||||||
|
"systemctl".into()
|
||||||
|
}
|
||||||
|
fn default_systemctl() -> PathBuf {
|
||||||
|
PathBuf::from("systemctl")
|
||||||
|
}
|
||||||
|
fn default_edge_unit() -> String {
|
||||||
|
"ianitor-edge.service".into()
|
||||||
|
}
|
||||||
|
fn default_caddy_unit() -> String {
|
||||||
|
"caddy-fallback.service".into()
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Crash points for the crash-safety tests: with `IANITOR_TEST_CRASH_AT=<stage>` in its
|
||||||
|
//! environment, control exits at once with status 134 (no cleanup in Ianitor's code, like a
|
||||||
|
//! kill -9) when an apply reaches that stage. It does not raise SIGABRT: a signal would make
|
||||||
|
//! the kernel log a register dump per crash test and could hand the process to the host's
|
||||||
|
//! core-dump handler, and the tests must not reach into the host's systemd.
|
||||||
|
//!
|
||||||
|
//! `IANITOR_TEST_FAIL_WRITE=<file name>` makes every write of a state file with that name
|
||||||
|
//! fail, as on a full disk (fault injection for the same tests).
|
||||||
|
//!
|
||||||
|
//! Both exist only with the `test-hooks` cargo feature (on by default, so `cargo test` has
|
||||||
|
//! them). The release build (`nix build .#ianitor`) is built with `--no-default-features`:
|
||||||
|
//! there these functions do nothing and read no environment variable.
|
||||||
|
|
||||||
|
/// The stages, in order.
|
||||||
|
pub const STAGES: [&str; 9] = [
|
||||||
|
"prepared",
|
||||||
|
"committed",
|
||||||
|
"trial_written",
|
||||||
|
"trial_loaded",
|
||||||
|
"watching",
|
||||||
|
"watched",
|
||||||
|
"confirmed",
|
||||||
|
"promoted",
|
||||||
|
"reverting",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Whether this binary has the test hooks.
|
||||||
|
pub const ENABLED: bool = cfg!(feature = "test-hooks");
|
||||||
|
|
||||||
|
#[cfg(feature = "test-hooks")]
|
||||||
|
pub fn point(stage: &str) {
|
||||||
|
if std::env::var("IANITOR_TEST_CRASH_AT").as_deref() == Ok(stage) {
|
||||||
|
log::error!(target: "ianitor::crash", "IANITOR_TEST_CRASH_AT={stage}: exiting on purpose");
|
||||||
|
std::process::exit(134);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "test-hooks"))]
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn point(_stage: &str) {}
|
||||||
|
|
||||||
|
/// Fail a state-file write when `IANITOR_TEST_FAIL_WRITE` names this file.
|
||||||
|
#[cfg(feature = "test-hooks")]
|
||||||
|
pub fn fail_write(path: &std::path::Path) -> Result<(), String> {
|
||||||
|
match (
|
||||||
|
std::env::var_os("IANITOR_TEST_FAIL_WRITE"),
|
||||||
|
path.file_name(),
|
||||||
|
) {
|
||||||
|
(Some(want), Some(name)) if want == name => Err(format!(
|
||||||
|
"cannot write {}: IANITOR_TEST_FAIL_WRITE (injected)",
|
||||||
|
path.display()
|
||||||
|
)),
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "test-hooks"))]
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn fail_write(_path: &std::path::Path) -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! `ianitor-control --dev`: everything temporary, on 127.0.0.1. A fresh routes repository, a
|
||||||
|
//! state directory, a share-link key and one API token printed once. If an `ianitor-edge`
|
||||||
|
//! binary is found (`--edge-bin`, `$IANITOR_EDGE_BIN`, or next to this binary), it runs as
|
||||||
|
//! the dev proxy on 127.0.0.1:18080/18443 with an admin socket, so applies are loaded and
|
||||||
|
//! watched for real; otherwise applies are only written. Everything is removed on Ctrl-C.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Child, Command, Stdio};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes};
|
||||||
|
use ianitor_control::repo::Repo;
|
||||||
|
use ianitor_control::tokens::Tokens;
|
||||||
|
use ianitor_control::util::{hex, random, write_atomic};
|
||||||
|
|
||||||
|
/// A throw-away Domi root for dev mode, in `offline-root/` (its key stays in memory, like
|
||||||
|
/// on the offline machine), and the PKI password credential. Control then works like
|
||||||
|
/// production: it issues server certificates for every `tls = "domi"` host.
|
||||||
|
fn dev_pki(dir: &Path) -> Result<(String, ianitor_core::pki::KeyPair), String> {
|
||||||
|
let (root, key) = ianitor_core::pki::create_root(ianitor_control::util::now() as i64)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
std::fs::write(dir.join("offline-root/domi-root.crt"), &root).map_err(|e| e.to_string())?;
|
||||||
|
let pass = hex(&random::<24>().map_err(|e| e.to_string())?);
|
||||||
|
write_atomic(&dir.join("creds/pki-password"), pass.as_bytes(), 0o600)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok((root, key))
|
||||||
|
}
|
||||||
|
|
||||||
|
const SITE: &str = "# Dev site settings. Sign-in goes to an Authelia that may not run here.\n\
|
||||||
|
[forward_auth]\nurl = \"http://127.0.0.1:9091/api/authz/forward-auth\"\n";
|
||||||
|
|
||||||
|
struct Cleanup {
|
||||||
|
dir: PathBuf,
|
||||||
|
edge: Option<Child>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Cleanup {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(c) = &mut self.edge {
|
||||||
|
let _ = c.kill();
|
||||||
|
let _ = c.wait();
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_dir_all(&self.dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_edge(args: &[String]) -> Option<PathBuf> {
|
||||||
|
let mut it = args.iter();
|
||||||
|
while let Some(a) = it.next() {
|
||||||
|
if a == "--edge-bin" {
|
||||||
|
return it.next().map(PathBuf::from);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(p) = std::env::var_os("IANITOR_EDGE_BIN") {
|
||||||
|
return Some(PathBuf::from(p));
|
||||||
|
}
|
||||||
|
let me = std::env::current_exe().ok()?;
|
||||||
|
let sibling = me.with_file_name(if cfg!(windows) {
|
||||||
|
"ianitor-edge.exe"
|
||||||
|
} else {
|
||||||
|
"ianitor-edge"
|
||||||
|
});
|
||||||
|
sibling.is_file().then_some(sibling)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn arg(args: &[String], name: &str) -> Option<String> {
|
||||||
|
let mut it = args.iter();
|
||||||
|
while let Some(a) = it.next() {
|
||||||
|
if a == name {
|
||||||
|
return it.next().cloned();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(args: &[String]) -> Result<(), String> {
|
||||||
|
let listen: SocketAddr = arg(args, "--listen")
|
||||||
|
.unwrap_or_else(|| "127.0.0.1:7878".into())
|
||||||
|
.parse()
|
||||||
|
.map_err(|_| "--listen must be an address like 127.0.0.1:7878")?;
|
||||||
|
if !listen.ip().is_loopback() {
|
||||||
|
return Err("--dev listens on loopback only".into());
|
||||||
|
}
|
||||||
|
let dir = std::env::temp_dir().join(format!("ianitor-dev-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
let mut cleanup = Cleanup {
|
||||||
|
dir: dir.clone(),
|
||||||
|
edge: None,
|
||||||
|
};
|
||||||
|
for d in [
|
||||||
|
"state",
|
||||||
|
"edge",
|
||||||
|
"caddy",
|
||||||
|
"certs",
|
||||||
|
"creds",
|
||||||
|
"logs",
|
||||||
|
"edge-state",
|
||||||
|
"offline-root",
|
||||||
|
] {
|
||||||
|
std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
let (root_pem, root_key) = dev_pki(&dir)?;
|
||||||
|
let key = hex(&random::<32>().map_err(|e| e.to_string())?);
|
||||||
|
write_atomic(&dir.join("creds/share-link-key"), key.as_bytes(), 0o600)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let edge_bin = if cfg!(unix) { find_edge(args) } else { None };
|
||||||
|
let s = |p: &str| dir.join(p).to_string_lossy().into_owned();
|
||||||
|
let cfg = Config {
|
||||||
|
listen,
|
||||||
|
allowed_hosts: Vec::new(),
|
||||||
|
state_dir: dir.join("state"),
|
||||||
|
credentials_dir: Some(dir.join("creds")),
|
||||||
|
git: PathBuf::from("git"),
|
||||||
|
watch_secs: arg(args, "--watch-secs")
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(10),
|
||||||
|
watch_every_secs: 2,
|
||||||
|
trial_margin_secs: 20,
|
||||||
|
health_poll_secs: 2,
|
||||||
|
routes: Routes {
|
||||||
|
repo: dir.join("routes.git"),
|
||||||
|
branch: "main".into(),
|
||||||
|
remote: None,
|
||||||
|
remote_name: "Gitea".into(),
|
||||||
|
push_username: "ianitor".into(),
|
||||||
|
push_credential: None,
|
||||||
|
},
|
||||||
|
edge: Edge {
|
||||||
|
config: dir.join("edge/edge.json"),
|
||||||
|
trial: None,
|
||||||
|
admin_socket: edge_bin.as_ref().map(|_| dir.join("edge/admin.sock")),
|
||||||
|
share_revocations: dir.join("edge/share-revocations.json"),
|
||||||
|
},
|
||||||
|
caddy: Caddy {
|
||||||
|
config: dir.join("caddy/caddy.json"),
|
||||||
|
},
|
||||||
|
compile: Compile {
|
||||||
|
http_listen: "127.0.0.1:18080".parse().map_err(|_| "bad address")?,
|
||||||
|
https_listen: "127.0.0.1:18443".parse().map_err(|_| "bad address")?,
|
||||||
|
cert_dir: s("certs"),
|
||||||
|
state_dir: s("edge-state"),
|
||||||
|
access_log: s("logs/access.log"),
|
||||||
|
caddy_credentials_dir: s("creds"),
|
||||||
|
caddy_admin: None,
|
||||||
|
caddy_admin_socket: None,
|
||||||
|
trusted_proxies: Vec::new(),
|
||||||
|
},
|
||||||
|
compile_caddy: None,
|
||||||
|
pki: Some(ianitor_control::config::PkiConfig {
|
||||||
|
root_cert: dir.join("offline-root/domi-root.crt"),
|
||||||
|
password_credential: "pki-password".into(),
|
||||||
|
approval: "manual".into(),
|
||||||
|
// Fast in test builds; the real floor in a release build.
|
||||||
|
kdf_iterations: if cfg!(feature = "test-hooks") {
|
||||||
|
10_000
|
||||||
|
} else {
|
||||||
|
ianitor_control::config::MIN_KDF_ITERATIONS
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
ui: arg(args, "--ui-dir").map(|d| ianitor_control::config::UiConfig {
|
||||||
|
hostname: None,
|
||||||
|
proof_credential: None,
|
||||||
|
static_dir: Some(PathBuf::from(d)),
|
||||||
|
logout_url: None,
|
||||||
|
admin_tls: None,
|
||||||
|
}),
|
||||||
|
engine: None,
|
||||||
|
// Branch previews on a name nobody can own (RFC 2606), from loopback test upstreams.
|
||||||
|
previews: Some(ianitor_control::config::PreviewsConfig {
|
||||||
|
domain: "preview.dev.test".into(),
|
||||||
|
tls: "domi".into(),
|
||||||
|
auth: "none".into(),
|
||||||
|
upstreams: vec!["127.0.0.1:20000-29999".into(), "10.0.0.0/8".into()],
|
||||||
|
default_ttl_secs: 72 * 3600,
|
||||||
|
min_ttl_secs: 60,
|
||||||
|
max_ttl_secs: 30 * 86_400,
|
||||||
|
max_previews: 100,
|
||||||
|
sweep_secs: 10,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
cfg.check().map_err(|e| e.to_string())?;
|
||||||
|
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None, Default::default())?;
|
||||||
|
|
||||||
|
// Control writes edge.json first; then edge can start from it.
|
||||||
|
let ctl_cfg = cfg.clone();
|
||||||
|
let opened = ianitor_control::Control::open(ctl_cfg).await?;
|
||||||
|
// Dev only: sign the first intermediate with the throw-away root at once (in production
|
||||||
|
// this is the offline step in docs/pki.md).
|
||||||
|
if let Some(p) = &opened.pki {
|
||||||
|
let now = ianitor_control::util::now();
|
||||||
|
let r = p.request_renewal(now, "dev").map_err(|e| e.to_string())?;
|
||||||
|
let signed = ianitor_core::pki::sign_intermediate(
|
||||||
|
&root_pem,
|
||||||
|
&root_key,
|
||||||
|
r.csr_pem.as_deref().unwrap_or_default(),
|
||||||
|
now as i64,
|
||||||
|
)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
p.install_intermediate(&r.id, &signed, now)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
drop(opened);
|
||||||
|
if let Some(bin) = &edge_bin {
|
||||||
|
cleanup.edge = Some(start_edge(bin, &dir, &cfg)?);
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("Ianitor control (dev) on http://{listen}/api/v1");
|
||||||
|
println!("Routes repository: {}", cfg.routes.repo.display());
|
||||||
|
match &edge_bin {
|
||||||
|
Some(b) => println!(
|
||||||
|
"Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080). tls = \"domi\" works for any name; Domi root: {}",
|
||||||
|
b.display(),
|
||||||
|
dir.join("offline-root/domi-root.crt").display()
|
||||||
|
),
|
||||||
|
None => println!(
|
||||||
|
"No ianitor-edge found: applies are written but not loaded or watched (use --edge-bin)."
|
||||||
|
),
|
||||||
|
}
|
||||||
|
println!("API token (shown once): {token}");
|
||||||
|
println!(
|
||||||
|
"Approve a device request: ianitor-control pki approve <code> --state-dir {}",
|
||||||
|
dir.join("state").display()
|
||||||
|
);
|
||||||
|
println!("Press Ctrl-C to stop and remove {}", dir.display());
|
||||||
|
let r = ianitor_control::serve(cfg, ianitor_control::stop_signal()).await;
|
||||||
|
drop(cleanup);
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_edge(bin: &Path, dir: &Path, cfg: &Config) -> Result<Child, String> {
|
||||||
|
let log = std::fs::File::create(dir.join("logs/edge.log")).map_err(|e| e.to_string())?;
|
||||||
|
let log2 = log.try_clone().map_err(|e| e.to_string())?;
|
||||||
|
let child = Command::new(bin)
|
||||||
|
.arg("--config")
|
||||||
|
.arg(&cfg.edge.config)
|
||||||
|
.arg("--admin-socket")
|
||||||
|
.arg(dir.join("edge/admin.sock"))
|
||||||
|
.arg("--share-revocations")
|
||||||
|
.arg(&cfg.edge.share_revocations)
|
||||||
|
.env("CREDENTIALS_DIRECTORY", dir.join("creds"))
|
||||||
|
.stdout(Stdio::from(log))
|
||||||
|
.stderr(Stdio::from(log2))
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| format!("cannot start {}: {e}", bin.display()))?;
|
||||||
|
let sock = dir.join("edge/admin.sock");
|
||||||
|
for _ in 0..100 {
|
||||||
|
if sock.exists() {
|
||||||
|
return Ok(child);
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
Err(format!(
|
||||||
|
"the dev proxy did not start; see {}",
|
||||||
|
dir.join("logs/edge.log").display()
|
||||||
|
))
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Control's side of edge's admin socket (see `ianitor_edge::admin`).
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum EdgeLinkError {
|
||||||
|
/// Edge did not answer (not running, socket missing, timeout).
|
||||||
|
#[error("edge cannot be reached: {0}")]
|
||||||
|
Unreachable(String),
|
||||||
|
/// Edge answered with an error.
|
||||||
|
#[error("{message}")]
|
||||||
|
Refused { status: u16, message: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One probe result as edge reports it.
|
||||||
|
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||||
|
pub struct Check {
|
||||||
|
pub seq: u64,
|
||||||
|
pub at: u64,
|
||||||
|
pub ok: bool,
|
||||||
|
pub source: String,
|
||||||
|
pub kind: Option<String>,
|
||||||
|
pub status: Option<u16>,
|
||||||
|
pub latency_ms: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct UpstreamStatus {
|
||||||
|
pub address: String,
|
||||||
|
pub healthy: bool,
|
||||||
|
pub checks: Vec<Check>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct CertStatus {
|
||||||
|
pub state: String,
|
||||||
|
pub not_after: Option<i64>,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct HostStatus {
|
||||||
|
pub hostname: String,
|
||||||
|
pub health_check: bool,
|
||||||
|
pub upstreams: Vec<UpstreamStatus>,
|
||||||
|
pub certificate: CertStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct TrialStatus {
|
||||||
|
pub config_sha256: String,
|
||||||
|
pub seconds_left: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct EdgeStatus {
|
||||||
|
pub generation: u64,
|
||||||
|
pub config_sha256: String,
|
||||||
|
pub started_at: u64,
|
||||||
|
pub trial: Option<TrialStatus>,
|
||||||
|
pub hosts: Vec<HostStatus>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How control reaches edge. `None` in dev mode without an edge: applies are written but
|
||||||
|
/// not loaded or watched.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum EdgeLink {
|
||||||
|
Unix(PathBuf),
|
||||||
|
None,
|
||||||
|
}
|
||||||
|
|
||||||
|
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||||
|
|
||||||
|
impl EdgeLink {
|
||||||
|
pub fn attached(&self) -> bool {
|
||||||
|
matches!(self, EdgeLink::Unix(_))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call(
|
||||||
|
&self,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
body: Option<Value>,
|
||||||
|
) -> Result<Value, EdgeLinkError> {
|
||||||
|
let EdgeLink::Unix(socket) = self else {
|
||||||
|
return Err(EdgeLinkError::Unreachable("no edge is attached".into()));
|
||||||
|
};
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
let body = body.map(|b| b.to_string()).unwrap_or_default();
|
||||||
|
let req = format!(
|
||||||
|
"{method} {path} HTTP/1.1\r\nHost: edge\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
);
|
||||||
|
let exchange = async {
|
||||||
|
let mut s = tokio::net::UnixStream::connect(socket).await?;
|
||||||
|
s.write_all(req.as_bytes()).await?;
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
s.read_to_end(&mut buf).await?;
|
||||||
|
Ok::<_, std::io::Error>(buf)
|
||||||
|
};
|
||||||
|
let buf = tokio::time::timeout(TIMEOUT, exchange)
|
||||||
|
.await
|
||||||
|
.map_err(|_| EdgeLinkError::Unreachable("no answer within 10 s".into()))?
|
||||||
|
.map_err(|e| EdgeLinkError::Unreachable(e.to_string()))?;
|
||||||
|
let (status, json) = parse(&buf).map_err(EdgeLinkError::Unreachable)?;
|
||||||
|
if (200..300).contains(&status) {
|
||||||
|
Ok(json)
|
||||||
|
} else {
|
||||||
|
Err(EdgeLinkError::Refused {
|
||||||
|
status,
|
||||||
|
message: json["error"].as_str().unwrap_or("edge refused").to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
{
|
||||||
|
let _ = (socket, method, path, body);
|
||||||
|
Err(EdgeLinkError::Unreachable(
|
||||||
|
"the admin socket needs Unix".into(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn status(&self) -> Result<EdgeStatus, EdgeLinkError> {
|
||||||
|
let v = self.call("GET", "/v1/status", None).await?;
|
||||||
|
serde_json::from_value(v)
|
||||||
|
.map_err(|e| EdgeLinkError::Unreachable(format!("odd status: {e}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load the trial file; returns its SHA-256 as edge computed it.
|
||||||
|
pub async fn trial(
|
||||||
|
&self,
|
||||||
|
confirm_within: u64,
|
||||||
|
watch_hosts: &[String],
|
||||||
|
every: u64,
|
||||||
|
) -> Result<String, EdgeLinkError> {
|
||||||
|
let v = self
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/v1/trial",
|
||||||
|
Some(json!({
|
||||||
|
"confirm_within_secs": confirm_within,
|
||||||
|
"watch_hosts": watch_hosts,
|
||||||
|
"watch_every_secs": every,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn confirm(&self, sha: &str) -> Result<(), EdgeLinkError> {
|
||||||
|
self.call("POST", "/v1/confirm", Some(json!({ "config_sha256": sha })))
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn abort(&self) -> Result<bool, EdgeLinkError> {
|
||||||
|
let v = self.call("POST", "/v1/abort", None).await?;
|
||||||
|
Ok(v["reverted"].as_bool().unwrap_or(false))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reload(&self) -> Result<String, EdgeLinkError> {
|
||||||
|
let v = self.call("POST", "/v1/reload", None).await?;
|
||||||
|
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-read the device CA bundle and allow list (works during a trial too).
|
||||||
|
pub async fn reload_devices(&self) -> Result<(), EdgeLinkError> {
|
||||||
|
self.call("POST", "/v1/device-certs/reload", None)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reload_revocations(&self) -> Result<(), EdgeLinkError> {
|
||||||
|
self.call("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn acme_retry(&self) -> Result<(), EdgeLinkError> {
|
||||||
|
self.call("POST", "/v1/acme/retry", None).await.map(|_| ())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse(raw: &[u8]) -> Result<(u16, Value), String> {
|
||||||
|
let end = raw
|
||||||
|
.windows(4)
|
||||||
|
.position(|w| w == b"\r\n\r\n")
|
||||||
|
.ok_or("no complete answer from edge")?;
|
||||||
|
let head = String::from_utf8_lossy(&raw[..end]);
|
||||||
|
let status: u16 = head
|
||||||
|
.split(' ')
|
||||||
|
.nth(1)
|
||||||
|
.and_then(|s| s.parse().ok())
|
||||||
|
.ok_or("no status from edge")?;
|
||||||
|
let chunked = head
|
||||||
|
.to_ascii_lowercase()
|
||||||
|
.contains("transfer-encoding: chunked");
|
||||||
|
let mut body = raw[end + 4..].to_vec();
|
||||||
|
if chunked {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut rest = &body[..];
|
||||||
|
while let Some(p) = rest.windows(2).position(|w| w == b"\r\n") {
|
||||||
|
let size = usize::from_str_radix(String::from_utf8_lossy(&rest[..p]).trim(), 16)
|
||||||
|
.map_err(|_| "odd chunk from edge")?;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
let json = serde_json::from_slice(&body).unwrap_or(Value::Null);
|
||||||
|
Ok((status, json))
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,463 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Applies while Caddy serves (Mark, 2026-11-08: changes keep working under Caddy). The same
|
||||||
|
//! pipeline and journal as with edge; only the trial, the watch and the revert differ:
|
||||||
|
//!
|
||||||
|
//! - the trial is loaded into Caddy through its admin socket, after its deadline is armed
|
||||||
|
//! (crate::caddy_guard: a crashed or hung control cannot leave it serving);
|
||||||
|
//! - the watch judges health the way edge does (QC round 2, M1): control probes the upstreams
|
||||||
|
//! itself with edge's rules, and the probe *through* Caddy only asks whether Caddy answers
|
||||||
|
//! at all (any status counts, also its auth redirect, 401, 403 or 421);
|
||||||
|
//! - every round checks that Caddy still runs the trial (M2: a reload by anyone else drops it);
|
||||||
|
//! - a revert loads caddy.json (the last good config) again; a confirm claims the deadline,
|
||||||
|
//! then promotes, loads caddy.json and checks that Caddy runs it.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::caddy_guard;
|
||||||
|
use crate::caddy_link::{self, Probe};
|
||||||
|
|
||||||
|
/// Where control reaches Caddy's HTTPS listener (its own machine).
|
||||||
|
fn local(addr: SocketAddr) -> SocketAddr {
|
||||||
|
if addr.ip().is_unspecified() {
|
||||||
|
let ip: std::net::IpAddr = if addr.is_ipv6() {
|
||||||
|
std::net::Ipv6Addr::LOCALHOST.into()
|
||||||
|
} else {
|
||||||
|
std::net::Ipv4Addr::LOCALHOST.into()
|
||||||
|
};
|
||||||
|
SocketAddr::new(ip, addr.port())
|
||||||
|
} else {
|
||||||
|
addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How one host is probed (edge's rules, crates/edge/src/health.rs).
|
||||||
|
struct Rule {
|
||||||
|
upstreams: Vec<ianitor_core::Upstream>,
|
||||||
|
path: String,
|
||||||
|
has_check: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Control {
|
||||||
|
/// Caddy's admin API, from `[compile_caddy]` (or `[compile]`): its Unix socket, or its
|
||||||
|
/// loopback TCP address on Windows.
|
||||||
|
pub fn caddy_socket(&self) -> Option<caddy_link::Admin> {
|
||||||
|
caddy_link::Admin::from_compile(self.cfg.caddy_compile())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load caddy.json (the last good config) into the running Caddy, even when it is the
|
||||||
|
/// config Caddy already runs (so it reads its files again), and check that it runs it.
|
||||||
|
pub async fn caddy_reload(&self) -> Result<(), String> {
|
||||||
|
let sock = self
|
||||||
|
.caddy_socket()
|
||||||
|
.ok_or("no caddy_admin_socket (or loopback caddy_admin) is configured, so Caddy cannot be told")?;
|
||||||
|
let text = std::fs::read(&self.cfg.caddy.config)
|
||||||
|
.map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?;
|
||||||
|
caddy_link::load(&sock, &text).await?;
|
||||||
|
if !caddy_link::runs(&sock, &text).await? {
|
||||||
|
return Err("Caddy took the config but does not run it".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `caddy_reload`, then the backstop for certificate and device changes: Caddy must serve
|
||||||
|
/// the certificate that is on disk now for a Domi host (it proves the files were read).
|
||||||
|
pub async fn caddy_reload_checked(&self) -> Result<(), String> {
|
||||||
|
self.caddy_reload().await?;
|
||||||
|
let Ok((_, _, model)) = self.head_model() else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let Some(h) = model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.find(|h| h.tls == ianitor_core::TlsMode::Domi)
|
||||||
|
else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let file = std::path::Path::new(&self.cfg.caddy_compile().cert_dir)
|
||||||
|
.join(format!("{}.crt", h.hostname));
|
||||||
|
let want = std::fs::read_to_string(&file)
|
||||||
|
.ok()
|
||||||
|
.and_then(|pem| ianitor_core::pki::chain_der(&pem).ok())
|
||||||
|
.and_then(|c| c.into_iter().next())
|
||||||
|
.map(|der| crate::util::sha256_hex(&der))
|
||||||
|
.ok_or_else(|| format!("cannot read {}", file.display()))?;
|
||||||
|
let addr = local(self.cfg.caddy_compile().https_listen);
|
||||||
|
let got = caddy_link::served_cert_sha256(addr, h.hostname.as_str()).await?;
|
||||||
|
if got != want {
|
||||||
|
return Err(format!(
|
||||||
|
"Caddy still serves an older certificate for {} after the reload",
|
||||||
|
h.hostname
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn caddy_rules(&self, plan: &Plan) -> BTreeMap<String, Rule> {
|
||||||
|
plan.model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.map(|h| {
|
||||||
|
(
|
||||||
|
h.hostname.to_string(),
|
||||||
|
Rule {
|
||||||
|
upstreams: h.upstreams.clone(),
|
||||||
|
path: h
|
||||||
|
.health_check
|
||||||
|
.as_ref()
|
||||||
|
.map_or("/".to_owned(), |c| c.path.clone()),
|
||||||
|
has_check: h.health_check.is_some(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One round of edge-style upstream probes for one host; `(address, probe)` per upstream.
|
||||||
|
async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for u in &r.upstreams {
|
||||||
|
let host_header = if r.has_check {
|
||||||
|
u.authority()
|
||||||
|
} else {
|
||||||
|
hostname.to_owned()
|
||||||
|
};
|
||||||
|
let p = caddy_link::probe_upstream(u, &r.path, &host_header, !r.has_check).await;
|
||||||
|
out.push((u.authority(), p));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn run_under_caddy(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
mut j: Journal,
|
||||||
|
plan: &Plan,
|
||||||
|
caddy_text: &str,
|
||||||
|
change: &Change,
|
||||||
|
) {
|
||||||
|
let fail = |code: &str, detail: String| {
|
||||||
|
let mut r = reason(code, messages::params([("engine", "Caddy".into())]));
|
||||||
|
r.detail = Some(detail);
|
||||||
|
r
|
||||||
|
};
|
||||||
|
let Some(sock) = self.caddy_socket() else {
|
||||||
|
let r = fail(
|
||||||
|
"apply.failed.reload",
|
||||||
|
"no caddy_admin_socket is configured".into(),
|
||||||
|
);
|
||||||
|
return self.revert(id, &j, r, "failed").await;
|
||||||
|
};
|
||||||
|
let watch_hosts: Vec<String> = plan
|
||||||
|
.hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| plan.target.host(h).is_some())
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
let addr = local(self.cfg.caddy_compile().https_listen);
|
||||||
|
let rules = self.caddy_rules(plan);
|
||||||
|
// A host whose upstreams already failed before the change is no reason to revert
|
||||||
|
// (edge: `down_hosts`). Judged by the upstreams, as edge does.
|
||||||
|
let existed: BTreeSet<String> = self
|
||||||
|
.repo
|
||||||
|
.tree(&j.base)
|
||||||
|
.map(|t| {
|
||||||
|
watch_hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| t.host(h).is_some())
|
||||||
|
.cloned()
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
let mut was_down = BTreeSet::new();
|
||||||
|
for h in &existed {
|
||||||
|
if let Some(r) = rules.get(h)
|
||||||
|
&& !Self::probe_host(h, r).await.iter().any(|(_, p)| p.ok)
|
||||||
|
{
|
||||||
|
was_down.insert(h.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let window = self.cfg.watch_secs;
|
||||||
|
// The deadline goes out before the trial does (crate::caddy_guard).
|
||||||
|
let deadline = now() + window + self.cfg.trial_margin_secs + 5;
|
||||||
|
// Under the engine lock: a device change that looked a moment ago saw no trial and
|
||||||
|
// reloads caddy.json; it must not land after the trial is in.
|
||||||
|
let loaded = {
|
||||||
|
let _engine = self.engine_lock.lock().await;
|
||||||
|
match caddy_guard::arm(&self.cfg.state_dir, id, deadline) {
|
||||||
|
Err(e) => {
|
||||||
|
let mut r = reason("internal", Params::new());
|
||||||
|
r.detail = Some(e);
|
||||||
|
Err((r, "failed"))
|
||||||
|
}
|
||||||
|
Ok(()) => caddy_link::load(&sock, caddy_text.as_bytes())
|
||||||
|
.await
|
||||||
|
.map_err(|e| (fail("apply.failed.reload", e), "failed")),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Err((r, state)) = loaded {
|
||||||
|
return self.revert(id, &j, r, state).await;
|
||||||
|
}
|
||||||
|
j.stage = "trial_loaded".into();
|
||||||
|
if let Err(e) = self.journal(&j) {
|
||||||
|
let mut r = reason("internal", Params::new());
|
||||||
|
r.detail = Some(e);
|
||||||
|
return self.revert(id, &j, r, "failed").await;
|
||||||
|
}
|
||||||
|
crash::point("trial_loaded");
|
||||||
|
self.update(id, |r| r.step("reload", "done"));
|
||||||
|
|
||||||
|
let judged: Vec<String> = watch_hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| !was_down.contains(*h))
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
let mut kept_reason = if watch_hosts.is_empty() {
|
||||||
|
reason(
|
||||||
|
"apply.kept.removed",
|
||||||
|
messages::params([("hostname", plan.hosts.join(", "))]),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
reason(
|
||||||
|
"apply.kept",
|
||||||
|
messages::params([
|
||||||
|
("hostname", watch_hosts.join(", ")),
|
||||||
|
("seconds", window.to_string()),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let ends = now() + window;
|
||||||
|
if judged.is_empty() {
|
||||||
|
self.update(id, |r| r.step("watch", "skipped"));
|
||||||
|
} else {
|
||||||
|
self.update(id, |r| {
|
||||||
|
r.state = "watching".into();
|
||||||
|
r.step("watch", "running");
|
||||||
|
r.watch = Some(Watch {
|
||||||
|
ends,
|
||||||
|
hosts: judged
|
||||||
|
.iter()
|
||||||
|
.map(|h| WatchHost {
|
||||||
|
hostname: h.clone(),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if let Err(r) = self
|
||||||
|
.caddy_watch(id, &sock, caddy_text, &judged, &rules, plan, addr, ends)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
return self.revert(id, &j, r, "reverted").await;
|
||||||
|
}
|
||||||
|
if !judged.is_empty() {
|
||||||
|
let no_check: Vec<String> = judged
|
||||||
|
.iter()
|
||||||
|
.filter(|h| rules.get(*h).is_some_and(|r| !r.has_check))
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
if !no_check.is_empty() && no_check.len() == judged.len() {
|
||||||
|
kept_reason = reason(
|
||||||
|
"apply.kept.no_watch",
|
||||||
|
messages::params([("hostname", no_check.join(", "))]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.update(id, |r| r.step("watch", "done"));
|
||||||
|
}
|
||||||
|
crash::point("watched");
|
||||||
|
// Confirmed first, then the deadline is claimed (fix round 3): a crash in between
|
||||||
|
// leaves the deadline armed *and* the journal confirmed, so the guard and caddy-revert
|
||||||
|
// leave the trial alone and recovery promotes it. The other order would leave a window
|
||||||
|
// with nothing armed and nothing confirmed, where nobody reverts Caddy.
|
||||||
|
j.stage = "confirmed".into();
|
||||||
|
if let Err(e) = self.journal(&j) {
|
||||||
|
let mut r = reason("internal", Params::new());
|
||||||
|
r.detail = Some(e);
|
||||||
|
return self.revert(id, &j, r, "failed").await;
|
||||||
|
}
|
||||||
|
crash::point("confirmed");
|
||||||
|
// From the claim to Caddy running the promoted caddy.json, no device reload may load
|
||||||
|
// the old caddy.json in between.
|
||||||
|
let engine = self.engine_lock.lock().await;
|
||||||
|
// The guard may have reverted a trial that ran past its deadline (a stalled control):
|
||||||
|
// then this change is not kept.
|
||||||
|
if !caddy_guard::claim(&self.cfg.state_dir) {
|
||||||
|
drop(engine);
|
||||||
|
let mut r = reason("apply.interrupted", Params::new());
|
||||||
|
r.detail = Some(
|
||||||
|
"the trial ran past its deadline, so Caddy went back to the last good config"
|
||||||
|
.into(),
|
||||||
|
);
|
||||||
|
return self.revert(id, &j, r, "reverted").await;
|
||||||
|
}
|
||||||
|
if let Err(e) = self.promote() {
|
||||||
|
drop(engine);
|
||||||
|
log::error!(target: "ianitor::apply", "cannot write the config files: {e}");
|
||||||
|
let mut p = reason("control.files_unwritten", Params::new());
|
||||||
|
p.detail = Some(e.to_string());
|
||||||
|
p.params.insert("apply_id".into(), id.to_owned());
|
||||||
|
if let Err(pe) = self.pause(p) {
|
||||||
|
log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it");
|
||||||
|
}
|
||||||
|
let push_step = self.push_step();
|
||||||
|
self.update(id, |r| r.step("push", push_step));
|
||||||
|
self.finish(id, "kept", Some(kept_reason), Vec::new());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
crash::point("promoted");
|
||||||
|
// caddy.json now holds the change: Caddy loads what was written (with the device and
|
||||||
|
// certificate files as they are now) and must run it.
|
||||||
|
if let Err(e) = self.caddy_reload().await {
|
||||||
|
log::error!(target: "ianitor::apply", "Caddy did not load the promoted caddy.json: {e}");
|
||||||
|
}
|
||||||
|
drop(engine);
|
||||||
|
let push_step = self.push_step();
|
||||||
|
self.update(id, |r| r.step("push", push_step));
|
||||||
|
self.finish(id, "kept", Some(kept_reason), Vec::new());
|
||||||
|
self.clear_journal();
|
||||||
|
if self.paused().is_some() && matches!(change, Change::Restore { .. }) {
|
||||||
|
self.unpause();
|
||||||
|
}
|
||||||
|
self.push_wake.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The watch under Caddy until `ends`: the reason to revert, if any.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
async fn caddy_watch(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
sock: &caddy_link::Admin,
|
||||||
|
trial: &str,
|
||||||
|
judged: &[String],
|
||||||
|
rules: &BTreeMap<String, Rule>,
|
||||||
|
plan: &Plan,
|
||||||
|
addr: SocketAddr,
|
||||||
|
ends: u64,
|
||||||
|
) -> Result<(), Reason> {
|
||||||
|
let mut seen: HashMap<(String, String), BTreeMap<u64, Check>> = HashMap::new();
|
||||||
|
let mut seq = 0u64;
|
||||||
|
let mut silent: BTreeMap<String, (u32, String)> = BTreeMap::new();
|
||||||
|
let paths: HashMap<String, String> = rules
|
||||||
|
.iter()
|
||||||
|
.map(|(h, r)| (h.clone(), r.path.clone()))
|
||||||
|
.collect();
|
||||||
|
let mut first = true;
|
||||||
|
loop {
|
||||||
|
// Anyone else's reload (a device change, a restart of caddy-fallback) drops the
|
||||||
|
// trial: then this is not a verdict on the change.
|
||||||
|
match caddy_link::runs(sock, trial.as_bytes()).await {
|
||||||
|
Ok(true) => {}
|
||||||
|
Ok(false) => {
|
||||||
|
let mut r = reason("apply.reverted.edge_lost", Params::new());
|
||||||
|
r.detail = Some("Caddy no longer runs the trial config".into());
|
||||||
|
return Err(r);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let mut r = reason("apply.reverted.edge_lost", Params::new());
|
||||||
|
r.detail = Some(e);
|
||||||
|
return Err(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if first {
|
||||||
|
crash::point("watching");
|
||||||
|
first = false;
|
||||||
|
}
|
||||||
|
let mut counts = Vec::new();
|
||||||
|
for h in judged {
|
||||||
|
let Some(rule) = rules.get(h) else { continue };
|
||||||
|
// Does Caddy answer for this host at all? Any status does.
|
||||||
|
match caddy_link::probe(addr, h, "/").await {
|
||||||
|
Probe::Status(_) => {
|
||||||
|
silent.remove(h);
|
||||||
|
}
|
||||||
|
Probe::NoAnswer(e) => {
|
||||||
|
let s = silent.entry(h.clone()).or_insert((0, String::new()));
|
||||||
|
s.0 += 1;
|
||||||
|
s.1 = e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some((n, e)) = silent.get(h)
|
||||||
|
&& *n >= 3
|
||||||
|
{
|
||||||
|
let mut r = reason(
|
||||||
|
"apply.reverted.no_answer",
|
||||||
|
messages::params([
|
||||||
|
("hostname", h.clone()),
|
||||||
|
("verb", plan.verb.into()),
|
||||||
|
("seconds", self.cfg.watch_secs.to_string()),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
r.hostname = Some(h.clone());
|
||||||
|
r.detail = Some(format!("Caddy does not answer for {h}: {e}"));
|
||||||
|
return Err(r);
|
||||||
|
}
|
||||||
|
for (address, p) in Self::probe_host(h, rule).await {
|
||||||
|
seq += 1;
|
||||||
|
seen.entry((h.clone(), address)).or_default().insert(
|
||||||
|
seq,
|
||||||
|
Check {
|
||||||
|
seq,
|
||||||
|
at: now(),
|
||||||
|
ok: p.ok,
|
||||||
|
source: if rule.has_check {
|
||||||
|
"health_check".into()
|
||||||
|
} else {
|
||||||
|
"watch".into()
|
||||||
|
},
|
||||||
|
kind: p.kind.map(str::to_owned),
|
||||||
|
status: p.status,
|
||||||
|
latency_ms: p.latency_ms,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut passed = 0u32;
|
||||||
|
let mut failed = 0u32;
|
||||||
|
let mut all_failing = !rule.upstreams.is_empty();
|
||||||
|
for ((host, _), m) in &seen {
|
||||||
|
if host != h {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
passed += m.values().filter(|c| c.ok).count() as u32;
|
||||||
|
failed += m.values().filter(|c| !c.ok).count() as u32;
|
||||||
|
if m.values().rev().take_while(|c| !c.ok).count() < 3 {
|
||||||
|
all_failing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
counts.push(WatchHost {
|
||||||
|
hostname: h.clone(),
|
||||||
|
passed,
|
||||||
|
failed,
|
||||||
|
total: passed + failed,
|
||||||
|
});
|
||||||
|
if all_failing {
|
||||||
|
return Err(self.revert_reason(h, plan, &seen, &paths));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.update(id, |r| {
|
||||||
|
if let Some(w) = &mut r.watch {
|
||||||
|
w.hosts = counts;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if now() >= ends {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await;
|
||||||
|
}
|
||||||
|
// At the end, as with edge: every judged host needs an upstream whose last probe passed.
|
||||||
|
for h in judged {
|
||||||
|
let last_ok = seen
|
||||||
|
.iter()
|
||||||
|
.filter(|((host, _), _)| host == h)
|
||||||
|
.any(|(_, m)| m.values().next_back().is_some_and(|c| c.ok));
|
||||||
|
if !last_ok {
|
||||||
|
return Err(self.revert_reason(h, plan, &seen, &paths));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
// 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 host body of the API. It mirrors the host TOML file field for field (docs/ui-api.md
|
||||||
|
//! §1.2), so control writes exactly what Mark would write by hand. Core validates the TOML
|
||||||
|
//! control writes; this type only carries it.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct HostSpec {
|
||||||
|
/// Lowercase DNS name, e.g. `wiki.home.example`.
|
||||||
|
pub hostname: String,
|
||||||
|
/// Where traffic goes, e.g. `http://10.0.0.23:3000`. Same scheme for all.
|
||||||
|
pub upstreams: Vec<String>,
|
||||||
|
/// `letsencrypt` or `domi`.
|
||||||
|
#[serde(default = "letsencrypt")]
|
||||||
|
pub tls: String,
|
||||||
|
/// `none` or `forward-auth`.
|
||||||
|
#[serde(default = "auth_none")]
|
||||||
|
pub auth: String,
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub websockets: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub share_links: bool,
|
||||||
|
/// Visitors need a Domi device certificate (mTLS).
|
||||||
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||||
|
pub device_certs: bool,
|
||||||
|
/// `off` or `truncated`.
|
||||||
|
#[serde(default = "off")]
|
||||||
|
pub access_log: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub health_check: Option<HealthCheckSpec>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub request_headers: Vec<HeaderRuleSpec>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub response_headers: Vec<HeaderRuleSpec>,
|
||||||
|
/// Set on a branch preview (Fabrica); written by `/api/v1/previews`.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub preview: Option<PreviewSpec>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PreviewSpec {
|
||||||
|
pub project: String,
|
||||||
|
pub branch: String,
|
||||||
|
/// Unix seconds.
|
||||||
|
pub expires_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct HealthCheckSpec {
|
||||||
|
pub path: String,
|
||||||
|
#[serde(default = "ten")]
|
||||||
|
pub interval_secs: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct HeaderRuleSpec {
|
||||||
|
/// `set` or `remove`.
|
||||||
|
pub action: String,
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub value: Option<String>,
|
||||||
|
/// Name of a secret declared in `ianitor.toml`.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub secret: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn letsencrypt() -> String {
|
||||||
|
"letsencrypt".into()
|
||||||
|
}
|
||||||
|
fn auth_none() -> String {
|
||||||
|
"none".into()
|
||||||
|
}
|
||||||
|
fn off() -> String {
|
||||||
|
"off".into()
|
||||||
|
}
|
||||||
|
fn yes() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
fn ten() -> i64 {
|
||||||
|
10
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HostSpec {
|
||||||
|
/// The TOML file control commits for this host. Every field is written out, so the file
|
||||||
|
/// says exactly what the form said.
|
||||||
|
pub fn to_toml(&self) -> Result<String, String> {
|
||||||
|
let body = toml::to_string(self).map_err(|e| e.to_string())?;
|
||||||
|
Ok(format!(
|
||||||
|
"# Written by Ianitor control. Edit through the web UI or the API.\n{body}"
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_toml(text: &str) -> Result<HostSpec, String> {
|
||||||
|
toml::from_str(text).map_err(|e| e.message().to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Field-level differences, labelled for the restore preview (docs/ui-api.md §1.4).
|
||||||
|
pub fn diff(&self, to: &HostSpec) -> Vec<(String, String, String)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut push = |f: &str, a: String, b: String| {
|
||||||
|
if a != b {
|
||||||
|
out.push((f.to_owned(), a, b));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
push("hostname", self.hostname.clone(), to.hostname.clone());
|
||||||
|
push(
|
||||||
|
"upstreams",
|
||||||
|
self.upstreams.join(", "),
|
||||||
|
to.upstreams.join(", "),
|
||||||
|
);
|
||||||
|
push("tls", self.tls.clone(), to.tls.clone());
|
||||||
|
push("auth", self.auth.clone(), to.auth.clone());
|
||||||
|
push(
|
||||||
|
"websockets",
|
||||||
|
self.websockets.to_string(),
|
||||||
|
to.websockets.to_string(),
|
||||||
|
);
|
||||||
|
push(
|
||||||
|
"share_links",
|
||||||
|
self.share_links.to_string(),
|
||||||
|
to.share_links.to_string(),
|
||||||
|
);
|
||||||
|
push("access_log", self.access_log.clone(), to.access_log.clone());
|
||||||
|
push(
|
||||||
|
"device_certs",
|
||||||
|
self.device_certs.to_string(),
|
||||||
|
to.device_certs.to_string(),
|
||||||
|
);
|
||||||
|
let hc =
|
||||||
|
|h: &Option<HealthCheckSpec>| h.as_ref().map(|h| (h.path.clone(), h.interval_secs));
|
||||||
|
let (a, b) = (hc(&self.health_check), hc(&to.health_check));
|
||||||
|
push(
|
||||||
|
"health_check.path",
|
||||||
|
a.as_ref().map(|x| x.0.clone()).unwrap_or_default(),
|
||||||
|
b.as_ref().map(|x| x.0.clone()).unwrap_or_default(),
|
||||||
|
);
|
||||||
|
push(
|
||||||
|
"health_check.interval_secs",
|
||||||
|
a.map(|x| x.1.to_string()).unwrap_or_default(),
|
||||||
|
b.map(|x| x.1.to_string()).unwrap_or_default(),
|
||||||
|
);
|
||||||
|
let rules =
|
||||||
|
|r: &[HeaderRuleSpec], q: &[HeaderRuleSpec]| format!("{} rules", r.len() + q.len());
|
||||||
|
if self.request_headers != to.request_headers
|
||||||
|
|| self.response_headers != to.response_headers
|
||||||
|
{
|
||||||
|
out.push((
|
||||||
|
"headers".into(),
|
||||||
|
rules(&self.request_headers, &self.response_headers),
|
||||||
|
rules(&to.request_headers, &to.response_headers),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trips_and_core_accepts_it() {
|
||||||
|
let h = HostSpec {
|
||||||
|
hostname: "wiki.home.test".into(),
|
||||||
|
upstreams: vec!["http://10.0.0.2:3000".into()],
|
||||||
|
tls: "domi".into(),
|
||||||
|
auth: "none".into(),
|
||||||
|
websockets: false,
|
||||||
|
share_links: true,
|
||||||
|
device_certs: true,
|
||||||
|
access_log: "truncated".into(),
|
||||||
|
health_check: Some(HealthCheckSpec {
|
||||||
|
path: "/health".into(),
|
||||||
|
interval_secs: 15,
|
||||||
|
}),
|
||||||
|
request_headers: vec![HeaderRuleSpec {
|
||||||
|
action: "set".into(),
|
||||||
|
name: "X-A".into(),
|
||||||
|
value: Some("1".into()),
|
||||||
|
secret: None,
|
||||||
|
}],
|
||||||
|
response_headers: vec![],
|
||||||
|
preview: None,
|
||||||
|
};
|
||||||
|
let text = h.to_toml().unwrap();
|
||||||
|
assert_eq!(HostSpec::from_toml(&text).unwrap(), h);
|
||||||
|
let m = ianitor_core::load(
|
||||||
|
&ianitor_core::SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
},
|
||||||
|
&[ianitor_core::SourceFile {
|
||||||
|
name: "hosts/wiki.home.test.toml",
|
||||||
|
contents: &text,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(m.is_ok(), "{m:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Ianitor control: the routes repository, apply with automatic rollback, share links, API
|
||||||
|
//! tokens and the REST API, on loopback only. It never serves public traffic; if it stops,
|
||||||
|
//! edge keeps serving the last good config.
|
||||||
|
|
||||||
|
pub mod api;
|
||||||
|
pub mod caddy_guard;
|
||||||
|
pub mod caddy_link;
|
||||||
|
pub mod config;
|
||||||
|
pub mod crash;
|
||||||
|
pub mod edgelink;
|
||||||
|
pub mod engine;
|
||||||
|
pub mod hostspec;
|
||||||
|
pub mod logger;
|
||||||
|
pub mod messages;
|
||||||
|
pub mod pki;
|
||||||
|
pub mod pki_ctl;
|
||||||
|
pub mod previews;
|
||||||
|
pub mod records;
|
||||||
|
pub mod repo;
|
||||||
|
pub mod shares;
|
||||||
|
pub mod switch;
|
||||||
|
pub mod team;
|
||||||
|
pub mod tokens;
|
||||||
|
pub mod util;
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub use config::Config;
|
||||||
|
pub use engine::Control;
|
||||||
|
|
||||||
|
/// Open control, start its background tasks and serve the API until `shutdown` resolves.
|
||||||
|
pub async fn serve(
|
||||||
|
cfg: Config,
|
||||||
|
shutdown: impl std::future::Future<Output = ()> + Send + 'static,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
cfg.check().map_err(|e| e.to_string())?;
|
||||||
|
let listen = cfg.listen;
|
||||||
|
let ctl = Control::open(cfg).await?;
|
||||||
|
tokio::spawn(ctl.clone().worker());
|
||||||
|
tokio::spawn(ctl.clone().health_poller());
|
||||||
|
tokio::spawn(ctl.clone().pusher());
|
||||||
|
tokio::spawn(ctl.clone().pki_poller());
|
||||||
|
tokio::spawn(ctl.clone().preview_sweeper());
|
||||||
|
ctl.ensure_admin_host();
|
||||||
|
if ctl.cfg.ui.is_some() && !ctl.team.has_members() && ctl.ui_proof.is_none() {
|
||||||
|
log::warn!(target: "ianitor::team", "nobody is in the team yet: run `ianitor-control team setup-link --config <control.toml>` and open the link it prints");
|
||||||
|
}
|
||||||
|
let app = api::router(api::AppState::new(ctl.clone()));
|
||||||
|
if !listen.ip().is_loopback() {
|
||||||
|
return Err("ianitor-control only listens on loopback".into());
|
||||||
|
}
|
||||||
|
let listener = tokio::net::TcpListener::bind(listen)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("cannot listen on {listen}: {e}"))?;
|
||||||
|
log::info!(target: "ianitor::control", "API on http://{listen}/api/v1");
|
||||||
|
axum::serve(listener, app)
|
||||||
|
.with_graceful_shutdown(shutdown)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
drop(ctl);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait for Ctrl-C or SIGTERM.
|
||||||
|
pub async fn stop_signal() {
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use tokio::signal::unix::{SignalKind, signal};
|
||||||
|
let mut term = match signal(SignalKind::terminate()) {
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(_) => {
|
||||||
|
let _ = tokio::signal::ctrl_c().await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tokio::select! {
|
||||||
|
_ = tokio::signal::ctrl_c() => {}
|
||||||
|
_ = term.recv() => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
{
|
||||||
|
let _ = tokio::signal::ctrl_c().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For tests: the router over an opened control.
|
||||||
|
pub fn app(ctl: Arc<Control>) -> axum::Router {
|
||||||
|
api::router(api::AppState::new(ctl))
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Error log on stderr (journald under systemd). Control never logs request headers, bodies,
|
||||||
|
//! query strings, tokens, passwords or share links: request lines are logged as method and
|
||||||
|
//! route only, by the API layer.
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
use log::{Level, LevelFilter, Log, Metadata, Record};
|
||||||
|
|
||||||
|
struct Stderr {
|
||||||
|
own: LevelFilter,
|
||||||
|
/// `$IANITOR_LOG_FILE` or `--log-file`: append here instead of stderr (Windows services).
|
||||||
|
file: Option<std::sync::Mutex<std::fs::File>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Log for Stderr {
|
||||||
|
fn enabled(&self, m: &Metadata<'_>) -> bool {
|
||||||
|
let limit = if m.target().starts_with("ianitor") {
|
||||||
|
self.own
|
||||||
|
} else {
|
||||||
|
self.own.min(LevelFilter::Info)
|
||||||
|
};
|
||||||
|
m.level() <= limit
|
||||||
|
}
|
||||||
|
|
||||||
|
fn log(&self, r: &Record<'_>) {
|
||||||
|
if self.enabled(r.metadata()) {
|
||||||
|
let lvl = match r.level() {
|
||||||
|
Level::Error => "ERROR",
|
||||||
|
Level::Warn => "WARN",
|
||||||
|
Level::Info => "INFO",
|
||||||
|
Level::Debug => "DEBUG",
|
||||||
|
Level::Trace => "TRACE",
|
||||||
|
};
|
||||||
|
match &self.file {
|
||||||
|
Some(f) => {
|
||||||
|
if let Ok(mut f) = f.lock() {
|
||||||
|
let _ = writeln!(
|
||||||
|
f,
|
||||||
|
"{} {lvl} {}: {}",
|
||||||
|
crate::util::rfc3339(crate::util::now()),
|
||||||
|
r.target(),
|
||||||
|
r.args()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let _ = writeln!(
|
||||||
|
std::io::stderr().lock(),
|
||||||
|
"{lvl} {}: {}",
|
||||||
|
r.target(),
|
||||||
|
r.args()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&self) {
|
||||||
|
let _ = std::io::stderr().flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn init(level: Option<&str>) {
|
||||||
|
init_to(
|
||||||
|
level,
|
||||||
|
std::env::var_os("IANITOR_LOG_FILE").map(std::path::PathBuf::from),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`init`], appending to `file` when given.
|
||||||
|
pub fn init_to(level: Option<&str>, file: Option<std::path::PathBuf>) {
|
||||||
|
let file = file.and_then(|p| {
|
||||||
|
std::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.append(true)
|
||||||
|
.open(p)
|
||||||
|
.ok()
|
||||||
|
.map(std::sync::Mutex::new)
|
||||||
|
});
|
||||||
|
let own = match level.map(str::to_ascii_lowercase).as_deref() {
|
||||||
|
Some("error") => LevelFilter::Error,
|
||||||
|
Some("warn") => LevelFilter::Warn,
|
||||||
|
Some("debug") => LevelFilter::Debug,
|
||||||
|
Some("trace") => LevelFilter::Trace,
|
||||||
|
_ => LevelFilter::Info,
|
||||||
|
};
|
||||||
|
if log::set_boxed_logger(Box::new(Stderr { own, file })).is_ok() {
|
||||||
|
log::set_max_level(own);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,510 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! ```text
|
||||||
|
//! ianitor-control --config <control.toml> run the control plane
|
||||||
|
//! ianitor-control --dev [--edge-bin <ianitor-edge>] temporary everything on 127.0.0.1
|
||||||
|
//! ianitor-control token create --name <name> [--scope full|previews] [--expires-days <n> | --never] (--config <c> | --state-dir <d>)
|
||||||
|
//! ianitor-control token list (--config <c> | --state-dir <d>)
|
||||||
|
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
|
||||||
|
//! ianitor-control openapi print the OpenAPI document
|
||||||
|
//! ianitor-control pki approve|deny <code> (--config <c> | --state-dir <d>) approve a device request
|
||||||
|
//! ianitor-control pki install <intermediate.crt> (--config <c>) install a signed intermediate
|
||||||
|
//! ianitor-control pki status (--config <c>) open requests
|
||||||
|
//! ianitor-control ca init --out <dir> [--passphrase-file <f>] the offline root (never on the server)
|
||||||
|
//! ianitor-control ca sign --root <dir> --csr <f> --out <f> [--yes] sign an intermediate offline
|
||||||
|
//! ianitor-control check --config <control.toml> check the config and exit
|
||||||
|
//! ianitor-control team setup-link|list --config <c> the first admin's sign-in link
|
||||||
|
//! ianitor-control service control|caddy-guard --config <c> [--log-file <f>] Windows service
|
||||||
|
//! ```
|
||||||
|
//! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`),
|
||||||
|
//! the binary answers git's prompt from the push credential file.
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::ExitCode;
|
||||||
|
|
||||||
|
use ianitor_control::{Config, logger, tokens::Tokens};
|
||||||
|
|
||||||
|
mod dev;
|
||||||
|
#[cfg(windows)]
|
||||||
|
mod winsvc;
|
||||||
|
|
||||||
|
fn usage() -> ExitCode {
|
||||||
|
eprintln!(
|
||||||
|
"usage: ianitor-control --config <control.toml> | --dev [--edge-bin <path>] | \
|
||||||
|
token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) | \
|
||||||
|
token list (...) | token revoke <id> (...) | openapi | check --config <c> | \
|
||||||
|
caddy-revert --config <c> | caddy-guard --config <c>"
|
||||||
|
);
|
||||||
|
ExitCode::from(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn askpass() -> ExitCode {
|
||||||
|
// git asks "Username for 'https://…':" and "Password for 'https://…':".
|
||||||
|
let prompt = std::env::args().nth(1).unwrap_or_default();
|
||||||
|
if prompt.starts_with("Username") {
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
std::env::var("IANITOR_ASKPASS_USER").unwrap_or_default()
|
||||||
|
);
|
||||||
|
return ExitCode::SUCCESS;
|
||||||
|
}
|
||||||
|
// Answer only the password prompt; anything else (a passphrase, a host key question)
|
||||||
|
// gets no answer, so the push fails instead of handing out the token.
|
||||||
|
if !prompt.starts_with("Password for") {
|
||||||
|
eprintln!("ianitor-control askpass: not answering {prompt:?}");
|
||||||
|
return ExitCode::FAILURE;
|
||||||
|
}
|
||||||
|
let Some(file) = std::env::var_os("IANITOR_ASKPASS_FILE") else {
|
||||||
|
return ExitCode::FAILURE;
|
||||||
|
};
|
||||||
|
match std::fs::read_to_string(file) {
|
||||||
|
Ok(v) => {
|
||||||
|
println!("{}", v.trim_end_matches(['\r', '\n']));
|
||||||
|
ExitCode::SUCCESS
|
||||||
|
}
|
||||||
|
Err(_) => ExitCode::FAILURE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_dir(args: &[String]) -> Result<PathBuf, String> {
|
||||||
|
let mut it = args.iter();
|
||||||
|
while let Some(a) = it.next() {
|
||||||
|
match a.as_str() {
|
||||||
|
"--state-dir" => {
|
||||||
|
return it
|
||||||
|
.next()
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.ok_or("--state-dir needs a path".into());
|
||||||
|
}
|
||||||
|
"--config" => {
|
||||||
|
let p = it.next().ok_or("--config needs a path")?;
|
||||||
|
return Config::load(&PathBuf::from(p))
|
||||||
|
.map(|c| c.state_dir)
|
||||||
|
.map_err(|e| e.to_string());
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err("give --config <control.toml> or --state-dir <dir>".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The token files must stay owned by the user control runs as: refuse to touch them as
|
||||||
|
/// anyone else (typically root), instead of leaving root-owned files control cannot open.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn same_owner(dir: &std::path::Path) -> Result<(), String> {
|
||||||
|
use std::os::unix::fs::MetadataExt;
|
||||||
|
let existing = dir
|
||||||
|
.ancestors()
|
||||||
|
.find(|p| p.is_dir())
|
||||||
|
.ok_or_else(|| format!("no part of {} exists", dir.display()))?;
|
||||||
|
let owner = std::fs::metadata(existing)
|
||||||
|
.map_err(|e| format!("cannot read {}: {e}", existing.display()))?
|
||||||
|
.uid();
|
||||||
|
// Who we are, without libc: the owner of a file we create (in the temp dir, so nothing is
|
||||||
|
// created in the state dir by the wrong user).
|
||||||
|
let probe = std::env::temp_dir().join(format!(".ianitor-owner-probe-{}", std::process::id()));
|
||||||
|
// create_new: never follows or reuses a file someone else put there.
|
||||||
|
let me = std::fs::File::create_new(&probe)
|
||||||
|
.and_then(|f| f.metadata())
|
||||||
|
.map(|m| m.uid());
|
||||||
|
if me.is_ok() {
|
||||||
|
let _ = std::fs::remove_file(&probe);
|
||||||
|
}
|
||||||
|
let me = me.map_err(|e| format!("cannot create a probe file to learn who runs this: {e}"))?;
|
||||||
|
if me == 0 && !dir.is_dir() {
|
||||||
|
return Err(format!(
|
||||||
|
"{} does not exist; create it as the user control runs as (or run this as that user), not as root",
|
||||||
|
dir.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if me != owner {
|
||||||
|
return Err(format!(
|
||||||
|
"{} belongs to uid {owner}, but this runs as uid {me}; run it as that user (e.g. sudo -u ianitor ianitor-control token ...)",
|
||||||
|
existing.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
fn same_owner(_: &std::path::Path) -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn token(args: &[String]) -> Result<(), String> {
|
||||||
|
let dir = state_dir(args)?;
|
||||||
|
// Check the owner before creating anything: the nearest existing ancestor must belong to
|
||||||
|
// whoever runs this (so root does not create a state dir control cannot use).
|
||||||
|
same_owner(&dir)?;
|
||||||
|
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||||
|
let tokens = Tokens::new(&dir);
|
||||||
|
match args.first().map(String::as_str) {
|
||||||
|
Some("create") => {
|
||||||
|
let mut name = None;
|
||||||
|
let mut scope = ianitor_control::tokens::Scope::Full;
|
||||||
|
let mut expires = Some(ianitor_control::util::now() + 365 * 86_400);
|
||||||
|
let mut it = args.iter().skip(1);
|
||||||
|
while let Some(a) = it.next() {
|
||||||
|
match a.as_str() {
|
||||||
|
"--name" => name = it.next().cloned(),
|
||||||
|
"--never" => expires = None,
|
||||||
|
"--scope" => {
|
||||||
|
scope = it
|
||||||
|
.next()
|
||||||
|
.and_then(|s| ianitor_control::tokens::Scope::parse(s))
|
||||||
|
.ok_or("--scope must be full or previews")?;
|
||||||
|
}
|
||||||
|
"--expires-days" => {
|
||||||
|
let d: u64 = it
|
||||||
|
.next()
|
||||||
|
.and_then(|d| d.parse().ok())
|
||||||
|
.filter(|d| (1..=3650).contains(d))
|
||||||
|
.ok_or("--expires-days must be 1 to 3650")?;
|
||||||
|
expires = Some(ianitor_control::util::now() + d * 86_400);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let name = name.ok_or("--name <name> is required")?;
|
||||||
|
let (rec, value) = tokens.create(&name, expires, scope).map_err(|e| {
|
||||||
|
if e == "token.name" {
|
||||||
|
"the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores"
|
||||||
|
.to_owned()
|
||||||
|
} else {
|
||||||
|
e
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
eprintln!(
|
||||||
|
"Token {} ({}, scope {}) created. It is shown once; save it in Custos now:",
|
||||||
|
rec.id,
|
||||||
|
rec.name,
|
||||||
|
rec.scope.as_str()
|
||||||
|
);
|
||||||
|
println!("{value}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("list") => {
|
||||||
|
for t in tokens.list()? {
|
||||||
|
println!(
|
||||||
|
"{} {} created {}{}{}",
|
||||||
|
t.id,
|
||||||
|
t.name,
|
||||||
|
ianitor_control::util::rfc3339(t.created_at),
|
||||||
|
t.expires_at
|
||||||
|
.map(|e| format!(" expires {}", ianitor_control::util::rfc3339(e)))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
t.revoked_at
|
||||||
|
.map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e)))
|
||||||
|
.unwrap_or_default()
|
||||||
|
);
|
||||||
|
if t.scope != ianitor_control::tokens::Scope::Full {
|
||||||
|
println!(" scope {}", t.scope.as_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("revoke") => {
|
||||||
|
let id = args.get(1).ok_or("token revoke <id>")?;
|
||||||
|
match tokens.revoke(id)? {
|
||||||
|
Some(_) => {
|
||||||
|
eprintln!("Token {id} revoked.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
None => Err(format!("there is no token {id}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => Err("token create | list | revoke".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn arg_after(args: &[String], name: &str) -> Option<String> {
|
||||||
|
let mut it = args.iter();
|
||||||
|
while let Some(a) = it.next() {
|
||||||
|
if a == name {
|
||||||
|
return it.next().cloned();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A passphrase from `--passphrase-file`, or asked on the terminal without echo.
|
||||||
|
fn passphrase(args: &[String], confirm: bool) -> Result<String, String> {
|
||||||
|
if let Some(f) = arg_after(args, "--passphrase-file") {
|
||||||
|
let v = std::fs::read_to_string(&f).map_err(|e| format!("cannot read {f}: {e}"))?;
|
||||||
|
let v = v.trim_end_matches(['\r', '\n']).to_owned();
|
||||||
|
if v.chars().count() < 12 {
|
||||||
|
return Err("the passphrase must have at least 12 characters".into());
|
||||||
|
}
|
||||||
|
return Ok(v);
|
||||||
|
}
|
||||||
|
let p = rpassword::prompt_password("Root key passphrase: ").map_err(|e| e.to_string())?;
|
||||||
|
if p.chars().count() < 12 {
|
||||||
|
return Err("the passphrase must have at least 12 characters".into());
|
||||||
|
}
|
||||||
|
if confirm {
|
||||||
|
let again = rpassword::prompt_password("Again: ").map_err(|e| e.to_string())?;
|
||||||
|
if again != p {
|
||||||
|
return Err("the two passphrases differ".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ca init` and `ca sign`: the offline root (ROADMAP §1.2; docs/pki.md). Never run on the
|
||||||
|
/// server.
|
||||||
|
fn ca(args: &[String]) -> Result<(), String> {
|
||||||
|
use ianitor_core::pki;
|
||||||
|
let now = ianitor_control::util::now() as i64;
|
||||||
|
match args.first().map(String::as_str) {
|
||||||
|
Some("init") => {
|
||||||
|
let out = PathBuf::from(arg_after(args, "--out").ok_or("ca init --out <dir>")?);
|
||||||
|
let crt = out.join("domi-root.crt");
|
||||||
|
let key = out.join("domi-root.key");
|
||||||
|
if crt.exists() || key.exists() {
|
||||||
|
return Err(format!(
|
||||||
|
"{} already has a root; refusing to replace it",
|
||||||
|
out.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
|
||||||
|
let pass = passphrase(args, true)?;
|
||||||
|
let (cert, k) = pki::create_root(now).map_err(|e| e.to_string())?;
|
||||||
|
let sealed = pki::encrypt_key(&k, pass.as_bytes()).map_err(|e| e.to_string())?;
|
||||||
|
ianitor_control::util::write_atomic(&key, sealed.as_bytes(), 0o600)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
ianitor_control::util::write_atomic(&crt, cert.as_bytes(), 0o644)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let info = pki::inspect(&cert).map_err(|e| e.to_string())?;
|
||||||
|
eprintln!(
|
||||||
|
"Domi root created in {}: {} (valid until {}).\nSHA-256 {}\n\
|
||||||
|
Copy domi-root.crt to the server's configuration (services.ianitor.pki.rootCertificate).\n\
|
||||||
|
Keep domi-root.key and its passphrase offline (Custos, once it can hold it).",
|
||||||
|
out.display(),
|
||||||
|
info.subject_cn,
|
||||||
|
ianitor_core::time::long_date(info.not_after.max(0) as u64),
|
||||||
|
info.sha256_hex
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("sign") => {
|
||||||
|
let root = PathBuf::from(
|
||||||
|
arg_after(args, "--root")
|
||||||
|
.ok_or("ca sign --root <dir> --csr <file> --out <file>")?,
|
||||||
|
);
|
||||||
|
let csr_path = arg_after(args, "--csr").ok_or("--csr <file> is required")?;
|
||||||
|
let out = PathBuf::from(arg_after(args, "--out").ok_or("--out <file> is required")?);
|
||||||
|
let csr = std::fs::read_to_string(&csr_path)
|
||||||
|
.map_err(|e| format!("cannot read {csr_path}: {e}"))?;
|
||||||
|
let code = pki::match_code(&pki::csr_der(&csr).map_err(|e| e.to_string())?);
|
||||||
|
eprintln!("This request's code is {code}. It must be the code Ianitor shows.");
|
||||||
|
if !args.iter().any(|a| a == "--yes") {
|
||||||
|
let typed = rpassword::prompt_password("Type the code to sign (no echo): ")
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if ianitor_control::pki::normalise_code(&typed)
|
||||||
|
!= ianitor_control::pki::normalise_code(&code)
|
||||||
|
{
|
||||||
|
return Err("the code does not match; nothing was signed".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let cert =
|
||||||
|
std::fs::read_to_string(root.join("domi-root.crt")).map_err(|e| e.to_string())?;
|
||||||
|
let sealed =
|
||||||
|
std::fs::read_to_string(root.join("domi-root.key")).map_err(|e| e.to_string())?;
|
||||||
|
let pass = passphrase(args, false)?;
|
||||||
|
let key = pki::decrypt_key(&sealed, pass.as_bytes()).map_err(|e| e.to_string())?;
|
||||||
|
let signed =
|
||||||
|
pki::sign_intermediate(&cert, &key, &csr, now).map_err(|e| e.to_string())?;
|
||||||
|
ianitor_control::util::write_atomic(&out, signed.as_bytes(), 0o644)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let info = pki::inspect(&signed).map_err(|e| e.to_string())?;
|
||||||
|
eprintln!(
|
||||||
|
"Signed {} until {}. Install it on the server: ianitor-control pki install {}",
|
||||||
|
info.subject_cn,
|
||||||
|
ianitor_core::time::long_date(info.not_after.max(0) as u64),
|
||||||
|
out.display()
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err("ca init --out <dir> | ca sign --root <dir> --csr <file> --out <file>".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `pki approve|deny|install|status` on the server, as the user control runs as.
|
||||||
|
fn pki_cli(args: &[String]) -> Result<(), String> {
|
||||||
|
let dir = state_dir(args)?;
|
||||||
|
same_owner(&dir)?;
|
||||||
|
let now = ianitor_control::util::now();
|
||||||
|
match args.first().map(String::as_str) {
|
||||||
|
Some(verb @ ("approve" | "deny")) => {
|
||||||
|
// The code may be given as one word or three (47 19 83).
|
||||||
|
let code: String = args
|
||||||
|
.iter()
|
||||||
|
.skip(1)
|
||||||
|
.take_while(|a| !a.starts_with("--"))
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("");
|
||||||
|
let r = ianitor_control::pki::cli_approve(&dir, &code, verb == "deny", now)?;
|
||||||
|
let name = r.name.clone().unwrap_or_default();
|
||||||
|
eprintln!("Handed to control; waiting for it ...");
|
||||||
|
let state = ianitor_control::pki::cli_wait(&dir, &r.id, now)
|
||||||
|
.map_err(|e| format!("not done for \"{name}\" ({}): {e}", r.id))?;
|
||||||
|
eprintln!(
|
||||||
|
"{} the request for \"{name}\" ({}).",
|
||||||
|
if state == "approved" { "Approved" } else { "Turned down" },
|
||||||
|
r.id
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("install") => {
|
||||||
|
let f = args.get(1).filter(|a| !a.starts_with("--")).ok_or("pki install <intermediate.crt>")?;
|
||||||
|
let pem = std::fs::read_to_string(f).map_err(|e| format!("cannot read {f}: {e}"))?;
|
||||||
|
let r = ianitor_control::pki::cli_install(&dir, &pem, now)?;
|
||||||
|
eprintln!("Handed to renewal {}; waiting for control to install it ...", r.id);
|
||||||
|
ianitor_control::pki::cli_wait(&dir, &r.id, now)
|
||||||
|
.map_err(|e| format!("not installed: {e}"))?;
|
||||||
|
eprintln!("Installed. Server certificates are reissued from it now.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("status") => {
|
||||||
|
let rs: Vec<ianitor_control::pki::Request> =
|
||||||
|
ianitor_control::util::read_json(&ianitor_control::pki::requests_path(&dir))?.unwrap_or_default();
|
||||||
|
for r in rs.iter().filter(|r| r.state == "waiting" && r.expires_at > now) {
|
||||||
|
println!(
|
||||||
|
"{} {} {} code {} until {}",
|
||||||
|
r.id,
|
||||||
|
r.kind,
|
||||||
|
r.name.clone().unwrap_or_default(),
|
||||||
|
r.match_code,
|
||||||
|
ianitor_control::util::rfc3339(r.expires_at)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err("pki approve <code> | pki deny <code> | pki install <cert> | pki status (--config <c> | --state-dir <d>)".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `team setup-link | list` on the server, as the user control runs as.
|
||||||
|
fn team_cli(args: &[String]) -> Result<(), String> {
|
||||||
|
let path = arg_after(args, "--config").ok_or("team setup-link|list --config <control.toml>")?;
|
||||||
|
let cfg = Config::load(&PathBuf::from(path)).map_err(|e| e.to_string())?;
|
||||||
|
same_owner(&cfg.state_dir)?;
|
||||||
|
let team = ianitor_control::team::Team::new(&cfg.state_dir);
|
||||||
|
match args.first().map(String::as_str) {
|
||||||
|
Some("setup-link") => {
|
||||||
|
let (code, until) = team.setup_code()?;
|
||||||
|
let base = match cfg.ui.as_ref().and_then(|u| u.hostname.as_ref()) {
|
||||||
|
Some(h) => format!("https://{h}/"),
|
||||||
|
None => format!("http://{}/", cfg.listen),
|
||||||
|
};
|
||||||
|
eprintln!(
|
||||||
|
"Open this link to sign in as the team's first admin. It works once, until {}:",
|
||||||
|
ianitor_control::util::rfc3339(until)
|
||||||
|
);
|
||||||
|
println!("{base}#signin={code}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("list") => {
|
||||||
|
for m in team.members()? {
|
||||||
|
println!("{} {} {}", m.id, m.role.as_str(), m.name);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err("team setup-link|list --config <control.toml>".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> ExitCode {
|
||||||
|
if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") {
|
||||||
|
return askpass();
|
||||||
|
}
|
||||||
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let log_file = args
|
||||||
|
.iter()
|
||||||
|
.position(|a| a == "--log-file")
|
||||||
|
.and_then(|i| args.get(i + 1))
|
||||||
|
.map(PathBuf::from);
|
||||||
|
match log_file {
|
||||||
|
Some(f) => logger::init_to(std::env::var("IANITOR_LOG").ok().as_deref(), Some(f)),
|
||||||
|
None => logger::init(std::env::var("IANITOR_LOG").ok().as_deref()),
|
||||||
|
}
|
||||||
|
// Windows Server, Caddy mode: started by the service control manager.
|
||||||
|
if args.first().map(String::as_str) == Some("service") {
|
||||||
|
#[cfg(windows)]
|
||||||
|
return match winsvc::run(&args[1..]) {
|
||||||
|
Ok(()) => ExitCode::SUCCESS,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("ianitor-control: {e}");
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
};
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
eprintln!("ianitor-control: `service` is for Windows; use the systemd units on Linux");
|
||||||
|
return ExitCode::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let rt = match tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
{
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("ianitor-control: cannot start: {e}");
|
||||||
|
return ExitCode::FAILURE;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let result = match args.first().map(String::as_str) {
|
||||||
|
Some("token") => token(&args[1..]),
|
||||||
|
Some("pki") => pki_cli(&args[1..]),
|
||||||
|
Some("team") => team_cli(&args[1..]),
|
||||||
|
Some("ca") => ca(&args[1..]),
|
||||||
|
Some("openapi") => {
|
||||||
|
println!("{}", ianitor_control::api::openapi_json());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")),
|
||||||
|
// Caddy trial deadline (ianitor_control::caddy_guard): after control stops, and the guard.
|
||||||
|
Some(verb @ ("caddy-revert" | "caddy-guard")) => match args
|
||||||
|
.iter()
|
||||||
|
.position(|a| a == "--config")
|
||||||
|
.and_then(|i| args.get(i + 1))
|
||||||
|
{
|
||||||
|
Some(p) => match Config::load(&PathBuf::from(p)) {
|
||||||
|
Ok(cfg) if verb == "caddy-guard" => {
|
||||||
|
rt.block_on(ianitor_control::caddy_guard::run(cfg))
|
||||||
|
}
|
||||||
|
Ok(cfg) => rt
|
||||||
|
.block_on(ianitor_control::caddy_guard::revert_after_stop(&cfg))
|
||||||
|
.map(|done| {
|
||||||
|
if done {
|
||||||
|
eprintln!("Caddy is back on the last good config.");
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
Err(e) => Err(e.to_string()),
|
||||||
|
},
|
||||||
|
None => return usage(),
|
||||||
|
},
|
||||||
|
Some("--dev") => rt.block_on(dev::run(&args[1..])),
|
||||||
|
Some("--config") => match args.get(1) {
|
||||||
|
Some(p) => match Config::load(&PathBuf::from(p)) {
|
||||||
|
Ok(cfg) => rt.block_on(ianitor_control::serve(cfg, ianitor_control::stop_signal())),
|
||||||
|
Err(e) => Err(e.to_string()),
|
||||||
|
},
|
||||||
|
None => return usage(),
|
||||||
|
},
|
||||||
|
Some("--help" | "-h") | None => return usage(),
|
||||||
|
Some(_) => return usage(),
|
||||||
|
};
|
||||||
|
match result {
|
||||||
|
Ok(()) => ExitCode::SUCCESS,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::control", "{e}");
|
||||||
|
eprintln!("ianitor-control: {e}");
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,445 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Every user-facing message, by code, in the words of docs/ui-api.md §3. `{x}` is filled from
|
||||||
|
//! the params; a missing param leaves a plain gap rather than a placeholder.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
pub type Params = BTreeMap<String, String>;
|
||||||
|
|
||||||
|
fn template(code: &str) -> &'static str {
|
||||||
|
match code {
|
||||||
|
// 3.1 host form
|
||||||
|
"host.hostname.missing" => "Enter the address people will type, like wiki.home.example.",
|
||||||
|
"host.hostname.uppercase" => "Use lowercase letters only: {suggestion}.",
|
||||||
|
"host.hostname.characters" => "Use only letters a–z, digits, dots and dashes.",
|
||||||
|
"host.hostname.spaces" => "Remove the spaces from the address.",
|
||||||
|
"host.hostname.wildcard" => {
|
||||||
|
"Addresses with * are not supported yet. Add each name as its own host."
|
||||||
|
}
|
||||||
|
"host.hostname.trailing_dot" => "Remove the dot at the end.",
|
||||||
|
"host.hostname.empty_label" => "There are two dots in a row. Remove one.",
|
||||||
|
"host.hostname.label_dash" => "A part of the address cannot start or end with a dash.",
|
||||||
|
"host.hostname.label_long" => "Each part between dots can be at most 63 characters.",
|
||||||
|
"host.hostname.too_long" => "The address can be at most 253 characters.",
|
||||||
|
"host.hostname.numeric" => {
|
||||||
|
"That looks like an IP address. Use a name, like wiki.home.example."
|
||||||
|
}
|
||||||
|
"host.hostname.taken" => "{hostname} is already a host.",
|
||||||
|
"host.hostname.mismatch" => {
|
||||||
|
"The address in the form ({hostname}) is not the host you are editing ({path_hostname})."
|
||||||
|
}
|
||||||
|
"host.file_name" => "The address does not match the file it is stored in.",
|
||||||
|
"host.upstreams.missing" => {
|
||||||
|
"Enter where Ianitor should send traffic, like http://10.0.0.23:3000."
|
||||||
|
}
|
||||||
|
"host.upstream.not_url" => "Write it as a full address, like http://10.0.0.23:3000.",
|
||||||
|
"host.upstream.scheme" => "Start the address with http:// or https://.",
|
||||||
|
"host.upstream.no_host" => "Add the server's name or IP address after http://.",
|
||||||
|
"host.upstream.host_name" => {
|
||||||
|
"The server name is not usable. Use letters a–z, digits, dots and dashes, or an IP address."
|
||||||
|
}
|
||||||
|
"host.upstream.no_port" => "Add the port at the end, like :3000.",
|
||||||
|
"host.upstream.port_zero" => {
|
||||||
|
"Port 0 cannot be used. Enter the port the service listens on."
|
||||||
|
}
|
||||||
|
"host.upstream.path" => "Leave out the path after the port. Visitors keep their own path.",
|
||||||
|
"host.upstream.query" | "host.upstream.fragment" => "Leave out everything after ? or #.",
|
||||||
|
"host.upstream.credentials" => {
|
||||||
|
"Leave out the user name and password. Put them in a header rule with a secret instead."
|
||||||
|
}
|
||||||
|
"host.upstream.duplicate" => "This address is listed twice.",
|
||||||
|
"host.upstream.mixed_schemes" => {
|
||||||
|
"All addresses for one host must start the same way: all http:// or all https://."
|
||||||
|
}
|
||||||
|
"host.upstream.too_many" => "One host can send traffic to at most {max} addresses.",
|
||||||
|
"host.auth.not_configured" => {
|
||||||
|
"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."
|
||||||
|
}
|
||||||
|
"host.header.name" => "\"{name}\" cannot be a header name. Use letters, digits and dashes.",
|
||||||
|
"host.header.value" => {
|
||||||
|
"This value has characters a header cannot carry. Use visible characters and spaces only."
|
||||||
|
}
|
||||||
|
"host.header.empty" => "Enter a value, or choose Remove to drop the header.",
|
||||||
|
"host.header.protected" => "Ianitor sets {name} itself, so a rule cannot change it.",
|
||||||
|
"host.header.duplicate" => "{name} already has a rule in this list.",
|
||||||
|
"host.header.both" => "Choose a fixed value or a secret, not both.",
|
||||||
|
"host.header.remove_value" => "Remove needs only the header name.",
|
||||||
|
"host.header.secret_unknown" => {
|
||||||
|
"There is no secret named {secret}. Secrets are listed in ianitor.toml and loaded from the server's credentials."
|
||||||
|
}
|
||||||
|
"host.header.secret_response" => {
|
||||||
|
"Secrets can only be sent to your service, never back to visitors."
|
||||||
|
}
|
||||||
|
"host.health.path" => "Start with / and use plain characters, like /health.",
|
||||||
|
"host.health.interval" => "Check every 1 to 3600 seconds.",
|
||||||
|
"host.field.unknown" => "Ianitor does not know the setting \"{field}\".",
|
||||||
|
"host.field.invalid" | "file.field.invalid" => {
|
||||||
|
"One of the settings has a value Ianitor cannot use. Show details to see which."
|
||||||
|
}
|
||||||
|
"file.field.missing" => "The setting \"{field}\" is missing.",
|
||||||
|
"change.conflict" => {
|
||||||
|
"{hostname} was changed at {time} (\"{summary}\") after you opened it. Your edits are still here. Check them, then Apply again."
|
||||||
|
}
|
||||||
|
"change.unchanged" => "This is the same as what is live now, so nothing changed.",
|
||||||
|
"host.not_found" => "{hostname} is no longer a host.",
|
||||||
|
"host.share.no_signin" => {
|
||||||
|
"Anyone can already open {hostname}, so a share link changes nothing."
|
||||||
|
}
|
||||||
|
// 3.2 apply, undo, restore, repository
|
||||||
|
"apply.queued" => "Waiting for \"{summary}\" to finish, about {seconds} s.",
|
||||||
|
"apply.kept" => "{hostname} is live. Health checks passed for {seconds} s.",
|
||||||
|
"apply.kept.no_watch" => {
|
||||||
|
"{hostname} is live. It has no health check, so Ianitor only checked that it answers."
|
||||||
|
}
|
||||||
|
"apply.kept.removed" => "{hostname} is removed.",
|
||||||
|
"apply.kept.no_edge" => {
|
||||||
|
"Saved. No proxy is attached (development mode), so nothing was checked."
|
||||||
|
}
|
||||||
|
"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."
|
||||||
|
}
|
||||||
|
"apply.reverted.timeout" => {
|
||||||
|
"{hostname} was not {verb}. {upstream} did not answer within 5 seconds on {count} of {of} checks. Ianitor undid the change."
|
||||||
|
}
|
||||||
|
"apply.reverted.not_found" => {
|
||||||
|
"{hostname} was not {verb}. {upstream} says {path} does not exist. Check the health check address. Ianitor undid the change."
|
||||||
|
}
|
||||||
|
"apply.reverted.server_error" => {
|
||||||
|
"{hostname} was not {verb}. {upstream} answered with an error page on {count} of {of} checks. Ianitor undid the change."
|
||||||
|
}
|
||||||
|
"apply.reverted.redirect" => {
|
||||||
|
"{hostname} was not {verb}. {upstream} sent visitors elsewhere instead of answering {path}. Use an address that answers directly, like /health."
|
||||||
|
}
|
||||||
|
"apply.reverted.sign_in" => {
|
||||||
|
"{hostname} was not {verb}. {upstream} asked for a sign-in on {path}. Use an address that answers without signing in."
|
||||||
|
}
|
||||||
|
"apply.reverted.name" => {
|
||||||
|
"{hostname} was not {verb}. The name {upstream_host} could not be found on this network."
|
||||||
|
}
|
||||||
|
"apply.reverted.tls" => {
|
||||||
|
"{hostname} was not {verb}. {upstream} uses https://, but its certificate could not be checked."
|
||||||
|
}
|
||||||
|
"apply.reverted.no_answer" => {
|
||||||
|
"{hostname} was not {verb}. No health check finished within {seconds} s. Ianitor undid the change."
|
||||||
|
}
|
||||||
|
"apply.reverted.edge_lost" => {
|
||||||
|
"The proxy restarted during the check, so it went back to the last good settings. Ianitor undid the change to match."
|
||||||
|
}
|
||||||
|
"apply.failed.reload" => {
|
||||||
|
"{engine} did not take the new settings, so nothing changed. Every host kept running."
|
||||||
|
}
|
||||||
|
"apply.failed.build" => {
|
||||||
|
"Ianitor could not build the settings for this change, so nothing changed."
|
||||||
|
}
|
||||||
|
"apply.failed.validation" => {
|
||||||
|
"This change no longer fits with the routes: {first_error} Nothing changed."
|
||||||
|
}
|
||||||
|
"apply.failed.edge_unreachable" => {
|
||||||
|
"Ianitor cannot reach the proxy right now, so nothing changed. Traffic is not affected."
|
||||||
|
}
|
||||||
|
"apply.interrupted" => {
|
||||||
|
"Ianitor restarted during the check, so it undid the change to be safe."
|
||||||
|
}
|
||||||
|
"apply.interrupted.queued" => {
|
||||||
|
"Ianitor restarted before this change ran, so nothing changed. Try again."
|
||||||
|
}
|
||||||
|
"apply.cancelled" => "Cancelled before it started. Nothing changed.",
|
||||||
|
"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."
|
||||||
|
}
|
||||||
|
"push.failed.unreachable" => {
|
||||||
|
"Kept, but not yet saved to {remote}: {remote} did not answer. Ianitor tries again at {time}."
|
||||||
|
}
|
||||||
|
"push.failed.rejected" => {
|
||||||
|
"Kept, but {remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server."
|
||||||
|
}
|
||||||
|
"push.failed.auth" => {
|
||||||
|
"Kept, but {remote} refused Ianitor's access key. Check the key in Custos."
|
||||||
|
}
|
||||||
|
"undo.nothing" => "Nothing to undo yet.",
|
||||||
|
"undo.watching" => "Wait for the check to finish ({seconds} s).",
|
||||||
|
"undo.paused" => "Changes are paused, so Undo is not available.",
|
||||||
|
"undo.target_moved" => {
|
||||||
|
"The last change is now \"{summary}\", so Undo did nothing. Look again and choose."
|
||||||
|
}
|
||||||
|
"restore.same" => "This version is the same as the current one. Nothing to restore.",
|
||||||
|
"restore.not_kept" => {
|
||||||
|
"This change was undone at the time, so there is nothing to go back to."
|
||||||
|
}
|
||||||
|
"change.not_found" => "There is no change with that id.",
|
||||||
|
"repo.unreadable" => {
|
||||||
|
"{file} in the routes repository cannot be read. Changes are paused until it is fixed."
|
||||||
|
}
|
||||||
|
"repo.unexpected_file" => "{file} does not belong in the routes repository.",
|
||||||
|
"repo.no_remote" => "No place to push to is set up.",
|
||||||
|
// 3.4 share links
|
||||||
|
"share.disabled" => {
|
||||||
|
"Share links are off for {hostname}. Turning them on is a change to the host, checked like any other."
|
||||||
|
}
|
||||||
|
"share.prefix" => "Start with /, like /share/summer-2026. / shares the whole site.",
|
||||||
|
"share.expiry" => "Choose between 1 hour and 90 days.",
|
||||||
|
"share.password_short" => "Use at least 8 characters.",
|
||||||
|
"share.password_long" => "Use at most 128 characters.",
|
||||||
|
"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.unavailable" => {
|
||||||
|
"Share links are not set up on this server: the share-link key is missing from the credentials."
|
||||||
|
}
|
||||||
|
"share.too_many" => {
|
||||||
|
"There are 2,000 active share links already. Stop some, or stop all, then try again."
|
||||||
|
}
|
||||||
|
"share.not_found" => "There is no share link with that id.",
|
||||||
|
"share.replaces" => "The link to replace is not a link for {hostname}.",
|
||||||
|
// 3.5 tokens, limits
|
||||||
|
"token.missing" => "This request needs an API token. Make one in Settings, API.",
|
||||||
|
"token.unknown" => {
|
||||||
|
"This API token is not one Ianitor issued, or it was copied incompletely."
|
||||||
|
}
|
||||||
|
"token.expired" => {
|
||||||
|
"This API token expired on {date}. Make a new one in Settings, API, then revoke this one."
|
||||||
|
}
|
||||||
|
"token.revoked" => "This API token was revoked on {date}.",
|
||||||
|
"token.not_found" => "There is no API token with that id.",
|
||||||
|
"token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.",
|
||||||
|
"token.expiry" => "Choose between 1 and 3650 days, or never.",
|
||||||
|
"token.scope" => {
|
||||||
|
"This API token may only open and close branch previews (/api/v1/previews)."
|
||||||
|
}
|
||||||
|
"token.scope_value" => "A token's scope is full or previews.",
|
||||||
|
"session.code" => {
|
||||||
|
"This sign-in link does not work: it was used, it expired, or it was mistyped. Ask an admin for a new one."
|
||||||
|
}
|
||||||
|
"session.unknown" => {
|
||||||
|
"You are signed out. Open your sign-in link again, or ask an admin for one."
|
||||||
|
}
|
||||||
|
"team.admin_only" => "Only an admin of this team can do that.",
|
||||||
|
"team.last_admin" => "The team needs at least one admin. Make someone else an admin first.",
|
||||||
|
"team.full" => "The team is full (64 people, 100 open invites).",
|
||||||
|
"team.name" => "Enter a name of 1 to 64 characters.",
|
||||||
|
"team.role" => "A role is admin or member.",
|
||||||
|
"team.root" => "That is not a Tessera root. Copy it from Custos, Domi identity.",
|
||||||
|
"team.not_found" => "There is no such member or invite.",
|
||||||
|
"team.session_only" => "Only a signed-in person can do that, not an API token.",
|
||||||
|
"preview.off" => {
|
||||||
|
"Previews are off on this server: set a preview domain under [previews] in control.toml."
|
||||||
|
}
|
||||||
|
"preview.taken" => {
|
||||||
|
"{hostname} is already used by another host or branch, so this branch's preview cannot have it."
|
||||||
|
}
|
||||||
|
"preview.not_found" => "There is no preview at that address.",
|
||||||
|
"preview.branch" => "The branch name {problem}.",
|
||||||
|
"preview.project" => "The project name {problem}.",
|
||||||
|
"preview.domain" => "The preview address is not usable: {problem}.",
|
||||||
|
"preview.ttl" => "Choose a lifetime between {min} and {max} seconds.",
|
||||||
|
"preview.upstream" => {
|
||||||
|
"Write the preview's address as http://host:port or https://host:port, without a path, user or password."
|
||||||
|
}
|
||||||
|
"preview.upstream_not_allowed" => {
|
||||||
|
"{upstream} is not an address previews may use. Allowed: {allowed}."
|
||||||
|
}
|
||||||
|
"preview.too_many" => "There are already {max} previews. Close some first.",
|
||||||
|
"preview.expired" => "Preview of {branch} expired",
|
||||||
|
"rate.limited" => "Too many requests in a short time. Try again in {seconds} s.",
|
||||||
|
"control.files_unwritten" => {
|
||||||
|
"The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them."
|
||||||
|
}
|
||||||
|
"control.paused" => "Changes are paused: {reason} Traffic keeps flowing.",
|
||||||
|
// request shape
|
||||||
|
"request.body" => "The request body is not valid: {problem}",
|
||||||
|
"request.body_unknown_field" => "Ianitor does not know the field \"{field}\".",
|
||||||
|
"request.too_large" => "The request body is too large.",
|
||||||
|
"request.csrf" => {
|
||||||
|
"This request came from a browser page without Ianitor's UI header, so it was refused."
|
||||||
|
}
|
||||||
|
"request.host" => "This request was sent to an address Ianitor does not answer on.",
|
||||||
|
"request.not_found" => "There is no such API call.",
|
||||||
|
"request.method" => "This API call does not take that method.",
|
||||||
|
"request.in_progress" => {
|
||||||
|
"The first request with this Idempotency-Key is still being handled. Try again in a moment."
|
||||||
|
}
|
||||||
|
"request.idempotency" => "This Idempotency-Key was already used for a different request.",
|
||||||
|
"request.base_rev" => "base_rev is not a commit in the routes history.",
|
||||||
|
"health.unavailable" => {
|
||||||
|
"Ianitor cannot read health from {engine} right now. Traffic is not affected."
|
||||||
|
}
|
||||||
|
// 3.6 PKI
|
||||||
|
"pki.waiting" => {
|
||||||
|
"Open Custos on your phone. Approve only if it shows the same code: {code}."
|
||||||
|
}
|
||||||
|
"pki.waiting.manual" => {
|
||||||
|
"Approve it on the server: run ianitor-control pki approve {code}. Approve only if the code matches."
|
||||||
|
}
|
||||||
|
"pki.renew.manual" => {
|
||||||
|
"Sign this request on the offline computer and check that its fingerprint matches (Sign by hand shows both), then install the certificate."
|
||||||
|
}
|
||||||
|
"pki.denied" => "The request was turned down. Nothing was issued.",
|
||||||
|
"pki.expired" => "Nobody approved it in time, so the request closed. Nothing was issued.",
|
||||||
|
"pki.custos_unreachable" => "Custos is not answering, so the request could not be sent.",
|
||||||
|
"pki.device_name_taken" => {
|
||||||
|
"A device with this name already has a certificate or an open request. Use another name, or revoke the old one first."
|
||||||
|
}
|
||||||
|
"pki.device_name" => "Give the device a name of 1 to 64 characters.",
|
||||||
|
"pki.device_kind" => "Choose phone, computer or app.",
|
||||||
|
"pki.issued" => "{name} has a certificate.",
|
||||||
|
"pki.bundle_used" => {
|
||||||
|
"This download was already used or has expired. Make a new one from the device's row."
|
||||||
|
}
|
||||||
|
"pki.renew_due" => "The Domi intermediate certificate expires in {days} days, on {date}.",
|
||||||
|
"pki.renew_urgent" => {
|
||||||
|
"The Domi intermediate certificate expires in {days} days. After that, Domi certificates stop working."
|
||||||
|
}
|
||||||
|
"pki.intermediate_expired" => {
|
||||||
|
"The Domi intermediate certificate has expired. Hosts with a Domi certificate are not trusted until it is renewed."
|
||||||
|
}
|
||||||
|
"pki.renewed" => "Renewed. The Domi intermediate certificate is now valid until {date}.",
|
||||||
|
"pki.not_configured" => {
|
||||||
|
"The Domi certificate authority is not set up on this server. See docs/pki.md."
|
||||||
|
}
|
||||||
|
"pki.no_password" => {
|
||||||
|
"The password for the Domi certificate keys is missing from the server's credentials, so nothing can be issued."
|
||||||
|
}
|
||||||
|
"pki.wrong_password" => {
|
||||||
|
"The password for the Domi certificate keys does not open them. Check the pki-password credential."
|
||||||
|
}
|
||||||
|
"pki.no_intermediate" => {
|
||||||
|
"There is no Domi intermediate certificate yet, so Domi certificates cannot be issued. Set it up first in Certificates."
|
||||||
|
}
|
||||||
|
"pki.not_our_root" => {
|
||||||
|
"This certificate was not signed by the Domi root this server trusts."
|
||||||
|
}
|
||||||
|
"pki.wrong_key" => {
|
||||||
|
"This certificate was made for another request. Sign the request shown here, then try again."
|
||||||
|
}
|
||||||
|
"pki.bad_certificate" => {
|
||||||
|
"This is not a Domi intermediate certificate Ianitor can use. It must be a CA with path length 0 that is valid now."
|
||||||
|
}
|
||||||
|
"pki.request_not_found" => "There is no such request.",
|
||||||
|
"pki.request_closed" => "This request is closed. Start a new one.",
|
||||||
|
"pki.wrong_code" => "That code does not match the request.",
|
||||||
|
"pki.too_many_requests" => "Too many requests are open. Finish or cancel some first.",
|
||||||
|
"pki.device_not_found" => "There is no such device.",
|
||||||
|
"pki.device_not_valid" => {
|
||||||
|
"This device's certificate is revoked or expired, so it cannot be installed. Issue a new one."
|
||||||
|
}
|
||||||
|
"pki.revoked" => {
|
||||||
|
"Revoked. {name} can no longer reach hosts that need a device certificate."
|
||||||
|
}
|
||||||
|
// UI sign-in
|
||||||
|
"ui.no_proof" => {
|
||||||
|
"This request carries a sign-in header but did not come through Ianitor's proxy, so it was refused."
|
||||||
|
}
|
||||||
|
"ui.no_user" => "The sign-in did not say who you are. Sign in again.",
|
||||||
|
// engine switch
|
||||||
|
"engine.unmanaged" => {
|
||||||
|
"This server does not let Ianitor switch engines (no engine settings in control.toml)."
|
||||||
|
}
|
||||||
|
"engine.same" => "{engine} is already serving.",
|
||||||
|
"engine.switching" => "A switch is already running. Wait for it to finish.",
|
||||||
|
"engine.busy" => "A change is being applied. Switch when it has finished.",
|
||||||
|
"engine.switched" => "{engine} is serving now.",
|
||||||
|
"engine.switch_failed" => {
|
||||||
|
"{engine} did not start, so Ianitor went back to {previous}. Traffic is served as before."
|
||||||
|
}
|
||||||
|
"host.header.proof" => {
|
||||||
|
"Only a host behind sign-in can send the ui-proof secret. Choose Sign in first, or remove the rule."
|
||||||
|
}
|
||||||
|
"host.header.proof_host" => {
|
||||||
|
"Only the web UI's admin host can send the ui-proof secret, and {hostname} is not it ([ui] hostname in control.toml)."
|
||||||
|
}
|
||||||
|
"pki.manual.not_ca" => {
|
||||||
|
"This certificate cannot sign other certificates. Sign it again with the signing settings file (.ext)."
|
||||||
|
}
|
||||||
|
"pki.manual.eku" => {
|
||||||
|
"This certificate is limited to some uses, so it could not issue both host and device certificates. Sign it again with the signing settings file (.ext)."
|
||||||
|
}
|
||||||
|
"pki.manual.dates" => {
|
||||||
|
"This certificate is not valid yet, has already expired, or lasts longer than the Domi root. Check the offline computer's clock and use -days 365."
|
||||||
|
}
|
||||||
|
"pki.devices_unwritten" => {
|
||||||
|
"The device list could not be saved or handed to the proxy, so the change is not in force yet. Ianitor keeps trying; try again in a moment."
|
||||||
|
}
|
||||||
|
"engine.not_ready" => {
|
||||||
|
"Caddy is not ready: its settings could not be built from the current routes."
|
||||||
|
}
|
||||||
|
// The eight codes the UI hand-off gave sentences for (handoff §12.2, decision Q12).
|
||||||
|
"repo.duplicate_file" => {
|
||||||
|
"Two files in the routes repository describe {hostname}. Remove one, then Ianitor picks it up."
|
||||||
|
}
|
||||||
|
"file.syntax" => {
|
||||||
|
"{file} in the routes repository has a typing mistake. Changes are paused until it is fixed."
|
||||||
|
}
|
||||||
|
"file.too_large" => {
|
||||||
|
"{file} in the routes repository is too large to read. Changes are paused until it is fixed."
|
||||||
|
}
|
||||||
|
"site.field.unknown" => "ianitor.toml has a setting Ianitor does not know: \"{field}\".",
|
||||||
|
"site.forward_auth" => {
|
||||||
|
"The sign-in settings in ianitor.toml cannot be used. Show details to see why."
|
||||||
|
}
|
||||||
|
"site.forward_auth.header" => {
|
||||||
|
"ianitor.toml asks sign-in to pass on \"{name}\", which cannot be a header name."
|
||||||
|
}
|
||||||
|
"site.secret.name" => {
|
||||||
|
"\"{name}\" cannot be a secret name in ianitor.toml. Use letters, digits, dashes and underscores."
|
||||||
|
}
|
||||||
|
"site.acme" => {
|
||||||
|
"The Let's Encrypt settings in ianitor.toml cannot be used. Show details to see why."
|
||||||
|
}
|
||||||
|
"share.engine_caddy" => {
|
||||||
|
"Share links are paused while Caddy serves. They work again after switching back."
|
||||||
|
}
|
||||||
|
"internal" => "Something went wrong inside Ianitor control. Show details for more.",
|
||||||
|
_ => "Something went wrong.",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The message for `code`, with params filled in.
|
||||||
|
pub fn message(code: &str, params: &Params) -> String {
|
||||||
|
let t = template(code);
|
||||||
|
let mut out = String::with_capacity(t.len() + 32);
|
||||||
|
let mut rest = t;
|
||||||
|
while let Some(start) = rest.find('{') {
|
||||||
|
out.push_str(&rest[..start]);
|
||||||
|
let after = &rest[start + 1..];
|
||||||
|
match after.find('}') {
|
||||||
|
Some(end) => {
|
||||||
|
let key = &after[..end];
|
||||||
|
if let Some(v) = params.get(key) {
|
||||||
|
out.push_str(v);
|
||||||
|
}
|
||||||
|
rest = &after[end + 1..];
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
out.push_str(&rest[start..]);
|
||||||
|
rest = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str(rest);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn params<const N: usize>(pairs: [(&str, String); N]) -> Params {
|
||||||
|
pairs.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn placeholders_are_filled() {
|
||||||
|
let p = params([("hostname", "a.test".into()), ("max", "64".into())]);
|
||||||
|
assert_eq!(
|
||||||
|
message("host.hostname.taken", &p),
|
||||||
|
"a.test is already a host."
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
message("host.upstream.too_many", &p),
|
||||||
|
"One host can send traffic to at most 64 addresses."
|
||||||
|
);
|
||||||
|
assert!(!message("token.revoked", &Params::new()).contains('{'));
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,270 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Control's side of the Domi CA: certificates for the hosts of every tree that is applied,
|
||||||
|
//! the device files both engines read, and what happens after an approval, a renewal or a
|
||||||
|
//! revocation.
|
||||||
|
|
||||||
|
// A refusal is built once per failed request; boxing it buys nothing.
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use ianitor_core::TlsMode;
|
||||||
|
|
||||||
|
use crate::engine::{Control, Fail};
|
||||||
|
use crate::messages::{self, Params};
|
||||||
|
use crate::pki::PkiFail;
|
||||||
|
use crate::util::now;
|
||||||
|
|
||||||
|
/// The HTTP status for a PKI refusal.
|
||||||
|
pub fn status_of(code: &str) -> u16 {
|
||||||
|
match code {
|
||||||
|
"pki.request_not_found" | "pki.device_not_found" => 404,
|
||||||
|
"pki.bundle_used" => 410,
|
||||||
|
"pki.bad_certificate"
|
||||||
|
| "pki.not_our_root"
|
||||||
|
| "pki.wrong_key"
|
||||||
|
| "pki.device_name"
|
||||||
|
| "pki.device_kind"
|
||||||
|
| "pki.wrong_code"
|
||||||
|
| "pki.manual.not_ca"
|
||||||
|
| "pki.manual.eku"
|
||||||
|
| "pki.manual.dates" => 422,
|
||||||
|
"pki.devices_unwritten" => 503,
|
||||||
|
"pki.too_many_requests" => 429,
|
||||||
|
_ => 409,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pki_fail(e: PkiFail) -> Fail {
|
||||||
|
match e {
|
||||||
|
PkiFail::Code(c) => Fail::new(status_of(c), c, Params::new()),
|
||||||
|
PkiFail::Internal(d) => Fail::new(500, "internal", Params::new()).detail(d),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Control {
|
||||||
|
pub fn pki_or_fail(&self) -> Result<&crate::pki::Pki, Fail> {
|
||||||
|
self.pki
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| Fail::new(409, "pki.not_configured", Params::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every certificate directory a compiler output points at.
|
||||||
|
fn cert_dirs(&self) -> Vec<&Path> {
|
||||||
|
let mut v = vec![Path::new(&self.cfg.compile.cert_dir)];
|
||||||
|
let c = Path::new(&self.cfg.caddy_compile().cert_dir);
|
||||||
|
if c != v[0] {
|
||||||
|
v.push(c);
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Before a tree goes live: server certificates for its `tls = "domi"` hosts and the
|
||||||
|
/// device files when a host needs them. Without `[pki]` nothing is issued (the files are
|
||||||
|
/// expected to be there, as in phase 2). Returns whether a file changed.
|
||||||
|
pub fn pki_prepare(&self, model: &ianitor_core::Model) -> Result<bool, Fail> {
|
||||||
|
let Some(p) = &self.pki else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
let t = now();
|
||||||
|
let domi: Vec<String> = model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.filter(|h| h.tls == TlsMode::Domi)
|
||||||
|
.map(|h| h.hostname.to_string())
|
||||||
|
.collect();
|
||||||
|
let mut changed = false;
|
||||||
|
for dir in self.cert_dirs() {
|
||||||
|
let issued = p.ensure_host_certs(&domi, dir, t).map_err(|e| {
|
||||||
|
let mut f = pki_fail(e);
|
||||||
|
// The apply's reason names a host so the UI can point at it.
|
||||||
|
if let Some(h) = domi.first() {
|
||||||
|
f.reason.hostname = Some(h.clone());
|
||||||
|
}
|
||||||
|
f
|
||||||
|
})?;
|
||||||
|
if !issued.is_empty() {
|
||||||
|
log::info!(target: "ianitor::pki", "issued server certificates for {}", issued.join(", "));
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
// Always: the files are tiny, and a list that failed to be written catches up here.
|
||||||
|
changed |= p.write_device_files(dir, t).map_err(pki_fail)?;
|
||||||
|
}
|
||||||
|
Ok(changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every couple of seconds: act on approvals; once an hour: renew server certificates.
|
||||||
|
pub async fn pki_poller(self: Arc<Self>) {
|
||||||
|
if self.pki.is_none() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut last_renewal_check = now();
|
||||||
|
// At start: bring the device files in line (a revocation that could not be written
|
||||||
|
// before a restart is in force now).
|
||||||
|
let _ = self.devices_changed().await;
|
||||||
|
loop {
|
||||||
|
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||||
|
let me = self.clone();
|
||||||
|
let polled = tokio::task::spawn_blocking(move || match &me.pki {
|
||||||
|
Some(p) => p.poll(now()),
|
||||||
|
None => Ok(Default::default()),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let changes = match polled {
|
||||||
|
Ok(Ok(c)) => c,
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
log::error!(target: "ianitor::pki", "{e}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::pki", "pki poll crashed: {e}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let t = now();
|
||||||
|
if changes.intermediate || t.saturating_sub(last_renewal_check) >= 3600 {
|
||||||
|
last_renewal_check = t;
|
||||||
|
self.refresh_certificates(changes.intermediate).await;
|
||||||
|
}
|
||||||
|
let retry = self
|
||||||
|
.devices_problem
|
||||||
|
.lock()
|
||||||
|
.map(|p| p.is_some())
|
||||||
|
.unwrap_or(false);
|
||||||
|
if changes.devices || retry {
|
||||||
|
let _ = self.devices_changed().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Issue what the current tree needs (after a new intermediate: everything) and reload
|
||||||
|
/// the engine that serves, under the apply lock so no trial is running.
|
||||||
|
pub async fn refresh_certificates(&self, new_intermediate: bool) {
|
||||||
|
let _lock = self.apply_lock.lock().await;
|
||||||
|
let Ok((_, _, model)) = self.head_model() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match self.pki_prepare(&model) {
|
||||||
|
Ok(changed) if changed || new_intermediate => {
|
||||||
|
if new_intermediate {
|
||||||
|
log::info!(target: "ianitor::pki", "new Domi intermediate installed; certificates reissued");
|
||||||
|
}
|
||||||
|
self.reload_serving_engine().await;
|
||||||
|
}
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(f) => {
|
||||||
|
log::error!(target: "ianitor::pki", "certificates not renewed: {}", f.reason.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The device files changed (issue or revoke): rewrite them and tell the engine at once.
|
||||||
|
///
|
||||||
|
/// It never waits for an apply (fix round 3): the files go to disk at once and edge is told
|
||||||
|
/// at once, also during a watch (edge's trial reads the same files). Only when Caddy serves
|
||||||
|
/// *and* a trial is out is the Caddy reload left to the end of that apply: a reload now
|
||||||
|
/// would drop the trial, and the end of every Caddy trial loads caddy.json again (promote,
|
||||||
|
/// revert, caddy-guard, caddy-revert), which reads the new files. During an engine switch
|
||||||
|
/// (engine lock busy for more than a second) the engine being started reads them anyway.
|
||||||
|
pub async fn devices_changed(&self) -> Result<(), String> {
|
||||||
|
let Some(p) = &self.pki else { return Ok(()) };
|
||||||
|
let _files = self.devices_lock.lock().await;
|
||||||
|
let t = now();
|
||||||
|
let mut result = Ok(());
|
||||||
|
for dir in self.cert_dirs() {
|
||||||
|
if let Err(e) = p.write_device_files(dir, t) {
|
||||||
|
result = Err(format!(
|
||||||
|
"the device files in {} could not be written: {e}",
|
||||||
|
dir.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The engine lock is held for long only by a switch; an apply holds it for a moment
|
||||||
|
// (loading a trial, or from the claim to the promoted reload), so then this waits.
|
||||||
|
let engine =
|
||||||
|
match tokio::time::timeout(Duration::from_secs(1), self.engine_lock.lock()).await {
|
||||||
|
Ok(g) => Some(g),
|
||||||
|
Err(_) if self.engine_state().state == "switching" => None,
|
||||||
|
Err(_) => Some(self.engine_lock.lock().await),
|
||||||
|
};
|
||||||
|
// Tell the serving engine every time, changed or not: a repeated Revoke nudges again.
|
||||||
|
// During a switch it is not told now, and never silently (QC round 4): the problem
|
||||||
|
// stays set, so the retry tells whichever engine serves once the switch is over (the
|
||||||
|
// switch itself also ends by telling it).
|
||||||
|
let mut pending = None;
|
||||||
|
if result.is_ok() {
|
||||||
|
if engine.is_none() {
|
||||||
|
pending = Some(
|
||||||
|
"an engine switch is under way; the engine that serves after it is told then"
|
||||||
|
.to_owned(),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
result = self.nudge_devices().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(mut pr) = self.devices_problem.lock() {
|
||||||
|
*pr = result.as_ref().err().cloned().or(pending.clone());
|
||||||
|
}
|
||||||
|
if let Some(p) = &pending {
|
||||||
|
log::info!(target: "ianitor::pki", "{p}");
|
||||||
|
}
|
||||||
|
if let Err(e) = &result {
|
||||||
|
log::error!(target: "ianitor::pki", "{e}; retrying");
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tell the engine that serves to read the device files again. The caller holds the engine
|
||||||
|
/// lock. Under Caddy with a trial out, the end of that apply does it (promote, revert, the
|
||||||
|
/// guard and caddy-revert all load caddy.json, which reads the files).
|
||||||
|
pub(crate) async fn nudge_devices(&self) -> Result<(), String> {
|
||||||
|
let caddy = self.engine_running() == "caddy";
|
||||||
|
if caddy && crate::caddy_guard::armed(&self.cfg.state_dir).is_some() {
|
||||||
|
log::info!(target: "ianitor::pki", "a change is being tried on Caddy; Caddy reads the new device list when it ends");
|
||||||
|
Ok(())
|
||||||
|
} else if caddy {
|
||||||
|
self.caddy_reload_checked()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("Caddy did not reload the device list: {e}"))
|
||||||
|
} else if self.edge.attached() {
|
||||||
|
self.edge
|
||||||
|
.reload_devices()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("edge did not re-read the device list: {e}"))
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reload_serving_engine(&self) {
|
||||||
|
let _engine = self.engine_lock.lock().await;
|
||||||
|
if self.engine_running() == "caddy" {
|
||||||
|
if let Err(e) = self.caddy_reload_checked().await {
|
||||||
|
log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {e}");
|
||||||
|
}
|
||||||
|
} else if self.edge.attached()
|
||||||
|
&& let Err(e) = self.edge.reload().await
|
||||||
|
{
|
||||||
|
log::error!(target: "ianitor::pki", "edge did not reload the new certificates: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The code and message for a PKI request that waits for its approval.
|
||||||
|
pub fn waiting_message(&self, kind: &str, code: &str) -> (String, String) {
|
||||||
|
let manual = self.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual");
|
||||||
|
let c = match (kind, manual) {
|
||||||
|
("intermediate", _) => "pki.renew.manual",
|
||||||
|
(_, true) => "pki.waiting.manual",
|
||||||
|
(_, false) => "pki.waiting",
|
||||||
|
};
|
||||||
|
(
|
||||||
|
c.to_owned(),
|
||||||
|
messages::message(c, &messages::params([("code", code.to_owned())])),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,598 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Branch previews for Fabrica (Fabrica docs/32_coherence.md, T4). A preview is an ordinary
|
||||||
|
//! host file in the routes repository with a `[preview]` table, so it goes through the same
|
||||||
|
//! validation, compilers, differential tests and commit-confirmed apply as any host. This
|
||||||
|
//! module holds what is preview-only: the host body control writes, the upstream allow list
|
||||||
|
//! (a preview token is hostile: it must not be able to publish this machine's admin ports),
|
||||||
|
//! and the sweeper that closes expired previews.
|
||||||
|
|
||||||
|
// A refusal is built once per failed request; boxing it buys nothing (as in `engine`).
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::config::{Config, PreviewsConfig};
|
||||||
|
use crate::engine::{Change, Control, Fail};
|
||||||
|
use crate::hostspec::{HeaderRuleSpec, HostSpec, PreviewSpec};
|
||||||
|
use crate::messages::{self, Params};
|
||||||
|
use crate::util::now;
|
||||||
|
|
||||||
|
/// The actor name the sweeper's removals carry in the history.
|
||||||
|
pub const EXPIRY_ACTOR: &str = "Preview expiry";
|
||||||
|
|
||||||
|
/// One entry of `[previews] upstreams`.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
enum Target {
|
||||||
|
Net(IpAddr, u8),
|
||||||
|
Name(String),
|
||||||
|
/// `*.suffix`: any name ending in `.suffix`.
|
||||||
|
Suffix(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct Allowed {
|
||||||
|
target: Target,
|
||||||
|
ports: Option<(u16, u16)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_ports(p: &str) -> Option<(u16, u16)> {
|
||||||
|
let (lo, hi) = match p.split_once('-') {
|
||||||
|
Some((a, b)) => (a.parse().ok()?, b.parse().ok()?),
|
||||||
|
None => {
|
||||||
|
let x: u16 = p.parse().ok()?;
|
||||||
|
(x, x)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
(lo >= 1 && lo <= hi).then_some((lo, hi))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_entry(e: &str) -> Option<Allowed> {
|
||||||
|
let e = e.trim();
|
||||||
|
// IPv6 networks carry no port (`fd00::/8`); everything else may end in `:port[-port]`.
|
||||||
|
if e.matches(':').count() > 1 {
|
||||||
|
let (ip, bits) = e.split_once('/').unwrap_or((e, "128"));
|
||||||
|
let ip: Ipv6Addr = ip.parse().ok()?;
|
||||||
|
let bits: u8 = bits.parse().ok().filter(|b| *b <= 128)?;
|
||||||
|
return Some(Allowed {
|
||||||
|
target: Target::Net(IpAddr::V6(ip), bits),
|
||||||
|
ports: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let (host, ports) = match e.rsplit_once(':') {
|
||||||
|
Some((h, p)) => (h, Some(parse_ports(p)?)),
|
||||||
|
None => (e, None),
|
||||||
|
};
|
||||||
|
if let Some((ip, bits)) = host.split_once('/') {
|
||||||
|
let ip: Ipv4Addr = ip.parse().ok()?;
|
||||||
|
let bits: u8 = bits.parse().ok().filter(|b| *b <= 32)?;
|
||||||
|
return Some(Allowed {
|
||||||
|
target: Target::Net(IpAddr::V4(ip), bits),
|
||||||
|
ports,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if let Ok(ip) = host.parse::<Ipv4Addr>() {
|
||||||
|
return Some(Allowed {
|
||||||
|
target: Target::Net(IpAddr::V4(ip), 32),
|
||||||
|
ports,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let name = host.to_ascii_lowercase();
|
||||||
|
let plain = |n: &str| {
|
||||||
|
!n.is_empty()
|
||||||
|
&& n.len() <= 253
|
||||||
|
&& n.split('.').all(|l| {
|
||||||
|
!l.is_empty()
|
||||||
|
&& l.len() <= 63
|
||||||
|
&& l.bytes()
|
||||||
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
|
||||||
|
})
|
||||||
|
};
|
||||||
|
if let Some(suffix) = name.strip_prefix("*.") {
|
||||||
|
return plain(suffix).then(|| Allowed {
|
||||||
|
target: Target::Suffix(suffix.to_owned()),
|
||||||
|
ports,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if !plain(&name) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(Allowed {
|
||||||
|
target: Target::Name(name),
|
||||||
|
ports,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn in_net(ip: IpAddr, net: IpAddr, bits: u8) -> bool {
|
||||||
|
match (ip, net) {
|
||||||
|
(IpAddr::V4(a), IpAddr::V4(n)) => {
|
||||||
|
let mask = if bits == 0 {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
u32::MAX << (32 - u32::from(bits))
|
||||||
|
};
|
||||||
|
u32::from(a) & mask == u32::from(n) & mask
|
||||||
|
}
|
||||||
|
(IpAddr::V6(a), IpAddr::V6(n)) => {
|
||||||
|
let mask = if bits == 0 {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
u128::MAX << (128 - u32::from(bits))
|
||||||
|
};
|
||||||
|
u128::from(a) & mask == u128::from(n) & mask
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Addresses no preview may ever use, whatever the allow list says.
|
||||||
|
fn never(ip: IpAddr) -> bool {
|
||||||
|
match ip {
|
||||||
|
IpAddr::V4(v) => {
|
||||||
|
v.is_unspecified() || v.is_link_local() || v.is_multicast() || v.is_broadcast()
|
||||||
|
}
|
||||||
|
IpAddr::V6(v) => {
|
||||||
|
v.is_unspecified()
|
||||||
|
|| v.is_multicast()
|
||||||
|
|| (v.segments()[0] & 0xffc0) == 0xfe80
|
||||||
|
|| v.to_ipv4_mapped().is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check the `[previews]` section at start.
|
||||||
|
pub fn check_config(p: &PreviewsConfig, cfg: &Config) -> Result<(), String> {
|
||||||
|
ianitor_core::preview::hostname("p", "main", &p.domain)
|
||||||
|
.map_err(|e| format!("previews.domain: {e}"))?;
|
||||||
|
if !["domi", "letsencrypt"].contains(&p.tls.as_str()) {
|
||||||
|
return Err("previews.tls must be domi or letsencrypt".into());
|
||||||
|
}
|
||||||
|
if !["none", "forward-auth"].contains(&p.auth.as_str()) {
|
||||||
|
return Err("previews.auth must be none or forward-auth".into());
|
||||||
|
}
|
||||||
|
for u in &p.upstreams {
|
||||||
|
if parse_entry(u).is_none() {
|
||||||
|
return Err(format!(
|
||||||
|
"previews.upstreams: {u:?} is not a network (10.0.0.0/8), an address with ports (127.0.0.1:20000-29999) or a name (app.internal, *.svc.internal)"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.min_ttl_secs == 0
|
||||||
|
|| p.min_ttl_secs > p.max_ttl_secs
|
||||||
|
|| !(p.min_ttl_secs..=p.max_ttl_secs).contains(&p.default_ttl_secs)
|
||||||
|
{
|
||||||
|
return Err(
|
||||||
|
"previews: min_ttl_secs ≤ default_ttl_secs ≤ max_ttl_secs, and min_ttl_secs > 0".into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if !(1..=3600).contains(&p.sweep_secs) || !(1..=10_000).contains(&p.max_previews) {
|
||||||
|
return Err("previews: sweep_secs 1 to 3600, max_previews 1 to 10000".into());
|
||||||
|
}
|
||||||
|
let _ = cfg;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fail(status: u16, code: &str, params: Params) -> Fail {
|
||||||
|
Fail::new(status, code, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a preview may send traffic to `upstream`; the parsed URL's host and port.
|
||||||
|
pub fn check_upstream(cfg: &Config, p: &PreviewsConfig, upstream: &str) -> Result<(), Fail> {
|
||||||
|
let bad = || fail(422, "preview.upstream", Params::new());
|
||||||
|
if upstream.is_empty()
|
||||||
|
|| upstream.len() > 512
|
||||||
|
|| !upstream.bytes().all(|c| c.is_ascii_graphic())
|
||||||
|
{
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let u = url::Url::parse(upstream).map_err(|_| bad())?;
|
||||||
|
if !["http", "https"].contains(&u.scheme())
|
||||||
|
|| !u.username().is_empty()
|
||||||
|
|| u.password().is_some()
|
||||||
|
|| u.query().is_some()
|
||||||
|
|| u.fragment().is_some()
|
||||||
|
|| !(u.path().is_empty() || u.path() == "/")
|
||||||
|
{
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let port = u.port_or_known_default().ok_or_else(bad)?;
|
||||||
|
let host = u.host().ok_or_else(bad)?;
|
||||||
|
let shown = || {
|
||||||
|
messages::params([
|
||||||
|
("upstream", upstream.to_owned()),
|
||||||
|
("allowed", {
|
||||||
|
if p.upstreams.is_empty() {
|
||||||
|
"nothing yet (set [previews] upstreams)".to_owned()
|
||||||
|
} else {
|
||||||
|
p.upstreams.join(", ")
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
};
|
||||||
|
let not_allowed = || fail(403, "preview.upstream_not_allowed", shown());
|
||||||
|
let ip = match &host {
|
||||||
|
url::Host::Ipv4(v) => Some(IpAddr::V4(*v)),
|
||||||
|
url::Host::Ipv6(v) => Some(IpAddr::V6(*v)),
|
||||||
|
url::Host::Domain(_) => None,
|
||||||
|
};
|
||||||
|
if let Some(ip) = ip {
|
||||||
|
if never(ip) {
|
||||||
|
return Err(not_allowed());
|
||||||
|
}
|
||||||
|
// This machine's own control API and Caddy admin API, whatever the list says.
|
||||||
|
if ip.is_loopback() {
|
||||||
|
let admin_ports = std::iter::once(cfg.listen.port()).chain(
|
||||||
|
[cfg.compile.caddy_admin, cfg.caddy_compile().caddy_admin]
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.map(|a| a.port()),
|
||||||
|
);
|
||||||
|
if admin_ports.into_iter().any(|a| a == port) || port == 2019 {
|
||||||
|
return Err(not_allowed());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let name = match &host {
|
||||||
|
url::Host::Domain(d) => Some(d.to_ascii_lowercase()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let ok = p.upstreams.iter().filter_map(|e| parse_entry(e)).any(|a| {
|
||||||
|
let port_ok = a.ports.is_none_or(|(lo, hi)| (lo..=hi).contains(&port));
|
||||||
|
let host_ok = match (&a.target, ip, &name) {
|
||||||
|
(Target::Net(net, bits), Some(ip), _) => in_net(ip, *net, *bits),
|
||||||
|
(Target::Name(n), _, Some(h)) => n == h,
|
||||||
|
(Target::Suffix(s), _, Some(h)) => h.ends_with(&format!(".{s}")),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
port_ok && host_ok
|
||||||
|
});
|
||||||
|
if ok { Ok(()) } else { Err(not_allowed()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host body of a branch's preview.
|
||||||
|
pub fn spec(
|
||||||
|
p: &PreviewsConfig,
|
||||||
|
hostname: &str,
|
||||||
|
project: &str,
|
||||||
|
branch: &str,
|
||||||
|
upstream: &str,
|
||||||
|
expires_at: u64,
|
||||||
|
) -> HostSpec {
|
||||||
|
HostSpec {
|
||||||
|
hostname: hostname.to_owned(),
|
||||||
|
upstreams: vec![upstream.trim_end_matches('/').to_owned()],
|
||||||
|
tls: p.tls.clone(),
|
||||||
|
auth: p.auth.clone(),
|
||||||
|
websockets: true,
|
||||||
|
share_links: false,
|
||||||
|
device_certs: false,
|
||||||
|
access_log: "off".into(),
|
||||||
|
health_check: None,
|
||||||
|
request_headers: Vec::new(),
|
||||||
|
// A preview is not for search engines.
|
||||||
|
response_headers: vec![HeaderRuleSpec {
|
||||||
|
action: "set".into(),
|
||||||
|
name: "X-Robots-Tag".into(),
|
||||||
|
value: Some("noindex, nofollow".into()),
|
||||||
|
secret: None,
|
||||||
|
}],
|
||||||
|
preview: Some(PreviewSpec {
|
||||||
|
project: project.to_owned(),
|
||||||
|
branch: branch.to_owned(),
|
||||||
|
expires_at: i64::try_from(expires_at).unwrap_or(i64::MAX),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A preview's field problem as an API refusal.
|
||||||
|
pub fn name_fail(e: ianitor_core::preview::PreviewError) -> Fail {
|
||||||
|
use ianitor_core::preview::PreviewError as P;
|
||||||
|
let (code, problem) = match &e {
|
||||||
|
P::Branch(r) => ("preview.branch", (*r).to_owned()),
|
||||||
|
P::Project(r) => ("preview.project", (*r).to_owned()),
|
||||||
|
P::Domain(r) => ("preview.domain", r.clone()),
|
||||||
|
};
|
||||||
|
let mut f = fail(422, code, messages::params([("problem", problem)]));
|
||||||
|
f.reason.field = Some(
|
||||||
|
match e {
|
||||||
|
P::Branch(_) => "branch",
|
||||||
|
P::Project(_) => "project",
|
||||||
|
P::Domain(_) => "domain",
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
);
|
||||||
|
f
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the previews screen and Fabrica see.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Listed {
|
||||||
|
pub hostname: String,
|
||||||
|
pub project: String,
|
||||||
|
pub branch: String,
|
||||||
|
pub upstream: String,
|
||||||
|
pub expires_at: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Control {
|
||||||
|
/// With `[ui] hostname` and `admin_tls`: make sure the admin host (the web UI and this
|
||||||
|
/// API, through the engine) is in the routes repository; queue it at start if not.
|
||||||
|
pub fn ensure_admin_host(&self) {
|
||||||
|
let Some(ui) = &self.cfg.ui else { return };
|
||||||
|
let (Some(host), Some(tls)) = (&ui.hostname, &ui.admin_tls) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Ok((_, tree, _)) = self.head_model() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if tree.host(host).is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let spec = HostSpec {
|
||||||
|
hostname: host.clone(),
|
||||||
|
upstreams: vec![format!("http://{}", self.cfg.listen)],
|
||||||
|
tls: tls.clone(),
|
||||||
|
auth: "none".into(),
|
||||||
|
websockets: false,
|
||||||
|
share_links: false,
|
||||||
|
device_certs: false,
|
||||||
|
access_log: "off".into(),
|
||||||
|
// No health path: every API path needs a sign-in, so a probe would see 401 and
|
||||||
|
// the apply would be reverted. Any answer from control counts as up.
|
||||||
|
health_check: None,
|
||||||
|
request_headers: Vec::new(),
|
||||||
|
response_headers: vec![
|
||||||
|
HeaderRuleSpec {
|
||||||
|
action: "set".into(),
|
||||||
|
name: "X-Robots-Tag".into(),
|
||||||
|
value: Some("noindex, nofollow".into()),
|
||||||
|
secret: None,
|
||||||
|
},
|
||||||
|
HeaderRuleSpec {
|
||||||
|
action: "set".into(),
|
||||||
|
name: "Strict-Transport-Security".into(),
|
||||||
|
value: Some("max-age=31536000".into()),
|
||||||
|
secret: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
preview: None,
|
||||||
|
};
|
||||||
|
match self.submit_as(
|
||||||
|
Change::Put { spec, create: true },
|
||||||
|
None,
|
||||||
|
"Setup",
|
||||||
|
Some(format!("Added the admin host {host} (the web UI)")),
|
||||||
|
) {
|
||||||
|
Ok(_) => log::info!(target: "ianitor::control", "adding the admin host {host}"),
|
||||||
|
Err(f) => {
|
||||||
|
log::error!(target: "ianitor::control", "cannot add the admin host {host}: {}", f.reason.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn previews_cfg(&self) -> Result<&PreviewsConfig, Fail> {
|
||||||
|
self.cfg
|
||||||
|
.previews
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| fail(409, "preview.off", Params::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every preview at the branch head, by host name.
|
||||||
|
pub fn previews(&self) -> Result<Vec<Listed>, Fail> {
|
||||||
|
let (_, _, model) = self.head_model()?;
|
||||||
|
Ok(model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.filter_map(|h| {
|
||||||
|
let p = h.preview.as_ref()?;
|
||||||
|
Some(Listed {
|
||||||
|
hostname: h.hostname.to_string(),
|
||||||
|
project: p.project.clone(),
|
||||||
|
branch: p.branch.clone(),
|
||||||
|
upstream: h
|
||||||
|
.upstreams
|
||||||
|
.first()
|
||||||
|
.map(ToString::to_string)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
expires_at: p.expires_at,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open (or move) a branch's preview.
|
||||||
|
pub fn open_preview(
|
||||||
|
&self,
|
||||||
|
project: &str,
|
||||||
|
branch: &str,
|
||||||
|
upstream: &str,
|
||||||
|
ttl: Option<u64>,
|
||||||
|
actor: &str,
|
||||||
|
) -> Result<(String, u64, crate::records::ApplyRecord), Fail> {
|
||||||
|
let p = self.previews_cfg()?;
|
||||||
|
let hostname =
|
||||||
|
ianitor_core::preview::hostname(project, branch, &p.domain).map_err(name_fail)?;
|
||||||
|
let ttl = ttl.unwrap_or(p.default_ttl_secs);
|
||||||
|
if !(p.min_ttl_secs..=p.max_ttl_secs).contains(&ttl) {
|
||||||
|
let mut f = fail(
|
||||||
|
422,
|
||||||
|
"preview.ttl",
|
||||||
|
messages::params([
|
||||||
|
("min", p.min_ttl_secs.to_string()),
|
||||||
|
("max", p.max_ttl_secs.to_string()),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
f.reason.field = Some("ttl".into());
|
||||||
|
return Err(f);
|
||||||
|
}
|
||||||
|
check_upstream(&self.cfg, p, upstream)?;
|
||||||
|
let previews = self.previews()?;
|
||||||
|
let (_, tree, model) = self.head_model()?;
|
||||||
|
let existing = model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.find(|h| h.hostname.as_str() == hostname);
|
||||||
|
let create = match existing {
|
||||||
|
None => {
|
||||||
|
if previews.len() >= p.max_previews {
|
||||||
|
return Err(fail(
|
||||||
|
409,
|
||||||
|
"preview.too_many",
|
||||||
|
messages::params([("max", p.max_previews.to_string())]),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Some(h) => match &h.preview {
|
||||||
|
Some(pv) if pv.project == project && pv.branch == branch => false,
|
||||||
|
_ => {
|
||||||
|
return Err(fail(
|
||||||
|
409,
|
||||||
|
"preview.taken",
|
||||||
|
messages::params([("hostname", hostname.clone())]),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
drop(tree);
|
||||||
|
let expires_at = now().saturating_add(ttl);
|
||||||
|
let spec = spec(p, &hostname, project, branch, upstream, expires_at);
|
||||||
|
let summary = format!(
|
||||||
|
"{} the preview of {branch} ({project})",
|
||||||
|
if create { "Opened" } else { "Moved" }
|
||||||
|
);
|
||||||
|
let rec = self.submit_as(Change::Put { spec, create }, None, actor, Some(summary))?;
|
||||||
|
Ok((hostname, expires_at, rec))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a preview by its host name. Only preview hosts.
|
||||||
|
pub fn close_preview(
|
||||||
|
&self,
|
||||||
|
hostname: &str,
|
||||||
|
actor: &str,
|
||||||
|
why: &str,
|
||||||
|
) -> Result<crate::records::ApplyRecord, Fail> {
|
||||||
|
self.previews_cfg()?;
|
||||||
|
let pv = self
|
||||||
|
.previews()?
|
||||||
|
.into_iter()
|
||||||
|
.find(|p| p.hostname == hostname)
|
||||||
|
.ok_or_else(|| fail(404, "preview.not_found", Params::new()))?;
|
||||||
|
let summary = format!("{why} preview of {} ({})", pv.branch, pv.project);
|
||||||
|
self.submit_as(
|
||||||
|
Change::Delete {
|
||||||
|
hostname: hostname.to_owned(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
actor,
|
||||||
|
Some(summary),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a preview stands: `applying`, `live`, `failed` (with why), or not a preview.
|
||||||
|
pub fn preview_state(&self, hostname: &str) -> Option<(String, Option<String>)> {
|
||||||
|
let live = self.previews().ok()?.iter().any(|p| p.hostname == hostname);
|
||||||
|
let last = self
|
||||||
|
.records()
|
||||||
|
.into_iter()
|
||||||
|
.rev()
|
||||||
|
.find(|r| r.hosts.iter().any(|h| h == hostname));
|
||||||
|
let pending = last
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()));
|
||||||
|
if pending {
|
||||||
|
return Some(("applying".into(), None));
|
||||||
|
}
|
||||||
|
if live {
|
||||||
|
return Some(("live".into(), None));
|
||||||
|
}
|
||||||
|
let r = last?;
|
||||||
|
// A preview that never went live because its apply failed.
|
||||||
|
(r.summary.contains("the preview of") && r.state != "kept").then(|| {
|
||||||
|
(
|
||||||
|
"failed".into(),
|
||||||
|
r.reason.as_ref().map(|x| x.message.clone()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close expired previews, every `sweep_secs`.
|
||||||
|
pub async fn preview_sweeper(self: Arc<Self>) {
|
||||||
|
let Some(p) = self.cfg.previews.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
loop {
|
||||||
|
tokio::time::sleep(Duration::from_secs(p.sweep_secs)).await;
|
||||||
|
let Ok(list) = self.previews() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let t = now();
|
||||||
|
let busy: Vec<String> = self
|
||||||
|
.records()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()))
|
||||||
|
.flat_map(|r| r.hosts)
|
||||||
|
.collect();
|
||||||
|
for pv in list.iter().filter(|p| p.expires_at <= t) {
|
||||||
|
if busy.contains(&pv.hostname) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match self.close_preview(&pv.hostname, EXPIRY_ACTOR, "Closed the expired") {
|
||||||
|
Ok(_) => {
|
||||||
|
log::info!(target: "ianitor::previews", "the preview {} expired; closing it", pv.hostname)
|
||||||
|
}
|
||||||
|
Err(f) => {
|
||||||
|
log::warn!(target: "ianitor::previews", "cannot close the expired preview {}: {}", pv.hostname, f.reason.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn allow_list_entries_parse() {
|
||||||
|
for ok in [
|
||||||
|
"10.0.0.0/8",
|
||||||
|
"127.0.0.1:20000-29999",
|
||||||
|
"192.168.1.5:8080",
|
||||||
|
"app.internal",
|
||||||
|
"app.internal:3000",
|
||||||
|
"*.svc.internal",
|
||||||
|
"fd00::/8",
|
||||||
|
] {
|
||||||
|
assert!(parse_entry(ok).is_some(), "{ok}");
|
||||||
|
}
|
||||||
|
for bad in [
|
||||||
|
"",
|
||||||
|
"10.0.0.0/33",
|
||||||
|
"a b",
|
||||||
|
"x:0",
|
||||||
|
"x:9-1",
|
||||||
|
"*.",
|
||||||
|
"http://x",
|
||||||
|
"1.2.3.4/8:70000",
|
||||||
|
] {
|
||||||
|
assert!(parse_entry(bad).is_none(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn networks_match() {
|
||||||
|
let n = |s: &str| s.parse::<IpAddr>().unwrap();
|
||||||
|
assert!(in_net(n("10.1.2.3"), n("10.0.0.0"), 8));
|
||||||
|
assert!(!in_net(n("11.1.2.3"), n("10.0.0.0"), 8));
|
||||||
|
assert!(in_net(n("fd12::1"), n("fd00::"), 8));
|
||||||
|
assert!(in_net(n("1.2.3.4"), n("0.0.0.0"), 0));
|
||||||
|
assert!(never(n("0.0.0.0")) && never(n("169.254.169.254")) && never(n("::ffff:127.0.0.1")));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Apply records (one per user action: the history the UI shows, docs/ui-api.md §2.1) and the
|
||||||
|
//! apply journal (what a crash interrupted).
|
||||||
|
//!
|
||||||
|
//! The journal (`journal.json`) is written, atomically and durably, before every step that
|
||||||
|
//! changes the outside world, so after a crash control knows how far an apply got:
|
||||||
|
//!
|
||||||
|
//! | stage | what has happened | recovery |
|
||||||
|
//! |:--|:--|:--|
|
||||||
|
//! | `prepared` | commit object made, branch not moved | branch at base: nothing to undo; at the commit: as `committed` |
|
||||||
|
//! | `committed` | branch moved to the commit | revert commit, abort trial, drop trial files |
|
||||||
|
//! | `trial_written` | trial files written | same |
|
||||||
|
//! | `trial_loaded` | edge serves the trial (and reverts by itself at its deadline) | same |
|
||||||
|
//! | `confirmed` | edge confirmed the trial | promote trial files, record kept |
|
||||||
|
//! | `promoted` | files promoted | record kept |
|
||||||
|
//! | `reverting` | revert started | finish the revert |
|
||||||
|
//!
|
||||||
|
//! Throughout, `edge.json` and `caddy.json` only ever hold a config that passed its watch.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
|
use crate::hostspec::HostSpec;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
|
||||||
|
pub struct Step {
|
||||||
|
/// `validate`, `compile`, `write`, `reload`, `watch` or `push`.
|
||||||
|
pub key: String,
|
||||||
|
/// `pending`, `running`, `done`, `failed` or `skipped`.
|
||||||
|
pub state: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, ToSchema)]
|
||||||
|
pub struct WatchHost {
|
||||||
|
pub hostname: String,
|
||||||
|
pub passed: u32,
|
||||||
|
pub failed: u32,
|
||||||
|
pub total: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
|
||||||
|
pub struct Watch {
|
||||||
|
/// Unix seconds.
|
||||||
|
pub ends: u64,
|
||||||
|
pub hosts: Vec<WatchHost>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why an apply did not stay (or a detail of why it did).
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, ToSchema)]
|
||||||
|
pub struct Reason {
|
||||||
|
pub code: String,
|
||||||
|
/// Plain English, from `messages`.
|
||||||
|
pub message: String,
|
||||||
|
pub hostname: Option<String>,
|
||||||
|
pub upstream: Option<String>,
|
||||||
|
pub field: Option<String>,
|
||||||
|
pub count: Option<u32>,
|
||||||
|
pub of: Option<u32>,
|
||||||
|
/// Technical detail (core's text, edge's error); never a secret.
|
||||||
|
pub detail: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub params: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One field problem, in the API error shape.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
|
||||||
|
pub struct FieldError {
|
||||||
|
pub code: String,
|
||||||
|
pub message: String,
|
||||||
|
pub field: Option<String>,
|
||||||
|
pub params: BTreeMap<String, String>,
|
||||||
|
pub detail: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
pub struct ApplyRecord {
|
||||||
|
pub id: String,
|
||||||
|
/// `add`, `edit`, `remove`, `undo`, `restore` or `share_links`.
|
||||||
|
pub kind: String,
|
||||||
|
pub summary: String,
|
||||||
|
pub hosts: Vec<String>,
|
||||||
|
/// `queued`, `validating`, `applying`, `watching`, `kept`, `reverted`, `failed` or
|
||||||
|
/// `needs_attention`.
|
||||||
|
pub state: String,
|
||||||
|
pub steps: Vec<Step>,
|
||||||
|
pub created: u64,
|
||||||
|
pub started: Option<u64>,
|
||||||
|
pub finished: Option<u64>,
|
||||||
|
pub watch: Option<Watch>,
|
||||||
|
pub reason: Option<Reason>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub errors: Vec<FieldError>,
|
||||||
|
/// Branch head when the apply started.
|
||||||
|
pub base: Option<String>,
|
||||||
|
/// The commit of this change (none if it never got one).
|
||||||
|
pub commit: Option<String>,
|
||||||
|
/// The commit that undid it, for reverted applies.
|
||||||
|
pub revert_commit: Option<String>,
|
||||||
|
pub undo_of: Option<String>,
|
||||||
|
pub restore_of: Option<String>,
|
||||||
|
/// Token name of whoever asked.
|
||||||
|
pub actor: String,
|
||||||
|
/// What was tried, for "Edit and try again".
|
||||||
|
pub attempted_host: Option<HostSpec>,
|
||||||
|
/// For undo: what it does ("Removes x").
|
||||||
|
pub effect: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const STEP_KEYS: [&str; 6] = ["validate", "compile", "write", "reload", "watch", "push"];
|
||||||
|
|
||||||
|
impl ApplyRecord {
|
||||||
|
pub fn new(
|
||||||
|
id: String,
|
||||||
|
kind: &str,
|
||||||
|
summary: String,
|
||||||
|
hosts: Vec<String>,
|
||||||
|
actor: &str,
|
||||||
|
t: u64,
|
||||||
|
) -> ApplyRecord {
|
||||||
|
ApplyRecord {
|
||||||
|
id,
|
||||||
|
kind: kind.into(),
|
||||||
|
summary,
|
||||||
|
hosts,
|
||||||
|
state: "queued".into(),
|
||||||
|
steps: STEP_KEYS
|
||||||
|
.iter()
|
||||||
|
.map(|k| Step {
|
||||||
|
key: (*k).into(),
|
||||||
|
state: "pending".into(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
created: t,
|
||||||
|
started: None,
|
||||||
|
finished: None,
|
||||||
|
watch: None,
|
||||||
|
reason: None,
|
||||||
|
errors: Vec::new(),
|
||||||
|
base: None,
|
||||||
|
commit: None,
|
||||||
|
revert_commit: None,
|
||||||
|
undo_of: None,
|
||||||
|
restore_of: None,
|
||||||
|
actor: actor.into(),
|
||||||
|
attempted_host: None,
|
||||||
|
effect: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn step(&mut self, key: &str, state: &str) {
|
||||||
|
if let Some(s) = self.steps.iter_mut().find(|s| s.key == key) {
|
||||||
|
s.state = state.into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_active(&self) -> bool {
|
||||||
|
matches!(
|
||||||
|
self.state.as_str(),
|
||||||
|
"queued" | "validating" | "applying" | "watching"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_running(&self) -> bool {
|
||||||
|
matches!(self.state.as_str(), "validating" | "applying" | "watching")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A kept change with a commit: something Undo can target.
|
||||||
|
pub fn is_kept_change(&self) -> bool {
|
||||||
|
self.state == "kept" && self.commit.is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Journal {
|
||||||
|
pub apply_id: String,
|
||||||
|
pub stage: String,
|
||||||
|
pub base: String,
|
||||||
|
pub commit: String,
|
||||||
|
pub edge_sha256: Option<String>,
|
||||||
|
pub reason: Option<Reason>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Push state, in `push.json`.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PushState {
|
||||||
|
pub pushed: Option<String>,
|
||||||
|
pub last_push_at: Option<u64>,
|
||||||
|
pub last_attempt_at: Option<u64>,
|
||||||
|
pub next_try_at: Option<u64>,
|
||||||
|
pub error_code: Option<String>,
|
||||||
|
pub error_detail: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub failures: u32,
|
||||||
|
}
|
||||||
@@ -0,0 +1,561 @@
|
|||||||
|
// 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: a bare git repository driven through the `git` binary.
|
||||||
|
//!
|
||||||
|
//! Why the `git` binary (not git2 or gix): pushing to Gitea over HTTPS or SSH is required,
|
||||||
|
//! and gix cannot push yet; git2 would bring libgit2 plus OpenSSL/libssh2 as C dependencies
|
||||||
|
//! into the Nix build, while `git` is one store path Mark already uses, with the same
|
||||||
|
//! behaviour he sees by hand. Control only uses plumbing with fixed arguments: commit ids are
|
||||||
|
//! checked to be hex before they reach a command line, file content goes through stdin, the
|
||||||
|
//! environment is cleared (no user or system git config, no hooks, no prompts), and objects
|
||||||
|
//! and refs are fsync'ed so a crash cannot lose a commit edge already runs.
|
||||||
|
//!
|
||||||
|
//! Control never reads a working tree: trees are read from git objects, so symbolic links or
|
||||||
|
//! files outside the repository cannot be smuggled in. A tree must have exactly the shape
|
||||||
|
//! `ianitor_core::routes` allows.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use ianitor_core::routes::{self, EntryKind, SITE_FILE};
|
||||||
|
use ianitor_core::{MAX_FILE_BYTES, ValidationError};
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum RepoError {
|
||||||
|
#[error("git {op} failed: {message}")]
|
||||||
|
Git { op: String, message: String },
|
||||||
|
#[error("the routes repository has files that do not belong there")]
|
||||||
|
Shape(Vec<ValidationError>),
|
||||||
|
#[error("{0} is not a commit in the routes history")]
|
||||||
|
UnknownCommit(String),
|
||||||
|
#[error("{0}")]
|
||||||
|
Other(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A commit id: 40 (SHA-1) or 64 (SHA-256) lowercase hex digits.
|
||||||
|
pub fn is_commit_id(s: &str) -> bool {
|
||||||
|
(s.len() == 40 || s.len() == 64)
|
||||||
|
&& s.bytes()
|
||||||
|
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The files of one routes tree: path → content. Paths are exactly `ianitor.toml` and
|
||||||
|
/// `hosts/<hostname>.toml`.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct RouteTree {
|
||||||
|
pub files: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RouteTree {
|
||||||
|
pub fn site(&self) -> &str {
|
||||||
|
self.files.get(SITE_FILE).map_or("", String::as_str)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn host(&self, hostname: &str) -> Option<&str> {
|
||||||
|
self.files
|
||||||
|
.get(&routes::host_path(hostname))
|
||||||
|
.map(String::as_str)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hostnames(&self) -> Vec<String> {
|
||||||
|
self.files
|
||||||
|
.keys()
|
||||||
|
.filter_map(|p| p.strip_prefix("hosts/")?.strip_suffix(".toml"))
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_host(&mut self, hostname: &str, contents: String) {
|
||||||
|
self.files.insert(routes::host_path(hostname), contents);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_host(&mut self, hostname: &str) -> bool {
|
||||||
|
self.files.remove(&routes::host_path(hostname)).is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load and validate with core.
|
||||||
|
pub fn model(&self) -> Result<ianitor_core::Model, ianitor_core::ValidationErrors> {
|
||||||
|
let hosts: Vec<ianitor_core::SourceFile> = self
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter(|(p, _)| p.as_str() != SITE_FILE)
|
||||||
|
.map(|(p, c)| ianitor_core::SourceFile {
|
||||||
|
name: p,
|
||||||
|
contents: c,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
ianitor_core::load(
|
||||||
|
&ianitor_core::SourceFile {
|
||||||
|
name: SITE_FILE,
|
||||||
|
contents: self.site(),
|
||||||
|
},
|
||||||
|
&hosts,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Facts about one commit.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct CommitInfo {
|
||||||
|
pub id: String,
|
||||||
|
pub parents: Vec<String>,
|
||||||
|
pub time: u64,
|
||||||
|
pub subject: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Repo {
|
||||||
|
git: PathBuf,
|
||||||
|
dir: PathBuf,
|
||||||
|
home: PathBuf,
|
||||||
|
branch: String,
|
||||||
|
cache: Mutex<Option<(String, Arc<RouteTree>)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn null_device() -> &'static str {
|
||||||
|
if cfg!(windows) { "NUL" } else { "/dev/null" }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Repo {
|
||||||
|
/// Open (or create, with an empty `ianitor.toml`) the bare repository at `dir`.
|
||||||
|
pub fn open(git: &Path, dir: &Path, home: &Path, branch: &str) -> Result<Repo, RepoError> {
|
||||||
|
Repo::open_seeded(git, dir, home, branch, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`Repo::open`]; a new repository starts with `site` as its `ianitor.toml`.
|
||||||
|
pub fn open_seeded(
|
||||||
|
git: &Path,
|
||||||
|
dir: &Path,
|
||||||
|
home: &Path,
|
||||||
|
branch: &str,
|
||||||
|
site: &str,
|
||||||
|
) -> Result<Repo, RepoError> {
|
||||||
|
let repo = Repo {
|
||||||
|
git: git.to_owned(),
|
||||||
|
dir: dir.to_owned(),
|
||||||
|
home: home.to_owned(),
|
||||||
|
branch: branch.to_owned(),
|
||||||
|
cache: Mutex::new(None),
|
||||||
|
};
|
||||||
|
if !dir.join("HEAD").exists() {
|
||||||
|
std::fs::create_dir_all(dir).map_err(|e| RepoError::Other(e.to_string()))?;
|
||||||
|
repo.run_in(
|
||||||
|
None,
|
||||||
|
&[
|
||||||
|
"init",
|
||||||
|
"--bare",
|
||||||
|
"--quiet",
|
||||||
|
&format!("--initial-branch={branch}"),
|
||||||
|
],
|
||||||
|
Some(dir),
|
||||||
|
None,
|
||||||
|
&[],
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
if repo.head()?.is_none() {
|
||||||
|
let mut t = RouteTree::default();
|
||||||
|
t.files.insert(SITE_FILE.into(), site.to_owned());
|
||||||
|
let tree = repo.write_tree(&t, None)?;
|
||||||
|
let c = repo.commit(&tree, &[], "Start the routes repository", "Ianitor control")?;
|
||||||
|
repo.update_ref(&c, None)?;
|
||||||
|
}
|
||||||
|
Ok(repo)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dir(&self) -> &Path {
|
||||||
|
&self.dir
|
||||||
|
}
|
||||||
|
|
||||||
|
fn command(&self) -> Command {
|
||||||
|
let mut c = Command::new(&self.git);
|
||||||
|
c.env_clear();
|
||||||
|
if let Some(p) = std::env::var_os("PATH") {
|
||||||
|
c.env("PATH", p);
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
for v in ["SYSTEMROOT", "TEMP", "TMP"] {
|
||||||
|
if let Some(x) = std::env::var_os(v) {
|
||||||
|
c.env(v, x);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.env("HOME", &self.home)
|
||||||
|
.env("LC_ALL", "C")
|
||||||
|
.env("GIT_CONFIG_NOSYSTEM", "1")
|
||||||
|
.env("GIT_CONFIG_GLOBAL", null_device())
|
||||||
|
.env("GIT_TERMINAL_PROMPT", "0")
|
||||||
|
.args([
|
||||||
|
"-c",
|
||||||
|
&format!("core.hooksPath={}", null_device()),
|
||||||
|
"-c",
|
||||||
|
"core.fsync=all",
|
||||||
|
"-c",
|
||||||
|
"core.fsyncMethod=fsync",
|
||||||
|
]);
|
||||||
|
c
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_in(
|
||||||
|
&self,
|
||||||
|
git_dir: Option<&Path>,
|
||||||
|
args: &[&str],
|
||||||
|
cwd: Option<&Path>,
|
||||||
|
stdin: Option<&[u8]>,
|
||||||
|
env: &[(&str, &str)],
|
||||||
|
) -> Result<Vec<u8>, RepoError> {
|
||||||
|
let mut c = self.command();
|
||||||
|
if let Some(d) = git_dir {
|
||||||
|
c.env("GIT_DIR", d);
|
||||||
|
}
|
||||||
|
if let Some(d) = cwd {
|
||||||
|
c.current_dir(d);
|
||||||
|
}
|
||||||
|
for (k, v) in env {
|
||||||
|
c.env(k, v);
|
||||||
|
}
|
||||||
|
c.args(args)
|
||||||
|
.stdin(if stdin.is_some() {
|
||||||
|
Stdio::piped()
|
||||||
|
} else {
|
||||||
|
Stdio::null()
|
||||||
|
})
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped());
|
||||||
|
let op = args.first().copied().unwrap_or("").to_owned();
|
||||||
|
let mut child = c.spawn().map_err(|e| RepoError::Git {
|
||||||
|
op: op.clone(),
|
||||||
|
message: format!("cannot run {}: {e}", self.git.display()),
|
||||||
|
})?;
|
||||||
|
if let (Some(data), Some(mut si)) = (stdin, child.stdin.take()) {
|
||||||
|
si.write_all(data).map_err(|e| RepoError::Git {
|
||||||
|
op: op.clone(),
|
||||||
|
message: e.to_string(),
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
let out = child.wait_with_output().map_err(|e| RepoError::Git {
|
||||||
|
op: op.clone(),
|
||||||
|
message: e.to_string(),
|
||||||
|
})?;
|
||||||
|
if !out.status.success() {
|
||||||
|
return Err(RepoError::Git {
|
||||||
|
op,
|
||||||
|
message: String::from_utf8_lossy(&out.stderr)
|
||||||
|
.trim()
|
||||||
|
.chars()
|
||||||
|
.take(500)
|
||||||
|
.collect(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(out.stdout)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn git(&self, args: &[&str], stdin: Option<&[u8]>) -> Result<Vec<u8>, RepoError> {
|
||||||
|
self.run_in(Some(&self.dir), args, None, stdin, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn git_str(&self, args: &[&str]) -> Result<String, RepoError> {
|
||||||
|
Ok(String::from_utf8_lossy(&self.git(args, None)?)
|
||||||
|
.trim()
|
||||||
|
.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reference(&self) -> String {
|
||||||
|
format!("refs/heads/{}", self.branch)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current commit of the branch.
|
||||||
|
pub fn head(&self) -> Result<Option<String>, RepoError> {
|
||||||
|
match self.git(
|
||||||
|
&["rev-parse", "--verify", "--quiet", &self.reference()],
|
||||||
|
None,
|
||||||
|
) {
|
||||||
|
Ok(out) => {
|
||||||
|
let s = String::from_utf8_lossy(&out).trim().to_owned();
|
||||||
|
Ok(is_commit_id(&s).then_some(s))
|
||||||
|
}
|
||||||
|
Err(RepoError::Git { .. }) => Ok(None),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn head_required(&self) -> Result<String, RepoError> {
|
||||||
|
self.head()?
|
||||||
|
.ok_or_else(|| RepoError::Other("the routes branch has no commit".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Is `id` a commit reachable from the branch head?
|
||||||
|
pub fn in_history(&self, id: &str) -> Result<bool, RepoError> {
|
||||||
|
if !is_commit_id(id) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let head = self.head_required()?;
|
||||||
|
let mut c = self.command();
|
||||||
|
c.env("GIT_DIR", &self.dir)
|
||||||
|
.args(["merge-base", "--is-ancestor", id, &head])
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(Stdio::null());
|
||||||
|
let st = c.status().map_err(|e| RepoError::Git {
|
||||||
|
op: "merge-base".into(),
|
||||||
|
message: e.to_string(),
|
||||||
|
})?;
|
||||||
|
Ok(st.success())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn info(&self, id: &str) -> Result<CommitInfo, RepoError> {
|
||||||
|
if !is_commit_id(id) {
|
||||||
|
return Err(RepoError::UnknownCommit(id.chars().take(64).collect()));
|
||||||
|
}
|
||||||
|
let out = self
|
||||||
|
.git(
|
||||||
|
&[
|
||||||
|
"show",
|
||||||
|
"-s",
|
||||||
|
"--format=%H%x00%P%x00%at%x00%s",
|
||||||
|
"--end-of-options",
|
||||||
|
id,
|
||||||
|
],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.map_err(|_| RepoError::UnknownCommit(id.to_owned()))?;
|
||||||
|
let text = String::from_utf8_lossy(&out);
|
||||||
|
let mut f = text.trim_end_matches('\n').split('\0');
|
||||||
|
let (Some(h), Some(p), Some(t), Some(s)) = (f.next(), f.next(), f.next(), f.next()) else {
|
||||||
|
return Err(RepoError::UnknownCommit(id.to_owned()));
|
||||||
|
};
|
||||||
|
Ok(CommitInfo {
|
||||||
|
id: h.to_owned(),
|
||||||
|
parents: p
|
||||||
|
.split(' ')
|
||||||
|
.filter(|x| !x.is_empty())
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect(),
|
||||||
|
time: t.parse().unwrap_or(0),
|
||||||
|
subject: s.to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read the tree of a commit, checking its shape. Cached for the last commit read.
|
||||||
|
pub fn tree(&self, commit: &str) -> Result<Arc<RouteTree>, RepoError> {
|
||||||
|
if !is_commit_id(commit) {
|
||||||
|
return Err(RepoError::UnknownCommit(commit.chars().take(64).collect()));
|
||||||
|
}
|
||||||
|
if let Ok(c) = self.cache.lock()
|
||||||
|
&& let Some((id, t)) = c.as_ref()
|
||||||
|
&& id == commit
|
||||||
|
{
|
||||||
|
return Ok(t.clone());
|
||||||
|
}
|
||||||
|
let listing = self.git(&["ls-tree", "-r", "-z", "--full-tree", "-l", commit], None)?;
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
for rec in listing.split(|b| *b == 0).filter(|r| !r.is_empty()) {
|
||||||
|
let rec = String::from_utf8_lossy(rec);
|
||||||
|
let (meta, path) = rec
|
||||||
|
.split_once('\t')
|
||||||
|
.ok_or_else(|| RepoError::Other("unexpected ls-tree output".into()))?;
|
||||||
|
let mut m = meta.split_whitespace();
|
||||||
|
let (mode, kind, sha, size) = (m.next(), m.next(), m.next(), m.next());
|
||||||
|
let entry_kind = match (mode, kind) {
|
||||||
|
(Some("100644"), Some("blob")) => EntryKind::File,
|
||||||
|
(Some("100755"), Some("blob")) => EntryKind::Executable,
|
||||||
|
(Some("120000"), _) => EntryKind::Symlink,
|
||||||
|
_ => EntryKind::Submodule,
|
||||||
|
};
|
||||||
|
let size: usize = size.and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||||
|
entries.push((
|
||||||
|
path.to_owned(),
|
||||||
|
entry_kind,
|
||||||
|
sha.unwrap_or("").to_owned(),
|
||||||
|
size,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
routes::check_tree(entries.iter().map(|(p, k, _, _)| (p.as_str(), *k)))
|
||||||
|
.map_err(RepoError::Shape)?;
|
||||||
|
let mut tree = RouteTree::default();
|
||||||
|
for (path, _, sha, size) in entries {
|
||||||
|
if size > MAX_FILE_BYTES {
|
||||||
|
return Err(RepoError::Shape(vec![ValidationError::FileTooLarge {
|
||||||
|
file: path,
|
||||||
|
max: MAX_FILE_BYTES,
|
||||||
|
}]));
|
||||||
|
}
|
||||||
|
if !is_commit_id(&sha) {
|
||||||
|
return Err(RepoError::Other("unexpected object id".into()));
|
||||||
|
}
|
||||||
|
let blob = self.git(&["cat-file", "blob", &sha], None)?;
|
||||||
|
let text = String::from_utf8(blob).map_err(|_| {
|
||||||
|
RepoError::Shape(vec![ValidationError::Syntax {
|
||||||
|
file: path.clone(),
|
||||||
|
line: None,
|
||||||
|
message: "the file is not UTF-8 text".into(),
|
||||||
|
}])
|
||||||
|
})?;
|
||||||
|
tree.files.insert(path, text);
|
||||||
|
}
|
||||||
|
let tree = Arc::new(tree);
|
||||||
|
if let Ok(mut c) = self.cache.lock() {
|
||||||
|
*c = Some((commit.to_owned(), tree.clone()));
|
||||||
|
}
|
||||||
|
Ok(tree)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the tree objects for `tree`; returns the tree id.
|
||||||
|
pub fn write_tree(&self, tree: &RouteTree, _base: Option<&str>) -> Result<String, RepoError> {
|
||||||
|
let mut hosts = Vec::new();
|
||||||
|
let mut root = Vec::new();
|
||||||
|
for (path, content) in &tree.files {
|
||||||
|
let sha = self.git_str_in(&["hash-object", "-w", "--stdin"], content.as_bytes())?;
|
||||||
|
if let Some(name) = path.strip_prefix("hosts/") {
|
||||||
|
hosts.extend_from_slice(format!("100644 blob {sha}\t{name}\0").as_bytes());
|
||||||
|
} else {
|
||||||
|
root.extend_from_slice(format!("100644 blob {sha}\t{path}\0").as_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !hosts.is_empty() {
|
||||||
|
let sub = self.git_str_in(&["mktree", "-z"], &hosts)?;
|
||||||
|
root.extend_from_slice(format!("040000 tree {sub}\thosts\0").as_bytes());
|
||||||
|
}
|
||||||
|
self.git_str_in(&["mktree", "-z"], &root)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn git_str_in(&self, args: &[&str], stdin: &[u8]) -> Result<String, RepoError> {
|
||||||
|
let out = self.git(args, Some(stdin))?;
|
||||||
|
let s = String::from_utf8_lossy(&out).trim().to_owned();
|
||||||
|
if !is_commit_id(&s) {
|
||||||
|
return Err(RepoError::Other(format!(
|
||||||
|
"git {} gave no object id",
|
||||||
|
args[0]
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a commit object (not yet on the branch).
|
||||||
|
pub fn commit(
|
||||||
|
&self,
|
||||||
|
tree: &str,
|
||||||
|
parents: &[&str],
|
||||||
|
message: &str,
|
||||||
|
author: &str,
|
||||||
|
) -> Result<String, RepoError> {
|
||||||
|
let mut args = vec!["commit-tree", tree];
|
||||||
|
for p in parents {
|
||||||
|
args.push("-p");
|
||||||
|
args.push(p);
|
||||||
|
}
|
||||||
|
args.extend(["-F", "-"]);
|
||||||
|
let author: String = author
|
||||||
|
.chars()
|
||||||
|
.filter(|c| !c.is_control() && !"<>".contains(*c))
|
||||||
|
.take(64)
|
||||||
|
.collect();
|
||||||
|
let author = if author.trim().is_empty() {
|
||||||
|
"Ianitor control".to_owned()
|
||||||
|
} else {
|
||||||
|
author
|
||||||
|
};
|
||||||
|
let env = [
|
||||||
|
("GIT_AUTHOR_NAME", author.as_str()),
|
||||||
|
("GIT_AUTHOR_EMAIL", "ianitor@localhost"),
|
||||||
|
("GIT_COMMITTER_NAME", "Ianitor control"),
|
||||||
|
("GIT_COMMITTER_EMAIL", "ianitor@localhost"),
|
||||||
|
];
|
||||||
|
let out = self.run_in(Some(&self.dir), &args, None, Some(message.as_bytes()), &env)?;
|
||||||
|
let s = String::from_utf8_lossy(&out).trim().to_owned();
|
||||||
|
if !is_commit_id(&s) {
|
||||||
|
return Err(RepoError::Other("git commit-tree gave no commit id".into()));
|
||||||
|
}
|
||||||
|
Ok(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tree_id(&self, commit: &str) -> Result<String, RepoError> {
|
||||||
|
if !is_commit_id(commit) {
|
||||||
|
return Err(RepoError::UnknownCommit(commit.to_owned()));
|
||||||
|
}
|
||||||
|
self.git_str(&["rev-parse", "--verify", &format!("{commit}^{{tree}}")])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Move the branch to `new` only if it is still at `old` (compare and swap).
|
||||||
|
pub fn update_ref(&self, new: &str, old: Option<&str>) -> Result<(), RepoError> {
|
||||||
|
let zero = "0".repeat(new.len());
|
||||||
|
let old = old.unwrap_or(&zero);
|
||||||
|
self.git(&["update-ref", &self.reference(), new, old], None)
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Number of commits in `to` that are not in `from` (`from` none: all of `to`).
|
||||||
|
pub fn count_between(&self, from: Option<&str>, to: &str) -> Result<u64, RepoError> {
|
||||||
|
let range = match from {
|
||||||
|
Some(f) if is_commit_id(f) => format!("{f}..{to}"),
|
||||||
|
_ => to.to_owned(),
|
||||||
|
};
|
||||||
|
Ok(self
|
||||||
|
.git_str(&["rev-list", "--count", &range])?
|
||||||
|
.parse()
|
||||||
|
.unwrap_or(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Push `commit` to the branch on `remote`. Credentials come through `GIT_ASKPASS`
|
||||||
|
/// (this binary's `askpass` mode), never on a command line or in a file.
|
||||||
|
pub async fn push(
|
||||||
|
&self,
|
||||||
|
remote: &str,
|
||||||
|
commit: &str,
|
||||||
|
askpass: Option<(PathBuf, String, PathBuf)>,
|
||||||
|
timeout: std::time::Duration,
|
||||||
|
) -> Result<(), RepoError> {
|
||||||
|
if !is_commit_id(commit) {
|
||||||
|
return Err(RepoError::UnknownCommit(commit.to_owned()));
|
||||||
|
}
|
||||||
|
let std_cmd = self.command();
|
||||||
|
let mut c = tokio::process::Command::from(std_cmd);
|
||||||
|
c.env("GIT_DIR", &self.dir);
|
||||||
|
if let Some((exe, user, file)) = askpass {
|
||||||
|
c.env("GIT_ASKPASS", exe)
|
||||||
|
.env("IANITOR_ASKPASS", "1")
|
||||||
|
.env("IANITOR_ASKPASS_USER", user)
|
||||||
|
.env("IANITOR_ASKPASS_FILE", file);
|
||||||
|
}
|
||||||
|
c.args([
|
||||||
|
"push",
|
||||||
|
"--porcelain",
|
||||||
|
"--",
|
||||||
|
remote,
|
||||||
|
&format!("{commit}:{}", self.reference()),
|
||||||
|
])
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.kill_on_drop(true);
|
||||||
|
let child = c.spawn().map_err(|e| RepoError::Git {
|
||||||
|
op: "push".into(),
|
||||||
|
message: e.to_string(),
|
||||||
|
})?;
|
||||||
|
let out = tokio::time::timeout(timeout, child.wait_with_output())
|
||||||
|
.await
|
||||||
|
.map_err(|_| RepoError::Git {
|
||||||
|
op: "push".into(),
|
||||||
|
message: format!("no answer within {} s", timeout.as_secs()),
|
||||||
|
})?
|
||||||
|
.map_err(|e| RepoError::Git {
|
||||||
|
op: "push".into(),
|
||||||
|
message: e.to_string(),
|
||||||
|
})?;
|
||||||
|
if out.status.success() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
let text = format!(
|
||||||
|
"{} {}",
|
||||||
|
String::from_utf8_lossy(&out.stdout),
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
Err(RepoError::Git {
|
||||||
|
op: "push".into(),
|
||||||
|
message: text.trim().chars().take(500).collect(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
// 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 on control's side: minting, the list, stopping.
|
||||||
|
//!
|
||||||
|
//! Control keeps what it minted in `share-links.json` (never the token itself) and writes
|
||||||
|
//! the revocation file edge reads (`{"epoch": n, "deny": [ids]}`): ids of stopped links that
|
||||||
|
//! have not expired yet, and the epoch below which every token is refused ("stop all").
|
||||||
|
//! The file lives outside git, is written atomically, and edge re-reads it when control asks
|
||||||
|
//! and on its own every 5 s. When control is down nothing can be stopped, but edge keeps
|
||||||
|
//! refusing what is already on the list, also across its own restarts.
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use ianitor_core::share::{self, LinkSpec, ShareId, ShareKey};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::util::{now, random, read_json, write_json};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct LinkRecord {
|
||||||
|
pub id: String,
|
||||||
|
pub hostname: String,
|
||||||
|
pub path_prefix: String,
|
||||||
|
pub epoch: u32,
|
||||||
|
pub created_at: u64,
|
||||||
|
pub expires_at: u64,
|
||||||
|
pub has_password: bool,
|
||||||
|
pub created_by: String,
|
||||||
|
pub stopped_at: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LinkRecord {
|
||||||
|
pub fn state(&self, epoch: u32, t: u64) -> &'static str {
|
||||||
|
if self.stopped_at.is_some() || self.epoch < epoch {
|
||||||
|
"stopped"
|
||||||
|
} else if t >= self.expires_at {
|
||||||
|
"expired"
|
||||||
|
} else {
|
||||||
|
"active"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct ShareFile {
|
||||||
|
pub epoch: u32,
|
||||||
|
pub links: Vec<LinkRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct RevocationFile {
|
||||||
|
epoch: u32,
|
||||||
|
deny: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Kept in the list this long after expiry or stop.
|
||||||
|
const KEEP_SECS: u64 = 30 * 86_400;
|
||||||
|
pub const MIN_EXPIRY: u64 = 3600;
|
||||||
|
pub const MAX_EXPIRY: u64 = 90 * 86_400;
|
||||||
|
/// Most active links at once.
|
||||||
|
pub const MAX_ACTIVE: usize = 2000;
|
||||||
|
/// Most ids edge takes on its deny list (edge refuses 10,000 and more).
|
||||||
|
const MAX_DENY: usize = 9_999;
|
||||||
|
|
||||||
|
pub struct Shares {
|
||||||
|
path: PathBuf,
|
||||||
|
revocations: PathBuf,
|
||||||
|
lock: std::sync::Mutex<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Minted {
|
||||||
|
pub record: LinkRecord,
|
||||||
|
pub token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum MintError {
|
||||||
|
Prefix,
|
||||||
|
Expiry,
|
||||||
|
PasswordShort,
|
||||||
|
PasswordLong,
|
||||||
|
Replaces,
|
||||||
|
/// More active links than [`MAX_ACTIVE`].
|
||||||
|
TooMany,
|
||||||
|
Store(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Shares {
|
||||||
|
pub fn new(state_dir: &Path, revocations: &Path) -> Shares {
|
||||||
|
Shares {
|
||||||
|
path: state_dir.join("share-links.json"),
|
||||||
|
revocations: revocations.to_owned(),
|
||||||
|
lock: std::sync::Mutex::new(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load(&self) -> Result<ShareFile, String> {
|
||||||
|
Ok(read_json(&self.path)?.unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The revocation file as edge has it now, if it can be read.
|
||||||
|
fn published(&self) -> Option<(u32, BTreeSet<String>)> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Published {
|
||||||
|
epoch: u32,
|
||||||
|
deny: Vec<String>,
|
||||||
|
}
|
||||||
|
let p: Published = serde_json::from_slice(&std::fs::read(&self.revocations).ok()?).ok()?;
|
||||||
|
Some((p.epoch, p.deny.into_iter().collect()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The records, with the epoch never below the published one (records lost or restored
|
||||||
|
/// from an older backup must not bring stopped links back).
|
||||||
|
fn load_reconciled(&self) -> Result<ShareFile, String> {
|
||||||
|
let mut f = self.load()?;
|
||||||
|
if let Some((epoch, _)) = self.published()
|
||||||
|
&& epoch > f.epoch
|
||||||
|
{
|
||||||
|
log::warn!(target: "ianitor::share", "share-link records are behind the published revocations (epoch {} < {epoch}); continuing from {epoch}", f.epoch);
|
||||||
|
f.epoch = epoch;
|
||||||
|
}
|
||||||
|
Ok(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, f: &mut ShareFile) -> Result<(), String> {
|
||||||
|
let t = now();
|
||||||
|
// Kept at least until they expire: a stopped link must stay on the deny list as long
|
||||||
|
// as its token would otherwise work.
|
||||||
|
f.links
|
||||||
|
.retain(|l| t < l.expires_at.saturating_add(KEEP_SECS));
|
||||||
|
let deny = self.reconcile(f);
|
||||||
|
write_json(&self.path, f)?;
|
||||||
|
self.publish(f.epoch, deny)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The deny list for `f`, raising `f.epoch` when the list cannot be kept whole:
|
||||||
|
/// - a published id that the records cannot account for (stopped link lost from the
|
||||||
|
/// records) is never just dropped: the epoch goes up, which stops every older link;
|
||||||
|
/// - a list longer than edge accepts also raises the epoch, instead of being cut short.
|
||||||
|
fn reconcile(&self, f: &mut ShareFile) -> Vec<String> {
|
||||||
|
let t = now();
|
||||||
|
let published = self.published();
|
||||||
|
if let Some((epoch, _)) = &published {
|
||||||
|
f.epoch = f.epoch.max(*epoch);
|
||||||
|
}
|
||||||
|
let deny_for = |f: &ShareFile| -> Vec<String> {
|
||||||
|
let mut d: Vec<String> = f
|
||||||
|
.links
|
||||||
|
.iter()
|
||||||
|
.filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch)
|
||||||
|
.map(|l| l.id.clone())
|
||||||
|
.collect();
|
||||||
|
d.sort();
|
||||||
|
d
|
||||||
|
};
|
||||||
|
let mut deny = deny_for(f);
|
||||||
|
if let Some((epoch, old)) = published
|
||||||
|
&& epoch == f.epoch
|
||||||
|
{
|
||||||
|
let accounted = |id: &String| {
|
||||||
|
deny.binary_search(id).is_ok()
|
||||||
|
|| f.links
|
||||||
|
.iter()
|
||||||
|
.any(|l| &l.id == id && (l.expires_at <= t || l.epoch < f.epoch))
|
||||||
|
};
|
||||||
|
if !old.iter().all(accounted) {
|
||||||
|
log::warn!(target: "ianitor::share", "stopped links are missing from the records; raising the epoch, which stops every earlier link");
|
||||||
|
f.epoch = f.epoch.saturating_add(1);
|
||||||
|
deny = deny_for(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if deny.len() > MAX_DENY {
|
||||||
|
log::warn!(target: "ianitor::share", "more than {MAX_DENY} stopped links; raising the epoch, which stops every earlier link");
|
||||||
|
f.epoch = f.epoch.saturating_add(1);
|
||||||
|
deny = deny_for(f);
|
||||||
|
}
|
||||||
|
deny
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the revocation file edge reads.
|
||||||
|
fn publish(&self, epoch: u32, deny: Vec<String>) -> Result<(), String> {
|
||||||
|
// Readable by edge (another user); it holds only random link ids.
|
||||||
|
let text =
|
||||||
|
serde_json::to_vec(&RevocationFile { epoch, deny }).map_err(|e| e.to_string())?;
|
||||||
|
crate::util::write_atomic(&self.revocations, &text, 0o644)
|
||||||
|
.map_err(|e| format!("cannot write {}: {e}", self.revocations.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ensure_revocation_file(&self) -> Result<(), String> {
|
||||||
|
let _g = self
|
||||||
|
.lock
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "share store unavailable".to_owned())?;
|
||||||
|
let mut f = self.load()?;
|
||||||
|
self.save(&mut f)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn mint(
|
||||||
|
&self,
|
||||||
|
key: &ShareKey,
|
||||||
|
hostname: &str,
|
||||||
|
prefix: &str,
|
||||||
|
expires_in: u64,
|
||||||
|
password: Option<&str>,
|
||||||
|
replaces: Option<&str>,
|
||||||
|
actor: &str,
|
||||||
|
) -> Result<Minted, MintError> {
|
||||||
|
let prefix = share::check_prefix(prefix).map_err(|_| MintError::Prefix)?;
|
||||||
|
if !(MIN_EXPIRY..=MAX_EXPIRY).contains(&expires_in) {
|
||||||
|
return Err(MintError::Expiry);
|
||||||
|
}
|
||||||
|
if let Some(p) = password {
|
||||||
|
let n = p.chars().count();
|
||||||
|
if n < share::MIN_PASSWORD_CHARS {
|
||||||
|
return Err(MintError::PasswordShort);
|
||||||
|
}
|
||||||
|
if n > share::MAX_PASSWORD_CHARS {
|
||||||
|
return Err(MintError::PasswordLong);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _g = self
|
||||||
|
.lock
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| MintError::Store("share store unavailable".into()))?;
|
||||||
|
let mut f = self.load_reconciled().map_err(MintError::Store)?;
|
||||||
|
let t0 = now();
|
||||||
|
if f.links
|
||||||
|
.iter()
|
||||||
|
.filter(|l| l.stopped_at.is_none() && l.expires_at > t0)
|
||||||
|
.count()
|
||||||
|
>= MAX_ACTIVE
|
||||||
|
{
|
||||||
|
return Err(MintError::TooMany);
|
||||||
|
}
|
||||||
|
if let Some(r) = replaces {
|
||||||
|
let Some(old) = f
|
||||||
|
.links
|
||||||
|
.iter_mut()
|
||||||
|
.find(|l| l.id == r && l.hostname == hostname)
|
||||||
|
else {
|
||||||
|
return Err(MintError::Replaces);
|
||||||
|
};
|
||||||
|
old.stopped_at.get_or_insert(now());
|
||||||
|
}
|
||||||
|
// Settle the epoch first (lost records, an overflowing deny list): a link minted
|
||||||
|
// below the epoch that is about to be published would be dead on arrival.
|
||||||
|
let _ = self.reconcile(&mut f);
|
||||||
|
let id = ShareId(random::<16>().map_err(|e| MintError::Store(e.to_string()))?);
|
||||||
|
let t = now();
|
||||||
|
let spec = LinkSpec {
|
||||||
|
id,
|
||||||
|
epoch: f.epoch,
|
||||||
|
expires_at: t + expires_in,
|
||||||
|
prefix: &prefix,
|
||||||
|
password,
|
||||||
|
};
|
||||||
|
let token =
|
||||||
|
share::mint(key, hostname, &spec).map_err(|e| MintError::Store(e.to_string()))?;
|
||||||
|
let record = LinkRecord {
|
||||||
|
id: id.to_hex(),
|
||||||
|
hostname: hostname.to_owned(),
|
||||||
|
path_prefix: prefix.clone(),
|
||||||
|
epoch: f.epoch,
|
||||||
|
created_at: t,
|
||||||
|
expires_at: t + expires_in,
|
||||||
|
has_password: password.is_some(),
|
||||||
|
created_by: actor.to_owned(),
|
||||||
|
stopped_at: None,
|
||||||
|
};
|
||||||
|
f.links.push(record.clone());
|
||||||
|
self.save(&mut f).map_err(MintError::Store)?;
|
||||||
|
Ok(Minted { record, token })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop one link. `Ok(None)` when there is no such link.
|
||||||
|
pub fn stop(&self, id: &str) -> Result<Option<LinkRecord>, String> {
|
||||||
|
let _g = self
|
||||||
|
.lock
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "share store unavailable".to_owned())?;
|
||||||
|
let mut f = self.load_reconciled()?;
|
||||||
|
let Some(l) = f.links.iter_mut().find(|l| l.id == id) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
l.stopped_at.get_or_insert(now());
|
||||||
|
let r = l.clone();
|
||||||
|
self.save(&mut f)?;
|
||||||
|
Ok(Some(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop every link minted so far by raising the epoch.
|
||||||
|
pub fn stop_all(&self) -> Result<u32, String> {
|
||||||
|
let _g = self
|
||||||
|
.lock
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "share store unavailable".to_owned())?;
|
||||||
|
let mut f = self.load_reconciled()?;
|
||||||
|
f.epoch = f.epoch.saturating_add(1);
|
||||||
|
let e = f.epoch;
|
||||||
|
self.save(&mut f)?;
|
||||||
|
Ok(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,412 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Switching the engine at runtime (ROADMAP §1.6 as corrected 2026-11-07, §3, §4).
|
||||||
|
//!
|
||||||
|
//! Exactly one of `ianitor-edge.service` and `caddy-fallback.service` runs. Control may start,
|
||||||
|
//! and stop only those two, through a polkit rule scoped to exactly them (NixOS
|
||||||
|
//! module). `/var/lib/ianitor/engine` names the one to run; the `ianitor-engine-select` unit
|
||||||
|
//! reads it at boot. A switch writes the file first (so a reboot mid-switch boots the
|
||||||
|
//! target), stops the old engine, starts the new one and waits until it serves; if the new
|
||||||
|
//! one does not come up, it goes back to the old one and says so.
|
||||||
|
//!
|
||||||
|
//! Decisions (phase 3):
|
||||||
|
//! - While Caddy serves, changes keep working (Mark, 2026-11-08): an apply is loaded into Caddy
|
||||||
|
//! through its admin socket, watched through Caddy and kept or reverted (`engine/caddy_apply`).
|
||||||
|
//! - Share links are refused while Caddy serves (`share.engine_caddy`, see docs/api.md):
|
||||||
|
//! Caddy cannot check them, and control never serves visitors itself.
|
||||||
|
//! - Device revocations while Caddy serves reload Caddy's config through its admin socket.
|
||||||
|
//!
|
||||||
|
//! The systemd calls go through [`Units`], so tests use a fake.
|
||||||
|
|
||||||
|
// A refusal is built once per request; boxing it buys nothing.
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::config::EngineConfig;
|
||||||
|
use crate::engine::{Control, Fail, reason};
|
||||||
|
use crate::messages::{self, Params};
|
||||||
|
use crate::records::Reason;
|
||||||
|
use crate::util::{now, write_atomic};
|
||||||
|
|
||||||
|
/// Start, stop and look at systemd units.
|
||||||
|
pub trait Units: Send + Sync {
|
||||||
|
fn start(&self, unit: &str) -> Result<(), String>;
|
||||||
|
fn stop(&self, unit: &str) -> Result<(), String>;
|
||||||
|
fn is_active(&self, unit: &str) -> Result<bool, String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `systemctl --no-ask-password <verb> <unit>`, as the control user (polkit decides).
|
||||||
|
pub struct Systemctl {
|
||||||
|
pub bin: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Systemctl {
|
||||||
|
fn run(&self, args: &[&str]) -> Result<std::process::Output, String> {
|
||||||
|
std::process::Command::new(&self.bin)
|
||||||
|
.arg("--no-ask-password")
|
||||||
|
.args(args)
|
||||||
|
.stdin(std::process::Stdio::null())
|
||||||
|
.output()
|
||||||
|
.map_err(|e| format!("cannot run {}: {e}", self.bin.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verb(&self, verb: &str, unit: &str) -> Result<(), String> {
|
||||||
|
let o = self.run(&[verb, unit])?;
|
||||||
|
if o.status.success() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(format!(
|
||||||
|
"systemctl {verb} {unit} failed: {}",
|
||||||
|
String::from_utf8_lossy(&o.stderr).trim()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Units for Systemctl {
|
||||||
|
fn start(&self, unit: &str) -> Result<(), String> {
|
||||||
|
self.verb("start", unit)
|
||||||
|
}
|
||||||
|
fn stop(&self, unit: &str) -> Result<(), String> {
|
||||||
|
self.verb("stop", unit)
|
||||||
|
}
|
||||||
|
fn is_active(&self, unit: &str) -> Result<bool, String> {
|
||||||
|
Ok(self.run(&["is-active", "--quiet", unit])?.status.success())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In-memory units for tests: records every call; `fail_start` makes a start fail.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct FakeUnits {
|
||||||
|
pub calls: Mutex<Vec<String>>,
|
||||||
|
pub active: Mutex<HashSet<String>>,
|
||||||
|
pub fail_start: Mutex<HashSet<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Units for FakeUnits {
|
||||||
|
fn start(&self, unit: &str) -> Result<(), String> {
|
||||||
|
if let Ok(mut c) = self.calls.lock() {
|
||||||
|
c.push(format!("start {unit}"));
|
||||||
|
}
|
||||||
|
if self.fail_start.lock().is_ok_and(|f| f.contains(unit)) {
|
||||||
|
return Err(format!("{unit} failed to start"));
|
||||||
|
}
|
||||||
|
if let Ok(mut a) = self.active.lock() {
|
||||||
|
a.insert(unit.to_owned());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn stop(&self, unit: &str) -> Result<(), String> {
|
||||||
|
if let Ok(mut c) = self.calls.lock() {
|
||||||
|
c.push(format!("stop {unit}"));
|
||||||
|
}
|
||||||
|
if let Ok(mut a) = self.active.lock() {
|
||||||
|
a.remove(unit);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn is_active(&self, unit: &str) -> Result<bool, String> {
|
||||||
|
Ok(self.active.lock().is_ok_and(|a| a.contains(unit)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which engine serves, as control knows it.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct EngineState {
|
||||||
|
/// `pingora` or `caddy`.
|
||||||
|
pub running: String,
|
||||||
|
/// `running`, `switching` or `stopped`.
|
||||||
|
pub state: String,
|
||||||
|
pub since: u64,
|
||||||
|
/// The target while switching.
|
||||||
|
pub target: Option<String>,
|
||||||
|
/// Why the last switch did not happen.
|
||||||
|
pub last_error: Option<Reason>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_engine_file(p: &Path) -> String {
|
||||||
|
match std::fs::read_to_string(p) {
|
||||||
|
Ok(s) if s.trim() == "caddy" => "caddy".into(),
|
||||||
|
_ => "pingora".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn engine_name(e: &str) -> String {
|
||||||
|
if e == "caddy" { "Caddy" } else { "Pingora" }.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Control {
|
||||||
|
pub fn engine_cfg(&self) -> Option<&EngineConfig> {
|
||||||
|
self.cfg.engine.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `pingora` or `caddy`.
|
||||||
|
pub fn engine_running(&self) -> String {
|
||||||
|
self.engine
|
||||||
|
.lock()
|
||||||
|
.map(|e| e.running.clone())
|
||||||
|
.unwrap_or_else(|_| "pingora".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn engine_state(&self) -> EngineState {
|
||||||
|
self.engine
|
||||||
|
.lock()
|
||||||
|
.map(|e| e.clone())
|
||||||
|
.unwrap_or(EngineState {
|
||||||
|
running: "pingora".into(),
|
||||||
|
state: "running".into(),
|
||||||
|
since: 0,
|
||||||
|
target: None,
|
||||||
|
last_error: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_engine(&self, f: impl FnOnce(&mut EngineState)) {
|
||||||
|
if let Ok(mut e) = self.engine.lock() {
|
||||||
|
f(&mut e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check a switch request and start it. Answers at once; the switch runs in the
|
||||||
|
/// background (`overview.engine.state` is `switching` until it ends).
|
||||||
|
pub fn request_switch(self: &Arc<Self>, target: &str) -> Result<EngineState, Fail> {
|
||||||
|
if self.engine_cfg().is_none() || self.units.is_none() {
|
||||||
|
return Err(Fail::new(409, "engine.unmanaged", Params::new()));
|
||||||
|
}
|
||||||
|
if target == "caddy" && !self.fallback_buildable() {
|
||||||
|
return Err(Fail::new(409, "engine.not_ready", Params::new()));
|
||||||
|
}
|
||||||
|
if target != "pingora" && target != "caddy" {
|
||||||
|
return Err(Fail::new(
|
||||||
|
422,
|
||||||
|
"request.body",
|
||||||
|
messages::params([("problem", "target must be \"pingora\" or \"caddy\".".into())]),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let mut e = self
|
||||||
|
.engine
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| Fail::new(500, "internal", Params::new()))?;
|
||||||
|
if e.state == "switching" {
|
||||||
|
return Err(Fail::new(409, "engine.switching", Params::new()));
|
||||||
|
}
|
||||||
|
if e.running == target {
|
||||||
|
return Err(Fail::new(
|
||||||
|
409,
|
||||||
|
"engine.same",
|
||||||
|
messages::params([("engine", engine_name(target))]),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
e.state = "switching".into();
|
||||||
|
e.target = Some(target.to_owned());
|
||||||
|
e.last_error = None;
|
||||||
|
}
|
||||||
|
let me = self.clone();
|
||||||
|
let t = target.to_owned();
|
||||||
|
tokio::spawn(async move { me.switch(&t).await });
|
||||||
|
Ok(self.engine_state())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn switch(self: Arc<Self>, target: &str) {
|
||||||
|
// No apply runs during a switch, and none starts.
|
||||||
|
let _lock = self.apply_lock.lock().await;
|
||||||
|
let _engine = self.engine_lock.lock().await;
|
||||||
|
let from = self.engine_running();
|
||||||
|
let res = self.switch_inner(&from, target).await;
|
||||||
|
let t = now();
|
||||||
|
match res {
|
||||||
|
Ok(()) => {
|
||||||
|
log::info!(target: "ianitor::engine", "switched from {from} to {target}");
|
||||||
|
self.set_engine(|e| {
|
||||||
|
e.running = target.to_owned();
|
||||||
|
e.state = "running".into();
|
||||||
|
e.since = t;
|
||||||
|
e.target = None;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(detail) => {
|
||||||
|
log::error!(target: "ianitor::engine", "switch to {target} failed: {detail}");
|
||||||
|
// Go back to what served before.
|
||||||
|
let back = self.bring_back(&from).await;
|
||||||
|
let mut r = reason(
|
||||||
|
"engine.switch_failed",
|
||||||
|
messages::params([
|
||||||
|
("engine", engine_name(target)),
|
||||||
|
("previous", engine_name(&from)),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
r.detail = Some(match back {
|
||||||
|
Ok(()) => detail,
|
||||||
|
Err(b) => format!("{detail}; going back also failed: {b}"),
|
||||||
|
});
|
||||||
|
self.set_engine(|e| {
|
||||||
|
e.running = from.clone();
|
||||||
|
e.state = "running".into();
|
||||||
|
e.target = None;
|
||||||
|
e.last_error = Some(r);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Still under the engine lock: whichever engine serves now reads the device files again
|
||||||
|
// (QC round 4). A device change during the switch only wrote them; a Caddy that was
|
||||||
|
// already running, or started before they changed, would keep the old list.
|
||||||
|
if self.pki.is_some()
|
||||||
|
&& let Err(e) = self.nudge_devices().await
|
||||||
|
{
|
||||||
|
log::error!(target: "ianitor::engine", "after the switch: {e}; retrying");
|
||||||
|
if let Ok(mut p) = self.devices_problem.lock() {
|
||||||
|
*p = Some(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn units_and_cfg(&self) -> Result<(Arc<dyn Units>, EngineConfig), String> {
|
||||||
|
match (self.units.clone(), self.engine_cfg().cloned()) {
|
||||||
|
(Some(u), Some(c)) => Ok((u, c)),
|
||||||
|
_ => Err("no engine settings".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unit_of(cfg: &EngineConfig, engine: &str) -> String {
|
||||||
|
if engine == "caddy" {
|
||||||
|
cfg.caddy_unit.clone()
|
||||||
|
} else {
|
||||||
|
cfg.edge_unit.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn blocking<T: Send + 'static>(
|
||||||
|
f: impl FnOnce() -> Result<T, String> + Send + 'static,
|
||||||
|
) -> Result<T, String> {
|
||||||
|
tokio::task::spawn_blocking(f)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn switch_inner(&self, from: &str, target: &str) -> Result<(), String> {
|
||||||
|
let (units, cfg) = self.units_and_cfg()?;
|
||||||
|
if target == "caddy" {
|
||||||
|
// Caddy starts from caddy.json: make sure it is the current tree's.
|
||||||
|
self.write_current_caddy()?;
|
||||||
|
}
|
||||||
|
write_atomic(&cfg.file, target.as_bytes(), 0o644)
|
||||||
|
.map_err(|e| format!("cannot write {}: {e}", cfg.file.display()))?;
|
||||||
|
let (old, new) = (Self::unit_of(&cfg, from), Self::unit_of(&cfg, target));
|
||||||
|
let u = units.clone();
|
||||||
|
Self::blocking(move || u.stop(&old)).await?;
|
||||||
|
let u = units.clone();
|
||||||
|
let n = new.clone();
|
||||||
|
Self::blocking(move || u.start(&n)).await?;
|
||||||
|
self.wait_serving(target, &units, &new).await?;
|
||||||
|
// Edge reads edge.json when it starts; tell it again in case it kept running (changes
|
||||||
|
// kept under Caddy are in edge.json).
|
||||||
|
if target == "pingora"
|
||||||
|
&& self.edge.attached()
|
||||||
|
&& let Err(e) = self.edge.reload().await
|
||||||
|
{
|
||||||
|
log::warn!(target: "ianitor::engine", "edge did not reload edge.json after the switch: {e}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn bring_back(&self, engine: &str) -> Result<(), String> {
|
||||||
|
let (units, cfg) = self.units_and_cfg()?;
|
||||||
|
let other = if engine == "caddy" {
|
||||||
|
"pingora"
|
||||||
|
} else {
|
||||||
|
"caddy"
|
||||||
|
};
|
||||||
|
write_atomic(&cfg.file, engine.as_bytes(), 0o644).map_err(|e| e.to_string())?;
|
||||||
|
let (stop, start) = (Self::unit_of(&cfg, other), Self::unit_of(&cfg, engine));
|
||||||
|
let u = units.clone();
|
||||||
|
let _ = Self::blocking(move || u.stop(&stop)).await;
|
||||||
|
let u = units.clone();
|
||||||
|
let s = start.clone();
|
||||||
|
Self::blocking(move || u.start(&s)).await?;
|
||||||
|
self.wait_serving(engine, &units, &start).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Until the unit is active and serves: edge answers on its admin socket, Caddy accepts
|
||||||
|
/// connections on the HTTPS address.
|
||||||
|
async fn wait_serving(
|
||||||
|
&self,
|
||||||
|
engine: &str,
|
||||||
|
units: &Arc<dyn Units>,
|
||||||
|
unit: &str,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let deadline = tokio::time::Instant::now() + Duration::from_secs(20);
|
||||||
|
let addr = if engine == "caddy" {
|
||||||
|
self.cfg.caddy_compile().https_listen
|
||||||
|
} else {
|
||||||
|
self.cfg.compile.https_listen
|
||||||
|
};
|
||||||
|
loop {
|
||||||
|
let u = units.clone();
|
||||||
|
let n = unit.to_owned();
|
||||||
|
let active = Self::blocking(move || u.is_active(&n))
|
||||||
|
.await
|
||||||
|
.unwrap_or(false);
|
||||||
|
let serving = active
|
||||||
|
&& if engine == "pingora" && self.edge.attached() {
|
||||||
|
self.edge.status().await.is_ok()
|
||||||
|
} else {
|
||||||
|
tokio::net::TcpStream::connect(addr).await.is_ok()
|
||||||
|
};
|
||||||
|
if serving {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if tokio::time::Instant::now() > deadline {
|
||||||
|
return Err(format!("{unit} did not come up within 20 s"));
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compile the current tree for Caddy and write caddy.json (the file only ever holds a
|
||||||
|
/// kept tree, so this only matters when it is missing or older).
|
||||||
|
fn write_current_caddy(&self) -> Result<(), String> {
|
||||||
|
let (_, _, model) = self.head_model().map_err(|f| f.reason.message)?;
|
||||||
|
self.pki_prepare(&model).map_err(|f| f.reason.message)?;
|
||||||
|
let text = ianitor_core::compile::caddy(&model, &self.cfg.caddy_compile().options())
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if std::fs::read_to_string(&self.cfg.caddy.config)
|
||||||
|
.ok()
|
||||||
|
.as_deref()
|
||||||
|
!= Some(text.as_str())
|
||||||
|
{
|
||||||
|
write_atomic(&self.cfg.caddy.config, text.as_bytes(), 0o644)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Can Caddy's settings be built from the current tree? (Otherwise `engine.not_ready`.)
|
||||||
|
pub fn fallback_buildable(&self) -> bool {
|
||||||
|
self.head_model().ok().is_some_and(|(_, _, m)| {
|
||||||
|
ianitor_core::compile::caddy(&m, &self.cfg.caddy_compile().options()).is_ok()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Any reason changes wait now: Caddy serving, or a pause.
|
||||||
|
pub fn effective_pause(&self) -> Option<Reason> {
|
||||||
|
self.paused()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What control.toml's `[engine]` asks for.
|
||||||
|
pub fn units_for(cfg: Option<&EngineConfig>) -> Option<Arc<dyn Units>> {
|
||||||
|
let c = cfg?;
|
||||||
|
match c.units.as_str() {
|
||||||
|
"systemctl" => Some(Arc::new(Systemctl {
|
||||||
|
bin: c.systemctl.clone(),
|
||||||
|
})),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,470 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Team sign-in without Authelia (T4: Ianitor on any server, for a small team). Authelia stays
|
||||||
|
//! an option (`[ui] proof_credential`, docs/api.md "Sign-in"); this is the default elsewhere.
|
||||||
|
//!
|
||||||
|
//! - **The founding admin** signs in with a one-time **setup link** (`#signin=isc_…`): made at
|
||||||
|
//! the first start of a server with no member, printed by the installer
|
||||||
|
//! (`ianitor-control team setup-link`), valid 7 days, one use.
|
||||||
|
//! - **Teammates** get an **invite link** from an admin (Settings → Team → Invite), for a role:
|
||||||
|
//! `admin` (everything) or `member` (hosts, previews, history; not tokens, the team, the
|
||||||
|
//! engine or the CA). One use, 7 days.
|
||||||
|
//! - Redeeming a link makes a **session**: `ise_` + 32 random bytes in an `HttpOnly`,
|
||||||
|
//! `Secure`, `SameSite=Strict`, `__Host-` cookie, 30 days, no sliding. Control stores only
|
||||||
|
//! SHA-256 of codes and sessions (in `team.json`, 0600), so a copy of the state directory
|
||||||
|
//! signs no one in. Signing out ends the session; removing a member ends all of theirs.
|
||||||
|
//! - A member may record their **Tessera root** (the Domi identity's public key, as Custos
|
||||||
|
//! shows it) so the team list shows its match code. Signing in *with* the Tessera key (a
|
||||||
|
//! browser Domi key) and Custos approval of admin changes need operations Custos does not
|
||||||
|
//! have yet (docs/custos-ticket.md, T4 part); until then admin changes need the admin role.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use base64::Engine as _;
|
||||||
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json};
|
||||||
|
|
||||||
|
pub const COOKIE: &str = "__Host-ianitor";
|
||||||
|
pub const SESSION_SECS: u64 = 30 * 86_400;
|
||||||
|
pub const CODE_SECS: u64 = 7 * 86_400;
|
||||||
|
const MAX_MEMBERS: usize = 64;
|
||||||
|
const MAX_SESSIONS: usize = 400;
|
||||||
|
const MAX_CODES: usize = 100;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum Role {
|
||||||
|
Admin,
|
||||||
|
Member,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Role {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Role::Admin => "admin",
|
||||||
|
Role::Member => "member",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn parse(s: &str) -> Option<Role> {
|
||||||
|
match s {
|
||||||
|
"admin" => Some(Role::Admin),
|
||||||
|
"member" => Some(Role::Member),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Member {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub role: Role,
|
||||||
|
/// The member's Tessera root public key (base64url, 32 bytes), when they gave it.
|
||||||
|
#[serde(default)]
|
||||||
|
pub tessera_root: Option<String>,
|
||||||
|
pub added_at: u64,
|
||||||
|
pub added_by: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Session {
|
||||||
|
pub id: String,
|
||||||
|
pub sha256: String,
|
||||||
|
pub member: String,
|
||||||
|
/// What the browser was called at sign-in (`Laptop`, `Phone`).
|
||||||
|
pub device: String,
|
||||||
|
pub created_at: u64,
|
||||||
|
pub expires_at: u64,
|
||||||
|
pub last_used_at: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Code {
|
||||||
|
pub id: String,
|
||||||
|
pub sha256: String,
|
||||||
|
/// `setup` (the founding admin) or `invite`.
|
||||||
|
pub kind: String,
|
||||||
|
pub role: Role,
|
||||||
|
/// The invitee's name, as the admin typed it.
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub expires_at: u64,
|
||||||
|
pub created_by: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct TeamFile {
|
||||||
|
members: Vec<Member>,
|
||||||
|
sessions: Vec<Session>,
|
||||||
|
codes: Vec<Code>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a sign-in or a team change was refused (an API error code).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Refused(pub &'static str);
|
||||||
|
|
||||||
|
pub struct Team {
|
||||||
|
path: PathBuf,
|
||||||
|
lock: std::sync::Mutex<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Guard<'a> {
|
||||||
|
_m: std::sync::MutexGuard<'a, ()>,
|
||||||
|
_f: std::fs::File,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn valid_name(n: &str) -> bool {
|
||||||
|
let n = n.trim();
|
||||||
|
!n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Tessera root as Custos shows it: base64url of 32 bytes.
|
||||||
|
pub fn valid_root(r: &str) -> bool {
|
||||||
|
URL_SAFE_NO_PAD
|
||||||
|
.decode(r.trim())
|
||||||
|
.is_ok_and(|b| b.len() == 32)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The 6-digit match code of a Tessera key, exactly as Fundamentum's `tessera::match_code`
|
||||||
|
/// (docs/TESSERA.md §5): SHA-256 of `"tessera match v1"` and the key, first 4 bytes
|
||||||
|
/// big-endian, mod 10^6; shown as `474 719`.
|
||||||
|
pub fn match_code(root: &str) -> Option<String> {
|
||||||
|
let b = URL_SAFE_NO_PAD.decode(root.trim()).ok()?;
|
||||||
|
let mut ctx = ring::digest::Context::new(&ring::digest::SHA256);
|
||||||
|
ctx.update(b"tessera match v1");
|
||||||
|
ctx.update(&b);
|
||||||
|
let d = ctx.finish();
|
||||||
|
let n = u32::from_be_bytes([d.as_ref()[0], d.as_ref()[1], d.as_ref()[2], d.as_ref()[3]]);
|
||||||
|
let c = n % 1_000_000;
|
||||||
|
Some(format!("{:03} {:03}", c / 1000, c % 1000))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn secret(prefix: &str) -> Result<String, String> {
|
||||||
|
Ok(format!(
|
||||||
|
"{prefix}_{}",
|
||||||
|
URL_SAFE_NO_PAD.encode(random::<32>().map_err(|e| e.to_string())?)
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_id() -> Result<String, String> {
|
||||||
|
Ok(hex(&random::<8>().map_err(|e| e.to_string())?))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Team {
|
||||||
|
pub fn new(state_dir: &Path) -> Team {
|
||||||
|
Team {
|
||||||
|
path: state_dir.join("team.json"),
|
||||||
|
lock: std::sync::Mutex::new(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn guard(&self) -> Result<Guard<'_>, String> {
|
||||||
|
let m = self
|
||||||
|
.lock
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "team store unavailable".to_owned())?;
|
||||||
|
let path = self.path.with_file_name("team.lock");
|
||||||
|
if let Some(d) = path.parent() {
|
||||||
|
std::fs::create_dir_all(d)
|
||||||
|
.map_err(|e| format!("cannot create {}: {e}", d.display()))?;
|
||||||
|
}
|
||||||
|
let f = std::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.write(true)
|
||||||
|
.open(&path)
|
||||||
|
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||||
|
f.lock()
|
||||||
|
.map_err(|e| format!("cannot lock {}: {e}", path.display()))?;
|
||||||
|
Ok(Guard { _m: m, _f: f })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(&self) -> Result<TeamFile, String> {
|
||||||
|
let mut f: TeamFile = read_json(&self.path)?.unwrap_or_default();
|
||||||
|
let t = now();
|
||||||
|
f.sessions.retain(|s| s.expires_at > t);
|
||||||
|
f.codes.retain(|c| c.expires_at > t);
|
||||||
|
Ok(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, f: &TeamFile) -> Result<(), String> {
|
||||||
|
write_json(&self.path, f)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn members(&self) -> Result<Vec<Member>, String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
|
Ok(self.load()?.members)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open invites (never their values).
|
||||||
|
pub fn codes(&self) -> Result<Vec<Code>, String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
|
Ok(self.load()?.codes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn has_members(&self) -> bool {
|
||||||
|
self.members().is_ok_and(|m| !m.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new setup code for the founding admin, while the team has no member. Older setup
|
||||||
|
/// codes stop working.
|
||||||
|
pub fn setup_code(&self) -> Result<(String, u64), String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
|
let mut f = self.load()?;
|
||||||
|
if !f.members.is_empty() {
|
||||||
|
return Err(
|
||||||
|
"the team already has members; an admin invites people from Settings → Team".into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
f.codes.retain(|c| c.kind != "setup");
|
||||||
|
let value = secret("isc")?;
|
||||||
|
let expires_at = now() + CODE_SECS;
|
||||||
|
f.codes.push(Code {
|
||||||
|
id: new_id()?,
|
||||||
|
sha256: sha256_hex(value.as_bytes()),
|
||||||
|
kind: "setup".into(),
|
||||||
|
role: Role::Admin,
|
||||||
|
name: None,
|
||||||
|
expires_at,
|
||||||
|
created_by: "setup".into(),
|
||||||
|
});
|
||||||
|
self.save(&f)?;
|
||||||
|
Ok((value, expires_at))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An invite for one person (admin only, checked by the caller).
|
||||||
|
pub fn invite(&self, name: &str, role: Role, by: &str) -> Result<(Code, String), Refused> {
|
||||||
|
let _g = self.guard().map_err(|_| Refused("internal"))?;
|
||||||
|
let mut f = self.load().map_err(|_| Refused("internal"))?;
|
||||||
|
if !valid_name(name) {
|
||||||
|
return Err(Refused("team.name"));
|
||||||
|
}
|
||||||
|
if f.codes.len() >= MAX_CODES || f.members.len() >= MAX_MEMBERS {
|
||||||
|
return Err(Refused("team.full"));
|
||||||
|
}
|
||||||
|
let value = secret("iin").map_err(|_| Refused("internal"))?;
|
||||||
|
let code = Code {
|
||||||
|
id: new_id().map_err(|_| Refused("internal"))?,
|
||||||
|
sha256: sha256_hex(value.as_bytes()),
|
||||||
|
kind: "invite".into(),
|
||||||
|
role,
|
||||||
|
name: Some(name.trim().to_owned()),
|
||||||
|
expires_at: now() + CODE_SECS,
|
||||||
|
created_by: by.to_owned(),
|
||||||
|
};
|
||||||
|
f.codes.push(code.clone());
|
||||||
|
self.save(&f).map_err(|_| Refused("internal"))?;
|
||||||
|
Ok((code, value))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cancel_invite(&self, id: &str) -> Result<bool, String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
|
let mut f = self.load()?;
|
||||||
|
let before = f.codes.len();
|
||||||
|
f.codes.retain(|c| !(c.id == id && c.kind == "invite"));
|
||||||
|
let gone = f.codes.len() != before;
|
||||||
|
self.save(&f)?;
|
||||||
|
Ok(gone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Redeem a setup or invite code: the member (made now) and a new session's value.
|
||||||
|
pub fn redeem(
|
||||||
|
&self,
|
||||||
|
code: &str,
|
||||||
|
name: Option<&str>,
|
||||||
|
device: &str,
|
||||||
|
) -> Result<(Member, String), Refused> {
|
||||||
|
let _g = self.guard().map_err(|_| Refused("internal"))?;
|
||||||
|
let mut f = self.load().map_err(|_| Refused("internal"))?;
|
||||||
|
let presented = sha256_hex(code.trim().as_bytes());
|
||||||
|
let Some(pos) = f
|
||||||
|
.codes
|
||||||
|
.iter()
|
||||||
|
.position(|c| ct_eq(c.sha256.as_bytes(), presented.as_bytes()))
|
||||||
|
else {
|
||||||
|
return Err(Refused("session.code"));
|
||||||
|
};
|
||||||
|
let c = f.codes.remove(pos);
|
||||||
|
if c.kind == "setup" && !f.members.is_empty() {
|
||||||
|
return Err(Refused("session.code"));
|
||||||
|
}
|
||||||
|
let name = match (c.name.as_deref(), name) {
|
||||||
|
(Some(n), _) => n.to_owned(),
|
||||||
|
(None, Some(n)) if valid_name(n) => n.trim().to_owned(),
|
||||||
|
(None, _) => "Admin".to_owned(),
|
||||||
|
};
|
||||||
|
if f.members.len() >= MAX_MEMBERS {
|
||||||
|
return Err(Refused("team.full"));
|
||||||
|
}
|
||||||
|
let member = Member {
|
||||||
|
id: new_id().map_err(|_| Refused("internal"))?,
|
||||||
|
name,
|
||||||
|
role: c.role,
|
||||||
|
tessera_root: None,
|
||||||
|
added_at: now(),
|
||||||
|
added_by: c.created_by.clone(),
|
||||||
|
};
|
||||||
|
f.members.push(member.clone());
|
||||||
|
let value = self.push_session(&mut f, &member.id, device)?;
|
||||||
|
self.save(&f).map_err(|_| Refused("internal"))?;
|
||||||
|
Ok((member, value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_session(
|
||||||
|
&self,
|
||||||
|
f: &mut TeamFile,
|
||||||
|
member: &str,
|
||||||
|
device: &str,
|
||||||
|
) -> Result<String, Refused> {
|
||||||
|
let value = secret("ise").map_err(|_| Refused("internal"))?;
|
||||||
|
let t = now();
|
||||||
|
if f.sessions.len() >= MAX_SESSIONS {
|
||||||
|
// The oldest one goes.
|
||||||
|
f.sessions.sort_by_key(|s| s.created_at);
|
||||||
|
f.sessions.remove(0);
|
||||||
|
}
|
||||||
|
let device = if valid_name(device) {
|
||||||
|
device.trim().to_owned()
|
||||||
|
} else {
|
||||||
|
"Browser".to_owned()
|
||||||
|
};
|
||||||
|
f.sessions.push(Session {
|
||||||
|
id: new_id().map_err(|_| Refused("internal"))?,
|
||||||
|
sha256: sha256_hex(value.as_bytes()),
|
||||||
|
member: member.to_owned(),
|
||||||
|
device,
|
||||||
|
created_at: t,
|
||||||
|
expires_at: t + SESSION_SECS,
|
||||||
|
last_used_at: Some(t),
|
||||||
|
});
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The member and session behind a cookie value.
|
||||||
|
pub fn check(&self, value: &str) -> Option<(Member, Session)> {
|
||||||
|
if !value.starts_with("ise_") || value.len() > 100 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let _g = self.guard().ok()?;
|
||||||
|
let mut f = self.load().ok()?;
|
||||||
|
let presented = sha256_hex(value.as_bytes());
|
||||||
|
let s = f
|
||||||
|
.sessions
|
||||||
|
.iter_mut()
|
||||||
|
.find(|s| ct_eq(s.sha256.as_bytes(), presented.as_bytes()))?;
|
||||||
|
let t = now();
|
||||||
|
let touch = s.last_used_at.is_none_or(|l| t.saturating_sub(l) >= 60);
|
||||||
|
if touch {
|
||||||
|
s.last_used_at = Some(t);
|
||||||
|
}
|
||||||
|
let s = s.clone();
|
||||||
|
let m = f.members.iter().find(|m| m.id == s.member)?.clone();
|
||||||
|
if touch {
|
||||||
|
let _ = self.save(&f);
|
||||||
|
}
|
||||||
|
Some((m, s))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn end_session(&self, id: &str) -> Result<(), String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
|
let mut f = self.load()?;
|
||||||
|
f.sessions.retain(|s| s.id != id);
|
||||||
|
self.save(&f)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a member and every session of theirs. The last admin stays.
|
||||||
|
pub fn remove(&self, id: &str) -> Result<Option<Member>, Refused> {
|
||||||
|
let _g = self.guard().map_err(|_| Refused("internal"))?;
|
||||||
|
let mut f = self.load().map_err(|_| Refused("internal"))?;
|
||||||
|
let Some(m) = f.members.iter().find(|m| m.id == id).cloned() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let admins = f.members.iter().filter(|m| m.role == Role::Admin).count();
|
||||||
|
if m.role == Role::Admin && admins <= 1 {
|
||||||
|
return Err(Refused("team.last_admin"));
|
||||||
|
}
|
||||||
|
f.members.retain(|x| x.id != id);
|
||||||
|
f.sessions.retain(|s| s.member != id);
|
||||||
|
self.save(&f).map_err(|_| Refused("internal"))?;
|
||||||
|
Ok(Some(m))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record (or clear) a member's own Tessera root.
|
||||||
|
pub fn set_root(&self, member: &str, root: Option<&str>) -> Result<(), Refused> {
|
||||||
|
if root.is_some_and(|r| !valid_root(r)) {
|
||||||
|
return Err(Refused("team.root"));
|
||||||
|
}
|
||||||
|
let _g = self.guard().map_err(|_| Refused("internal"))?;
|
||||||
|
let mut f = self.load().map_err(|_| Refused("internal"))?;
|
||||||
|
let m = f
|
||||||
|
.members
|
||||||
|
.iter_mut()
|
||||||
|
.find(|m| m.id == member)
|
||||||
|
.ok_or(Refused("team.not_found"))?;
|
||||||
|
m.tessera_root = root.map(|r| r.trim().to_owned());
|
||||||
|
self.save(&f).map_err(|_| Refused("internal"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn dir(n: &str) -> PathBuf {
|
||||||
|
let d = std::env::temp_dir().join(format!("ianitor-team-{n}-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&d);
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn setup_then_invite_then_sessions() {
|
||||||
|
let d = dir("flow");
|
||||||
|
let t = Team::new(&d);
|
||||||
|
let (setup, _) = t.setup_code().unwrap();
|
||||||
|
assert!(t.redeem("isc_wrong", Some("Mark"), "Laptop").is_err());
|
||||||
|
let (mark, s1) = t.redeem(&setup, Some("Mark"), "Laptop").unwrap();
|
||||||
|
assert_eq!(mark.role, Role::Admin);
|
||||||
|
// One use only, and no second setup once there is a member.
|
||||||
|
assert_eq!(
|
||||||
|
t.redeem(&setup, Some("Eve"), "x").unwrap_err(),
|
||||||
|
Refused("session.code")
|
||||||
|
);
|
||||||
|
assert!(t.setup_code().is_err());
|
||||||
|
let (who, _) = t.check(&s1).unwrap();
|
||||||
|
assert_eq!(who.name, "Mark");
|
||||||
|
// Only hashes on disk.
|
||||||
|
let stored = std::fs::read_to_string(d.join("team.json")).unwrap();
|
||||||
|
assert!(!stored.contains(&s1) && !stored.contains(&setup));
|
||||||
|
let (_, inv) = t.invite("Petra", Role::Member, &mark.id).unwrap();
|
||||||
|
let (petra, s2) = t.redeem(&inv, Some("Someone else"), "Phone").unwrap();
|
||||||
|
assert_eq!((petra.name.as_str(), petra.role), ("Petra", Role::Member));
|
||||||
|
// The last admin cannot go; a member can, with their sessions.
|
||||||
|
assert_eq!(t.remove(&mark.id).unwrap_err(), Refused("team.last_admin"));
|
||||||
|
t.remove(&petra.id).unwrap();
|
||||||
|
assert!(t.check(&s2).is_none());
|
||||||
|
let (_, s) = t.check(&s1).unwrap();
|
||||||
|
t.end_session(&s.id).unwrap();
|
||||||
|
assert!(t.check(&s1).is_none());
|
||||||
|
let _ = std::fs::remove_dir_all(&d);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tessera_roots_are_checked() {
|
||||||
|
assert!(valid_root(&URL_SAFE_NO_PAD.encode([7u8; 32])));
|
||||||
|
assert!(!valid_root("not base64!"));
|
||||||
|
assert!(!valid_root(&URL_SAFE_NO_PAD.encode([7u8; 31])));
|
||||||
|
// Fundamentum's vector (crates/tessera/tests/mandatory.rs, MATCH_SEVENS = "016810").
|
||||||
|
assert_eq!(
|
||||||
|
match_code(&URL_SAFE_NO_PAD.encode([7u8; 32])).unwrap(),
|
||||||
|
"016 810"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! API tokens. A token is `ian_<id>_<secret>`: a 16-hex-digit id (for listing and lookup)
|
||||||
|
//! and 32 random bytes. Control stores only SHA-256 of the whole token, in `tokens.json`
|
||||||
|
//! (mode 0600), and compares in constant time.
|
||||||
|
//!
|
||||||
|
//! A fast hash is enough here: the secret has 256 bits of entropy, so nobody can find a
|
||||||
|
//! preimage by guessing, slow or fast; slow password hashes only help low-entropy secrets
|
||||||
|
//! that people pick. The comparison is constant-time anyway (it compares hashes of the
|
||||||
|
//! presented value, so even a timing leak would say nothing about a stored hash's preimage).
|
||||||
|
//!
|
||||||
|
//! The value is shown once, in the response that creates it (or by `ianitor-control token
|
||||||
|
//! create`), and never logged. Revoked and expired tokens stay listed so a script gets a
|
||||||
|
//! precise message ("revoked on …").
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use base64::Engine as _;
|
||||||
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json};
|
||||||
|
|
||||||
|
/// What a token may do. `full` (the default, and every token made before T4) may do
|
||||||
|
/// everything the API offers; `previews` may only use `/api/v1/previews` (Fabrica's branch
|
||||||
|
/// previews), so a leaked preview token can never touch another host.
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum Scope {
|
||||||
|
#[default]
|
||||||
|
Full,
|
||||||
|
Previews,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Scope {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Scope::Full => "full",
|
||||||
|
Scope::Previews => "previews",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(s: &str) -> Option<Scope> {
|
||||||
|
match s {
|
||||||
|
"full" => Some(Scope::Full),
|
||||||
|
"previews" => Some(Scope::Previews),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct TokenRecord {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub sha256: String,
|
||||||
|
pub created_at: u64,
|
||||||
|
pub expires_at: Option<u64>,
|
||||||
|
pub last_used_at: Option<u64>,
|
||||||
|
pub revoked_at: Option<u64>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub scope: Scope,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct TokenFile {
|
||||||
|
tokens: Vec<TokenRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a presented token was refused.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum Refusal {
|
||||||
|
Missing,
|
||||||
|
Unknown,
|
||||||
|
Expired(u64),
|
||||||
|
Revoked(u64),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const MAX_TOKENS: usize = 200;
|
||||||
|
const LAST_USED_GRANULARITY: u64 = 60;
|
||||||
|
|
||||||
|
pub struct Tokens {
|
||||||
|
path: PathBuf,
|
||||||
|
/// Serialises read-modify-write of the file inside this process.
|
||||||
|
lock: std::sync::Mutex<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StoreGuard<'a> {
|
||||||
|
_m: std::sync::MutexGuard<'a, ()>,
|
||||||
|
_f: std::fs::File,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn valid_name(n: &str) -> bool {
|
||||||
|
let n = n.trim();
|
||||||
|
!n.is_empty()
|
||||||
|
&& n.chars().count() <= 64
|
||||||
|
&& n.chars()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || " ._-".contains(c))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Tokens {
|
||||||
|
pub fn new(state_dir: &Path) -> Tokens {
|
||||||
|
Tokens {
|
||||||
|
path: state_dir.join("tokens.json"),
|
||||||
|
lock: std::sync::Mutex::new(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exclusive access to `tokens.json` for one read-modify-write: a mutex inside this
|
||||||
|
/// process and an advisory lock on `tokens.lock` across processes (the CLI and the
|
||||||
|
/// server), released when the guard is dropped, also if the process dies.
|
||||||
|
fn guard(&self) -> Result<StoreGuard<'_>, String> {
|
||||||
|
let m = self
|
||||||
|
.lock
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "token store unavailable".to_owned())?;
|
||||||
|
let path = self.path.with_file_name("tokens.lock");
|
||||||
|
if let Some(dir) = path.parent() {
|
||||||
|
std::fs::create_dir_all(dir)
|
||||||
|
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||||
|
}
|
||||||
|
let f = std::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.write(true)
|
||||||
|
.open(&path)
|
||||||
|
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||||
|
f.lock()
|
||||||
|
.map_err(|e| format!("cannot lock {}: {e}", path.display()))?;
|
||||||
|
Ok(StoreGuard { _m: m, _f: f })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(&self) -> Result<TokenFile, String> {
|
||||||
|
Ok(read_json(&self.path)?.unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, f: &TokenFile) -> Result<(), String> {
|
||||||
|
write_json(&self.path, f)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a token; returns the record and the value (shown once).
|
||||||
|
pub fn create(
|
||||||
|
&self,
|
||||||
|
name: &str,
|
||||||
|
expires_at: Option<u64>,
|
||||||
|
scope: Scope,
|
||||||
|
) -> Result<(TokenRecord, String), String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
|
if !valid_name(name) {
|
||||||
|
return Err("token.name".into());
|
||||||
|
}
|
||||||
|
let mut f = self.load()?;
|
||||||
|
if f.tokens.iter().filter(|t| t.revoked_at.is_none()).count() >= MAX_TOKENS {
|
||||||
|
return Err("too many tokens; revoke some first".into());
|
||||||
|
}
|
||||||
|
let id = hex(&random::<8>().map_err(|e| e.to_string())?);
|
||||||
|
let secret = URL_SAFE_NO_PAD.encode(random::<32>().map_err(|e| e.to_string())?);
|
||||||
|
let value = format!("ian_{id}_{secret}");
|
||||||
|
let rec = TokenRecord {
|
||||||
|
id,
|
||||||
|
name: name.trim().to_owned(),
|
||||||
|
sha256: sha256_hex(value.as_bytes()),
|
||||||
|
created_at: now(),
|
||||||
|
expires_at,
|
||||||
|
last_used_at: None,
|
||||||
|
revoked_at: None,
|
||||||
|
scope,
|
||||||
|
};
|
||||||
|
f.tokens.push(rec.clone());
|
||||||
|
self.save(&f)?;
|
||||||
|
Ok((rec, value))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list(&self) -> Result<Vec<TokenRecord>, String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
|
Ok(self.load()?.tokens)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn revoke(&self, id: &str) -> Result<Option<TokenRecord>, String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
|
let mut f = self.load()?;
|
||||||
|
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
if t.revoked_at.is_none() {
|
||||||
|
t.revoked_at = Some(now());
|
||||||
|
}
|
||||||
|
let r = t.clone();
|
||||||
|
self.save(&f)?;
|
||||||
|
Ok(Some(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rename(&self, id: &str, name: &str) -> Result<Option<TokenRecord>, String> {
|
||||||
|
let _g = self.guard()?;
|
||||||
|
if !valid_name(name) {
|
||||||
|
return Err("token.name".into());
|
||||||
|
}
|
||||||
|
let mut f = self.load()?;
|
||||||
|
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
t.name = name.trim().to_owned();
|
||||||
|
let r = t.clone();
|
||||||
|
self.save(&f)?;
|
||||||
|
Ok(Some(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check a presented `Authorization` value. The token never appears in an error.
|
||||||
|
pub fn check(&self, header: Option<&str>) -> Result<TokenRecord, Refusal> {
|
||||||
|
let Some(h) = header else {
|
||||||
|
return Err(Refusal::Missing);
|
||||||
|
};
|
||||||
|
let Some(value) = h.strip_prefix("Bearer ").map(str::trim) else {
|
||||||
|
return Err(Refusal::Unknown);
|
||||||
|
};
|
||||||
|
let id = value
|
||||||
|
.strip_prefix("ian_")
|
||||||
|
.and_then(|r| r.split_once('_'))
|
||||||
|
.map(|(id, _)| id)
|
||||||
|
.filter(|id| id.len() == 16)
|
||||||
|
.ok_or(Refusal::Unknown)?;
|
||||||
|
let _g = self.guard().map_err(|_| Refusal::Unknown)?;
|
||||||
|
let mut f = self.load().map_err(|_| Refusal::Unknown)?;
|
||||||
|
let presented = sha256_hex(value.as_bytes());
|
||||||
|
let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else {
|
||||||
|
return Err(Refusal::Unknown);
|
||||||
|
};
|
||||||
|
if !ct_eq(t.sha256.as_bytes(), presented.as_bytes()) {
|
||||||
|
return Err(Refusal::Unknown);
|
||||||
|
}
|
||||||
|
if let Some(r) = t.revoked_at {
|
||||||
|
return Err(Refusal::Revoked(r));
|
||||||
|
}
|
||||||
|
let n = now();
|
||||||
|
if let Some(e) = t.expires_at
|
||||||
|
&& n >= e
|
||||||
|
{
|
||||||
|
return Err(Refusal::Expired(e));
|
||||||
|
}
|
||||||
|
let rec = t.clone();
|
||||||
|
if t.last_used_at
|
||||||
|
.is_none_or(|l| n.saturating_sub(l) >= LAST_USED_GRANULARITY)
|
||||||
|
{
|
||||||
|
t.last_used_at = Some(n);
|
||||||
|
if let Err(e) = self.save(&f) {
|
||||||
|
log::warn!(target: "ianitor::tokens", "cannot record token use: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(rec)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_check_revoke() {
|
||||||
|
let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id()));
|
||||||
|
let t = Tokens::new(&d);
|
||||||
|
let (rec, value) = t.create("laptop", None, Scope::Full).unwrap();
|
||||||
|
assert!(value.starts_with("ian_"));
|
||||||
|
let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap();
|
||||||
|
assert!(!stored.contains(&value[21..]), "only the hash is stored");
|
||||||
|
assert_eq!(
|
||||||
|
t.check(Some(&format!("Bearer {value}"))).unwrap().id,
|
||||||
|
rec.id
|
||||||
|
);
|
||||||
|
assert_eq!(t.check(None).unwrap_err(), Refusal::Missing);
|
||||||
|
assert_eq!(t.check(Some(&value)).unwrap_err(), Refusal::Unknown);
|
||||||
|
let mut wrong = value.clone();
|
||||||
|
wrong.pop();
|
||||||
|
wrong.push('x');
|
||||||
|
assert_eq!(
|
||||||
|
t.check(Some(&format!("Bearer {wrong}"))).unwrap_err(),
|
||||||
|
Refusal::Unknown
|
||||||
|
);
|
||||||
|
t.revoke(&rec.id).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
t.check(Some(&format!("Bearer {value}"))).unwrap_err(),
|
||||||
|
Refusal::Revoked(_)
|
||||||
|
));
|
||||||
|
let (_, v2) = t.create("old", Some(1), Scope::Full).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
t.check(Some(&format!("Bearer {v2}"))).unwrap_err(),
|
||||||
|
Refusal::Expired(1)
|
||||||
|
);
|
||||||
|
let _ = std::fs::remove_dir_all(&d);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Small shared helpers: time, randomness, hashing, atomic file writes.
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use ring::rand::{SecureRandom, SystemRandom};
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
|
||||||
|
pub fn now() -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs())
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rfc3339(t: u64) -> String {
|
||||||
|
ianitor_core::time::rfc3339(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn random<const N: usize>() -> Result<[u8; N], std::io::Error> {
|
||||||
|
let mut b = [0u8; N];
|
||||||
|
SystemRandom::new()
|
||||||
|
.fill(&mut b)
|
||||||
|
.map_err(|_| std::io::Error::other("the system random generator failed"))?;
|
||||||
|
Ok(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hex(bytes: &[u8]) -> String {
|
||||||
|
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sha256_hex(data: &[u8]) -> String {
|
||||||
|
hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compare two byte strings in time that depends only on their length.
|
||||||
|
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
||||||
|
if a.len() != b.len() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let mut d = 0u8;
|
||||||
|
for (x, y) in a.iter().zip(b) {
|
||||||
|
d |= x ^ y;
|
||||||
|
}
|
||||||
|
std::hint::black_box(d) == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write `data` to `path` so that readers see the old or the new content, never a mix, and
|
||||||
|
/// the new content survives a crash once this returns: temporary file in the same directory,
|
||||||
|
/// fsync, rename, fsync of the directory.
|
||||||
|
pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()> {
|
||||||
|
crate::crash::fail_write(path).map_err(std::io::Error::other)?;
|
||||||
|
let dir = path
|
||||||
|
.parent()
|
||||||
|
.filter(|p| !p.as_os_str().is_empty())
|
||||||
|
.unwrap_or(Path::new("."));
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
let mut name = path.file_name().unwrap_or_default().to_os_string();
|
||||||
|
// Unique per write (process, counter, random), so two writers of the same file never
|
||||||
|
// share a temporary file.
|
||||||
|
static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
let r = random::<4>().map(|b| hex(&b))?;
|
||||||
|
name.push(format!(".tmp-{}-{n}-{r}", std::process::id()));
|
||||||
|
let tmp = dir.join(name);
|
||||||
|
{
|
||||||
|
let mut opts = std::fs::OpenOptions::new();
|
||||||
|
opts.write(true).create(true).truncate(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, mode);
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
let _ = mode;
|
||||||
|
let mut f = opts.open(&tmp)?;
|
||||||
|
f.write_all(data)?;
|
||||||
|
f.sync_all()?;
|
||||||
|
}
|
||||||
|
std::fs::rename(&tmp, path)?;
|
||||||
|
sync_dir(dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rename `from` to `to` atomically and durably.
|
||||||
|
pub fn rename_durable(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||||
|
crate::crash::fail_write(to).map_err(std::io::Error::other)?;
|
||||||
|
std::fs::rename(from, to)?;
|
||||||
|
sync_dir(to.parent().unwrap_or(Path::new(".")))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sync_dir(dir: &Path) -> std::io::Result<()> {
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
std::fs::File::open(dir)?.sync_all()?;
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
let _ = dir;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_if_exists(path: &Path) -> std::io::Result<()> {
|
||||||
|
match std::fs::remove_file(path) {
|
||||||
|
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read a JSON state file; `Ok(None)` when it does not exist.
|
||||||
|
pub fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, String> {
|
||||||
|
match std::fs::read(path) {
|
||||||
|
Ok(b) => serde_json::from_slice(&b)
|
||||||
|
.map(Some)
|
||||||
|
.map_err(|e| format!("{} is damaged: {e}", path.display())),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||||
|
Err(e) => Err(format!("cannot read {}: {e}", path.display())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write a JSON state file atomically, readable by its owner only.
|
||||||
|
pub fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
|
||||||
|
let mut text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
|
||||||
|
text.push(b'\n');
|
||||||
|
write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn constant_time_compare() {
|
||||||
|
assert!(ct_eq(b"abc", b"abc"));
|
||||||
|
assert!(!ct_eq(b"abc", b"abd"));
|
||||||
|
assert!(!ct_eq(b"abc", b"ab"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn concurrent_atomic_writes_of_one_file_all_succeed() {
|
||||||
|
let d = std::env::temp_dir().join(format!("ianitor-util-c-{}", std::process::id()));
|
||||||
|
let p = d.join("paused.json");
|
||||||
|
let threads: Vec<_> = (0..16)
|
||||||
|
.map(|i| {
|
||||||
|
let p = p.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
(0..50).all(|_| write_atomic(&p, format!("{i}").as_bytes(), 0o600).is_ok())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
for t in threads {
|
||||||
|
assert!(t.join().unwrap(), "a write failed");
|
||||||
|
}
|
||||||
|
let left: Vec<_> = std::fs::read_dir(&d).unwrap().collect();
|
||||||
|
assert_eq!(left.len(), 1, "no temporary files left");
|
||||||
|
let _ = std::fs::remove_dir_all(&d);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn atomic_write_replaces() {
|
||||||
|
let d = std::env::temp_dir().join(format!("ianitor-util-{}", std::process::id()));
|
||||||
|
let p = d.join("f.json");
|
||||||
|
write_atomic(&p, b"one", 0o600).unwrap();
|
||||||
|
write_atomic(&p, b"two", 0o600).unwrap();
|
||||||
|
assert_eq!(std::fs::read(&p).unwrap(), b"two");
|
||||||
|
let _ = std::fs::remove_dir_all(&d);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Windows Server, Caddy mode (Fabrica docs/32_coherence.md §2.5, T4): what the service
|
||||||
|
//! control manager starts. `ianitor-control service control --config <c>` is the control
|
||||||
|
//! plane, `ianitor-control service caddy-guard --config <c>` the Caddy trial deadline guard
|
||||||
|
//! (its own service, so a hung or crashed control cannot leave Caddy on an unconfirmed
|
||||||
|
//! trial). Both stop cleanly on the SCM's Stop. `deploy/windows/install.ps1` registers them.
|
||||||
|
//! Logs go to the file given with `--log-file` (stderr goes nowhere under the SCM).
|
||||||
|
|
||||||
|
use std::ffi::OsString;
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use windows_service::service::{
|
||||||
|
ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType,
|
||||||
|
};
|
||||||
|
use windows_service::service_control_handler::{self, ServiceControlHandlerResult};
|
||||||
|
use windows_service::{define_windows_service, service_dispatcher};
|
||||||
|
|
||||||
|
static ARGS: OnceLock<Vec<String>> = OnceLock::new();
|
||||||
|
|
||||||
|
define_windows_service!(ffi_service_main, service_main);
|
||||||
|
|
||||||
|
/// Hand this process to the service control manager (blocks until the service stops).
|
||||||
|
pub fn run(args: &[String]) -> Result<(), String> {
|
||||||
|
let _ = ARGS.set(args.to_vec());
|
||||||
|
// The name is ignored for a service in its own process.
|
||||||
|
service_dispatcher::start("IanitorControl", ffi_service_main)
|
||||||
|
.map_err(|e| format!("not started by the service control manager ({e}); run it as a service, or use --config to run it in a console"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status(state: ServiceState, code: u32) -> ServiceStatus {
|
||||||
|
ServiceStatus {
|
||||||
|
service_type: ServiceType::OWN_PROCESS,
|
||||||
|
current_state: state,
|
||||||
|
controls_accepted: if state == ServiceState::Running {
|
||||||
|
ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN
|
||||||
|
} else {
|
||||||
|
ServiceControlAccept::empty()
|
||||||
|
},
|
||||||
|
exit_code: ServiceExitCode::Win32(code),
|
||||||
|
checkpoint: 0,
|
||||||
|
wait_hint: Duration::from_secs(10),
|
||||||
|
process_id: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn service_main(_: Vec<OsString>) {
|
||||||
|
let args = ARGS.get().cloned().unwrap_or_default();
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
|
||||||
|
let tx = std::sync::Mutex::new(Some(tx));
|
||||||
|
let handler = move |c| match c {
|
||||||
|
ServiceControl::Stop | ServiceControl::Shutdown => {
|
||||||
|
if let Ok(mut t) = tx.lock()
|
||||||
|
&& let Some(t) = t.take()
|
||||||
|
{
|
||||||
|
let _ = t.send(());
|
||||||
|
}
|
||||||
|
ServiceControlHandlerResult::NoError
|
||||||
|
}
|
||||||
|
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
|
||||||
|
_ => ServiceControlHandlerResult::NotImplemented,
|
||||||
|
};
|
||||||
|
let Ok(h) = service_control_handler::register("IanitorControl", handler) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let _ = h.set_service_status(status(ServiceState::Running, 0));
|
||||||
|
let result = serve(&args, rx);
|
||||||
|
if let Err(e) = &result {
|
||||||
|
log::error!(target: "ianitor::service", "{e}");
|
||||||
|
}
|
||||||
|
let _ = h.set_service_status(status(ServiceState::Stopped, u32::from(result.is_err())));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serve(args: &[String], stop: tokio::sync::oneshot::Receiver<()>) -> Result<(), String> {
|
||||||
|
let what = args.first().map(String::as_str).unwrap_or("control");
|
||||||
|
let config = args
|
||||||
|
.iter()
|
||||||
|
.position(|a| a == "--config")
|
||||||
|
.and_then(|i| args.get(i + 1))
|
||||||
|
.ok_or("service: --config <control.toml> is required")?;
|
||||||
|
let cfg =
|
||||||
|
ianitor_control::Config::load(std::path::Path::new(config)).map_err(|e| e.to_string())?;
|
||||||
|
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
rt.block_on(async move {
|
||||||
|
match what {
|
||||||
|
"control" => {
|
||||||
|
ianitor_control::serve(cfg, async {
|
||||||
|
let _ = stop.await;
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
"caddy-guard" => {
|
||||||
|
tokio::select! {
|
||||||
|
r = ianitor_control::caddy_guard::run(cfg) => r,
|
||||||
|
_ = stop => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => Err(format!(
|
||||||
|
"service: unknown part {other:?} (control or caddy-guard)"
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,549 @@
|
|||||||
|
// 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 API's edges (ROADMAP §6 phase 2, tests first): requests without a valid token are
|
||||||
|
//! rejected on every route and tokens never reach a log, an error or a state file; request
|
||||||
|
//! bodies are hostile input; the routes repository holds only host files; control only
|
||||||
|
//! listens on loopback; the OpenAPI document covers the API.
|
||||||
|
|
||||||
|
#![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 (edge admin socket); run it in WSL2",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::common::{Env, EnvSpec, host};
|
||||||
|
use ianitor_testkit::more::tcp_raw;
|
||||||
|
use ianitor_testkit::upstream::Echo;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
/// Every (method, path) in the OpenAPI document, with path parameters filled in.
|
||||||
|
fn routes(doc: &Value) -> Vec<(String, String)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (path, item) in doc["paths"].as_object().unwrap() {
|
||||||
|
// The one-time device download is the one call without a token: the link is
|
||||||
|
// the secret (G15). Every other call needs one.
|
||||||
|
if path.starts_with("/api/v1/device-bundles/") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for method in ["get", "post", "put", "patch", "delete"] {
|
||||||
|
if item.get(method).is_some() {
|
||||||
|
let p = path
|
||||||
|
.replace("{hostname}", "a.test")
|
||||||
|
.replace("{id}", "x")
|
||||||
|
.replace("{change_id}", "x");
|
||||||
|
out.push((method.to_uppercase(), p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn requests_without_a_valid_token_are_rejected_and_tokens_are_never_logged() {
|
||||||
|
let good = Echo::start("good").await;
|
||||||
|
let mut env = Env::new(EnvSpec::default()).await;
|
||||||
|
env.start_control(None);
|
||||||
|
let doc = env.call("GET", "/api/v1/openapi.json", None).await;
|
||||||
|
assert_eq!(doc.status, 200, "{}", doc.text);
|
||||||
|
let routes = routes(&doc.json);
|
||||||
|
assert!(routes.len() >= 25, "{routes:?}");
|
||||||
|
|
||||||
|
// Make a second token through the API and revoke it, to test a revoked one too.
|
||||||
|
let made = env
|
||||||
|
.call("POST", "/api/v1/tokens", Some(json!({ "name": "script" })))
|
||||||
|
.await;
|
||||||
|
assert_eq!(made.status, 201, "{}", made.text);
|
||||||
|
let revoked = made.json["token"].as_str().unwrap().to_owned();
|
||||||
|
let rid = made.json["id"].as_str().unwrap().to_owned();
|
||||||
|
assert_eq!(
|
||||||
|
env.call("DELETE", &format!("/api/v1/tokens/{rid}"), None)
|
||||||
|
.await
|
||||||
|
.status,
|
||||||
|
204
|
||||||
|
);
|
||||||
|
// A listing never shows values or hashes.
|
||||||
|
let list = env.call("GET", "/api/v1/tokens", None).await;
|
||||||
|
assert!(
|
||||||
|
!list.text.contains(&revoked) && !list.text.contains("sha256"),
|
||||||
|
"{}",
|
||||||
|
list.text
|
||||||
|
);
|
||||||
|
assert!(!list.text.contains(&env.token));
|
||||||
|
|
||||||
|
let mut wrong = env.token.clone();
|
||||||
|
wrong.pop();
|
||||||
|
wrong.push(if env.token.ends_with('A') { 'B' } else { 'A' });
|
||||||
|
type Case = (String, Vec<(String, String)>, &'static str);
|
||||||
|
let cases: Vec<Case> = vec![
|
||||||
|
("no header".into(), vec![], "token.missing"),
|
||||||
|
(
|
||||||
|
"not bearer".into(),
|
||||||
|
vec![("Authorization".into(), env.token.clone())],
|
||||||
|
"token.unknown",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"basic".into(),
|
||||||
|
vec![("Authorization".into(), "Basic YWRtaW46YWRtaW4=".into())],
|
||||||
|
"token.unknown",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"one char off".into(),
|
||||||
|
vec![("Authorization".into(), format!("Bearer {wrong}"))],
|
||||||
|
"token.unknown",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"made up".into(),
|
||||||
|
vec![(
|
||||||
|
"Authorization".into(),
|
||||||
|
"Bearer ian_0000000000000000_xxxxxxxx".into(),
|
||||||
|
)],
|
||||||
|
"token.unknown",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"revoked".into(),
|
||||||
|
vec![("Authorization".into(), format!("Bearer {revoked}"))],
|
||||||
|
"token.revoked",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"empty bearer".into(),
|
||||||
|
vec![("Authorization".into(), "Bearer ".into())],
|
||||||
|
"token.unknown",
|
||||||
|
),
|
||||||
|
// Identity headers without edge's proof are refused (docs/ui-api.md G14).
|
||||||
|
(
|
||||||
|
"remote-user".into(),
|
||||||
|
vec![
|
||||||
|
("Remote-User".into(), "mark".into()),
|
||||||
|
("Remote-Groups".into(), "admins".into()),
|
||||||
|
],
|
||||||
|
"ui.no_proof",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (what, headers, code) in &cases {
|
||||||
|
let hs: Vec<(&str, &str)> = headers
|
||||||
|
.iter()
|
||||||
|
.map(|(a, b)| (a.as_str(), b.as_str()))
|
||||||
|
.collect();
|
||||||
|
for (method, path) in &routes {
|
||||||
|
let body = (method != "GET" && method != "DELETE").then(|| json!({}));
|
||||||
|
let r = env.call_with(method, path, &hs, body).await;
|
||||||
|
assert_eq!(r.status, 401, "{what}: {method} {path}: {}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], *code, "{what}: {method} {path}");
|
||||||
|
assert!(r.json["error"]["message"].as_str().unwrap().len() > 10);
|
||||||
|
assert!(r.json["request_id"].is_string() && r.json["server_time"].is_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Unknown paths are refused the same way, before anything else.
|
||||||
|
assert_eq!(
|
||||||
|
env.call_with("GET", "/api/v1/nope", &[], None).await.status,
|
||||||
|
401
|
||||||
|
);
|
||||||
|
// Outside /api/ only the built UI is served (no data, no token); none is set up here.
|
||||||
|
assert_eq!(env.call_with("GET", "/", &[], None).await.status, 404);
|
||||||
|
|
||||||
|
// A wrong Host header (DNS rebinding) is refused even with a good token.
|
||||||
|
let auth = format!("Bearer {}", env.token);
|
||||||
|
let raw = format!(
|
||||||
|
"GET /api/v1/overview HTTP/1.1\r\nHost: evil.example\r\nAuthorization: {auth}\r\nConnection: close\r\n\r\n"
|
||||||
|
);
|
||||||
|
let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap();
|
||||||
|
assert_eq!(r.status, 403, "{}", r.text());
|
||||||
|
// A browser write without the UI header is refused (CSRF).
|
||||||
|
let r = env
|
||||||
|
.call_with(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
&[("Authorization", &auth), ("Origin", "https://evil.example")],
|
||||||
|
Some(json!({ "host": host("a.test", &good.url(), false) })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 403, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "request.csrf");
|
||||||
|
let r = env
|
||||||
|
.call_with(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
&[
|
||||||
|
("Authorization", &auth),
|
||||||
|
("Origin", "http://127.0.0.1"),
|
||||||
|
("X-Ianitor-UI", "1"),
|
||||||
|
],
|
||||||
|
Some(json!({ "host": host("a.test", &good.url(), false) })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
env.wait_apply(r.json["apply"]["id"].as_str().unwrap())
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Exercise the rest with the good token, then look for any token anywhere.
|
||||||
|
for (method, path) in &routes {
|
||||||
|
if method == "GET" {
|
||||||
|
env.call(method, path, None).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||||
|
env.kill_control();
|
||||||
|
let mut everything = env.control_log();
|
||||||
|
for f in [
|
||||||
|
"applies.json",
|
||||||
|
"push.json",
|
||||||
|
"share-links.json",
|
||||||
|
"journal.json",
|
||||||
|
] {
|
||||||
|
everything.push_str(&env.file(&format!("state/{f}")));
|
||||||
|
}
|
||||||
|
everything.push_str(&env.file("edge/edge.json"));
|
||||||
|
everything.push_str(&env.git(&["log", "-p", "--all"]));
|
||||||
|
// `ian_<16 hex>_<secret>`; the secret itself may contain '_'.
|
||||||
|
let secret_part = |t: &str| {
|
||||||
|
assert!(t.starts_with("ian_") && t.as_bytes()[20] == b'_');
|
||||||
|
t[21..].to_owned()
|
||||||
|
};
|
||||||
|
for t in [&env.token, &revoked] {
|
||||||
|
assert!(
|
||||||
|
!everything.contains(secret_part(t).as_str()),
|
||||||
|
"a token leaked"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let stored = env.file("state/tokens.json");
|
||||||
|
for t in [&env.token, &revoked] {
|
||||||
|
assert!(
|
||||||
|
!stored.contains(secret_part(t).as_str()),
|
||||||
|
"tokens.json holds a value, not a hash"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let mode = std::fs::metadata(env.dir.join("state/tokens.json"))
|
||||||
|
.unwrap()
|
||||||
|
.permissions()
|
||||||
|
.mode();
|
||||||
|
assert_eq!(mode & 0o077, 0, "tokens.json is private");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn bodies_are_hostile_input() {
|
||||||
|
let good = Echo::start("good").await;
|
||||||
|
let mut env = Env::new(EnvSpec::default()).await;
|
||||||
|
env.start_control(None);
|
||||||
|
let auth = format!("Bearer {}", env.token);
|
||||||
|
|
||||||
|
// Unknown fields, at the top and inside the host.
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
Some(json!({ "host": host("a.test", &good.url(), false), "colour": 1 })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "request.body_unknown_field");
|
||||||
|
assert_eq!(r.json["error"]["field"], "colour");
|
||||||
|
let mut h = host("a.test", &good.url(), false);
|
||||||
|
h["upstream"] = json!("typo");
|
||||||
|
let r = env
|
||||||
|
.call("POST", "/api/v1/hosts", Some(json!({ "host": h })))
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
r.json["error"]["code"], "request.body_unknown_field",
|
||||||
|
"{}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
// Wrong types never echo the value sent.
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/tokens",
|
||||||
|
Some(json!({ "name": ["secret-ish-value"] })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 400, "{}", r.text);
|
||||||
|
assert!(!r.text.contains("secret-ish-value"), "{}", r.text);
|
||||||
|
// Nor do odd field names, path parameters or credentials in an upstream URL.
|
||||||
|
let r = env
|
||||||
|
.call("POST", "/api/v1/tokens", Some(json!({ "pass:hunter2": 1 })))
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
assert!(!r.text.contains("hunter2"), "{}", r.text);
|
||||||
|
let r = env.call("GET", "/api/v1/hosts/x%3Chunter2%3E", None).await;
|
||||||
|
assert_eq!(r.status, 404, "{}", r.text);
|
||||||
|
assert!(!r.text.contains("hunter2"), "{}", r.text);
|
||||||
|
let mut leaky = host("a.test", "http://admin:hunter2@10.0.0.2:3000", false);
|
||||||
|
leaky["upstreams"] = json!(["http://admin:hunter2@10.0.0.2:3000", "ftp://u:hunter2@x"]);
|
||||||
|
let r = env
|
||||||
|
.call("POST", "/api/v1/hosts", Some(json!({ "host": leaky })))
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
assert!(!r.text.contains("hunter2"), "{}", r.text);
|
||||||
|
// Not JSON, wrong content type, too large.
|
||||||
|
let raw = format!(
|
||||||
|
"POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: application/json\r\nContent-Length: 5\r\nConnection: close\r\n\r\n{{{{{{{{{{",
|
||||||
|
env.api
|
||||||
|
);
|
||||||
|
let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap();
|
||||||
|
assert_eq!(r.status, 400, "{}", r.text());
|
||||||
|
let raw = format!(
|
||||||
|
"POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}",
|
||||||
|
env.api
|
||||||
|
);
|
||||||
|
let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap();
|
||||||
|
assert_eq!(r.status, 415, "{}", r.text());
|
||||||
|
let big = "x".repeat(70 * 1024);
|
||||||
|
let r = env
|
||||||
|
.call("POST", "/api/v1/tokens", Some(json!({ "name": big })))
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 413, "{}", &r.text[..r.text.len().min(300)]);
|
||||||
|
|
||||||
|
// Field errors come back as one envelope with codes and field paths.
|
||||||
|
let mut bad = host("a.test", "ftp://x", true);
|
||||||
|
bad["health_check"]["interval_secs"] = json!(0);
|
||||||
|
let r = env
|
||||||
|
.call("POST", "/api/v1/hosts", Some(json!({ "host": bad })))
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
let fields: Vec<&str> = r.json["errors"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.filter_map(|e| e["field"].as_str())
|
||||||
|
.collect();
|
||||||
|
assert!(fields.contains(&"upstreams[0]"), "{fields:?}");
|
||||||
|
assert!(fields.contains(&"health_check.interval_secs"), "{fields:?}");
|
||||||
|
assert_eq!(r.json["error"]["code"], "apply.failed.validation");
|
||||||
|
let codes: Vec<&str> = r.json["errors"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.filter_map(|e| e["code"].as_str())
|
||||||
|
.collect();
|
||||||
|
assert!(codes.contains(&"host.upstream.scheme"), "{codes:?}");
|
||||||
|
let msg = r.json["errors"][0]["message"].as_str().unwrap();
|
||||||
|
assert!(
|
||||||
|
!msg.contains("TOML") && !msg.contains("hosts/"),
|
||||||
|
"plain English: {msg}"
|
||||||
|
);
|
||||||
|
// Validate without applying.
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts/validate?mode=create",
|
||||||
|
Some(host("a.test", &good.url(), false)),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
// A hostname that does not match the path, a host that does not exist.
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"PUT",
|
||||||
|
"/api/v1/hosts/b.test",
|
||||||
|
Some(json!({ "host": host("a.test", &good.url(), false) })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
r.json["error"]["code"], "host.hostname.mismatch",
|
||||||
|
"{}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
let r = env.call("DELETE", "/api/v1/hosts/nope.test", None).await;
|
||||||
|
assert_eq!(r.status, 404);
|
||||||
|
let r = env.call("GET", "/api/v1/hosts/..%2f..%2fetc", None).await;
|
||||||
|
assert_eq!(r.status, 404);
|
||||||
|
// base_rev must be a commit of the history.
|
||||||
|
let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "0".repeat(40) }))).await;
|
||||||
|
assert_eq!(r.json["error"]["code"], "request.base_rev", "{}", r.text);
|
||||||
|
let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "--upload-pack=touch /tmp/x" }))).await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
|
||||||
|
// Idempotency-Key: a retry returns the same apply; another body with it is refused.
|
||||||
|
let body = json!({ "host": host("a.test", &good.url(), false) });
|
||||||
|
let k = [
|
||||||
|
("Authorization", auth.as_str()),
|
||||||
|
("Idempotency-Key", "click-1"),
|
||||||
|
];
|
||||||
|
let first = env
|
||||||
|
.call_with("POST", "/api/v1/hosts", &k, Some(body.clone()))
|
||||||
|
.await;
|
||||||
|
assert_eq!(first.status, 202, "{}", first.text);
|
||||||
|
let again = env.call_with("POST", "/api/v1/hosts", &k, Some(body)).await;
|
||||||
|
assert_eq!(again.status, 202, "{}", again.text);
|
||||||
|
assert_eq!(again.json["apply"]["id"], first.json["apply"]["id"]);
|
||||||
|
let other = env
|
||||||
|
.call_with(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
&k,
|
||||||
|
Some(json!({ "host": host("b.test", &good.url(), false) })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(other.status, 422);
|
||||||
|
assert_eq!(other.json["error"]["code"], "request.idempotency");
|
||||||
|
env.wait_apply(first.json["apply"]["id"].as_str().unwrap())
|
||||||
|
.await;
|
||||||
|
// Taken hostname.
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
Some(json!({ "host": host("a.test", &good.url(), false) })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.json["error"]["code"], "host.hostname.taken", "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["field"], "hostname");
|
||||||
|
// The overview answers 304 to its own ETag.
|
||||||
|
let o = env.call("GET", "/api/v1/overview", None).await;
|
||||||
|
let etag = o.header("etag").unwrap().to_owned();
|
||||||
|
let r = env
|
||||||
|
.call_with(
|
||||||
|
"GET",
|
||||||
|
"/api/v1/overview",
|
||||||
|
&[("Authorization", &auth), ("If-None-Match", &etag)],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 304);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn the_routes_repository_holds_only_host_files() {
|
||||||
|
let good = Echo::start("good").await;
|
||||||
|
let mut env = Env::new(EnvSpec::default()).await;
|
||||||
|
env.start_control(None);
|
||||||
|
assert_eq!(
|
||||||
|
env.add_host(host("a.test", &good.url(), false)).await["state"],
|
||||||
|
"kept"
|
||||||
|
);
|
||||||
|
let good_edge = env.file("edge/edge.json");
|
||||||
|
env.kill_control();
|
||||||
|
// Someone pushes a stray file and a nested folder straight into the repository.
|
||||||
|
let work = env.dir.join("work");
|
||||||
|
let git = |args: &[&str], cwd: &std::path::Path| {
|
||||||
|
let o = std::process::Command::new("git")
|
||||||
|
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
|
||||||
|
.args(args)
|
||||||
|
.current_dir(cwd)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
o.status.success(),
|
||||||
|
"{args:?} {}",
|
||||||
|
String::from_utf8_lossy(&o.stderr)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
git(
|
||||||
|
&[
|
||||||
|
"clone",
|
||||||
|
"--quiet",
|
||||||
|
&env.repo().to_string_lossy(),
|
||||||
|
&work.to_string_lossy(),
|
||||||
|
],
|
||||||
|
&env.dir.join("."),
|
||||||
|
);
|
||||||
|
std::fs::create_dir_all(work.join("hosts/sub")).unwrap();
|
||||||
|
std::fs::write(work.join("README.md"), "hello").unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
work.join("hosts/sub/b.test.toml"),
|
||||||
|
"hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
git(&["add", "-A"], &work);
|
||||||
|
git(&["commit", "--quiet", "-m", "stray"], &work);
|
||||||
|
git(&["push", "--quiet", "origin", "HEAD:main"], &work);
|
||||||
|
|
||||||
|
env.start_control(None);
|
||||||
|
let o = env.call("GET", "/api/v1/overview", None).await;
|
||||||
|
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
Some(json!({ "host": host("c.test", &good.url(), false) })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 409, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "control.paused");
|
||||||
|
// Edge keeps the last good config; nothing stray was compiled.
|
||||||
|
assert_eq!(env.file("edge/edge.json"), good_edge);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn control_only_listens_on_loopback() {
|
||||||
|
let env = Env::new(EnvSpec::default()).await;
|
||||||
|
let text = std::fs::read_to_string(env.config_path()).unwrap();
|
||||||
|
let open = text.replace(
|
||||||
|
&format!("listen = \"{}\"", env.api),
|
||||||
|
"listen = \"0.0.0.0:7979\"",
|
||||||
|
);
|
||||||
|
std::fs::write(env.config_path(), open).unwrap();
|
||||||
|
let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
|
||||||
|
.arg("--config")
|
||||||
|
.arg(env.config_path())
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(!out.status.success());
|
||||||
|
assert!(
|
||||||
|
String::from_utf8_lossy(&out.stderr).contains("loopback"),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
assert!(std::net::TcpStream::connect("127.0.0.1:7979").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn the_overview_has_everything_the_main_screen_needs() {
|
||||||
|
let good = Echo::start("good").await;
|
||||||
|
let mut env = Env::new(EnvSpec::default()).await;
|
||||||
|
env.start_control(None);
|
||||||
|
env.add_host(host("a.test", &good.url(), true)).await;
|
||||||
|
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||||
|
let o = env.call("GET", "/api/v1/overview", None).await;
|
||||||
|
assert_eq!(o.status, 200, "{}", o.text);
|
||||||
|
for k in [
|
||||||
|
"counts",
|
||||||
|
"hosts",
|
||||||
|
"engine",
|
||||||
|
"last_apply",
|
||||||
|
"undo",
|
||||||
|
"repo",
|
||||||
|
"site",
|
||||||
|
"server_time",
|
||||||
|
"rev",
|
||||||
|
] {
|
||||||
|
assert!(o.json.get(k).is_some(), "{k} missing: {}", o.text);
|
||||||
|
}
|
||||||
|
assert_eq!(o.json["counts"]["hosts"], 1);
|
||||||
|
assert_eq!(o.json["counts"]["healthy"], 1, "{}", o.text);
|
||||||
|
let h = &o.json["hosts"][0];
|
||||||
|
assert_eq!(h["health"]["state"], "healthy");
|
||||||
|
assert!(h["health"]["latency_ms"].is_u64());
|
||||||
|
assert_eq!(h["certificate"]["state"], "ok");
|
||||||
|
assert_eq!(o.json["engine"]["running"], "pingora");
|
||||||
|
assert_eq!(o.json["engine"]["state"], "running");
|
||||||
|
assert_eq!(o.json["last_apply"]["state"], "kept");
|
||||||
|
assert_eq!(o.json["undo"]["available"], true);
|
||||||
|
assert!(o.json["intermediate"].is_null());
|
||||||
|
// The CLI lists tokens without values.
|
||||||
|
let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
|
||||||
|
.args(["token", "list", "--config"])
|
||||||
|
.arg(env.config_path())
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
let text = String::from_utf8_lossy(&out.stdout);
|
||||||
|
assert!(text.contains("test") && !text.contains(&env.token[21..]));
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,280 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Caddy mode end to end (T4: Windows Server runs control with Caddy as the data plane, no
|
||||||
|
//! edge). Control runs with `engine = caddy`, Caddy's admin API on loopback TCP (as on
|
||||||
|
//! Windows), and the Domi CA. A previews-only token opens a branch preview; the apply goes
|
||||||
|
//! through Caddy (trial, watch, confirm); the preview's address then answers through Caddy
|
||||||
|
//! with a Domi certificate; closing it takes it away again. Runs on Windows and on Linux.
|
||||||
|
//! Needs `caddy` on PATH or `$IANITOR_CADDY_BIN` (else it fails, unless IANITOR_ALLOW_SKIP=1).
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use ianitor_control::Config;
|
||||||
|
use ianitor_control::tokens::{Scope, Tokens};
|
||||||
|
use ianitor_testkit::client::{self, Req};
|
||||||
|
use ianitor_testkit::more::{JsonResp, tcp_json};
|
||||||
|
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, require_binary, wait_for_port};
|
||||||
|
use ianitor_testkit::upstream::Echo;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
fn s(p: &std::path::Path) -> String {
|
||||||
|
p.to_string_lossy().replace('\\', "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call(
|
||||||
|
api: SocketAddr,
|
||||||
|
token: &str,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
body: Option<Value>,
|
||||||
|
) -> JsonResp {
|
||||||
|
let auth = format!("Bearer {token}");
|
||||||
|
tcp_json(
|
||||||
|
api,
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
&[("Authorization", &auth)],
|
||||||
|
body.as_ref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn settle(api: SocketAddr, token: &str, apply: &Value) -> Value {
|
||||||
|
let id = apply["id"].as_str().unwrap().to_owned();
|
||||||
|
let t = Instant::now();
|
||||||
|
loop {
|
||||||
|
let r = call(api, token, "GET", &format!("/api/v1/applies/{id}"), None).await;
|
||||||
|
if ["kept", "reverted", "failed"].contains(&r.json["state"].as_str().unwrap_or("")) {
|
||||||
|
return r.json;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
t.elapsed() < Duration::from_secs(90),
|
||||||
|
"apply stuck: {}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
tokio::time::sleep(Duration::from_millis(700)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_branch_preview_answers_through_caddy_without_an_edge() {
|
||||||
|
let Some(caddy) = require_binary("caddy") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let dir = TempDir::new("caddy-mode");
|
||||||
|
for d in [
|
||||||
|
"state",
|
||||||
|
"edge",
|
||||||
|
"caddy",
|
||||||
|
"certs",
|
||||||
|
"creds",
|
||||||
|
"caddy-state",
|
||||||
|
"root",
|
||||||
|
"xdg",
|
||||||
|
] {
|
||||||
|
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||||
|
}
|
||||||
|
// The offline root (a test one) and the intermediate's password.
|
||||||
|
let now = ianitor_control::util::now();
|
||||||
|
let (root_pem, root_key) = ianitor_core::pki::create_root(now as i64).unwrap();
|
||||||
|
std::fs::write(dir.join("root/domi-root.crt"), &root_pem).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.join("creds/pki-password"),
|
||||||
|
"caddy-mode-test-password-0123456789",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let api = local(free_port());
|
||||||
|
let admin = local(free_port());
|
||||||
|
let (http, https) = (free_port(), free_port());
|
||||||
|
// Caddy starts with only its admin API, as the installer starts it; control loads the rest.
|
||||||
|
let boot = json!({"admin": {"listen": admin.to_string()}}).to_string();
|
||||||
|
std::fs::write(dir.join("caddy/boot.json"), &boot).unwrap();
|
||||||
|
let log = std::fs::File::create(dir.join("caddy.log")).unwrap();
|
||||||
|
let _caddy = ChildGuard(
|
||||||
|
Command::new(&caddy)
|
||||||
|
.args(["run", "--config"])
|
||||||
|
.arg(dir.join("caddy/boot.json"))
|
||||||
|
.env("HOME", dir.join("xdg"))
|
||||||
|
.env("XDG_CONFIG_HOME", dir.join("xdg"))
|
||||||
|
.env("XDG_DATA_HOME", dir.join("xdg"))
|
||||||
|
.env("APPDATA", dir.join("xdg"))
|
||||||
|
.stdout(Stdio::from(log.try_clone().unwrap()))
|
||||||
|
.stderr(Stdio::from(log))
|
||||||
|
.spawn()
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
wait_for_port(admin, Duration::from_secs(60)),
|
||||||
|
"Caddy's admin API did not start"
|
||||||
|
);
|
||||||
|
std::fs::write(dir.join("state/engine"), "caddy\n").unwrap();
|
||||||
|
|
||||||
|
let text = format!(
|
||||||
|
r#"listen = "{api}"
|
||||||
|
state_dir = "{state}"
|
||||||
|
credentials_dir = "{creds}"
|
||||||
|
watch_secs = 2
|
||||||
|
watch_every_secs = 1
|
||||||
|
trial_margin_secs = 5
|
||||||
|
|
||||||
|
[routes]
|
||||||
|
repo = "{repo}"
|
||||||
|
|
||||||
|
[edge]
|
||||||
|
config = "{edge}/edge.json"
|
||||||
|
share_revocations = "{edge}/share-revocations.json"
|
||||||
|
|
||||||
|
[caddy]
|
||||||
|
config = "{caddy_dir}/caddy.json"
|
||||||
|
|
||||||
|
[compile]
|
||||||
|
http_listen = "127.0.0.1:{http}"
|
||||||
|
https_listen = "127.0.0.1:{https}"
|
||||||
|
cert_dir = "{certs}"
|
||||||
|
state_dir = "{caddy_state}"
|
||||||
|
access_log = "{caddy_state}/access.log"
|
||||||
|
caddy_credentials_dir = "{creds}"
|
||||||
|
caddy_admin = "{admin}"
|
||||||
|
|
||||||
|
[pki]
|
||||||
|
root_cert = "{root}/domi-root.crt"
|
||||||
|
kdf_iterations = 10000
|
||||||
|
|
||||||
|
[engine]
|
||||||
|
file = "{state}/engine"
|
||||||
|
units = "none"
|
||||||
|
|
||||||
|
[previews]
|
||||||
|
domain = "pv.test"
|
||||||
|
tls = "domi"
|
||||||
|
upstreams = ["127.0.0.1:1024-65535"]
|
||||||
|
min_ttl_secs = 60
|
||||||
|
"#,
|
||||||
|
state = s(&dir.join("state")),
|
||||||
|
creds = s(&dir.join("creds")),
|
||||||
|
repo = s(&dir.join("routes.git")),
|
||||||
|
edge = s(&dir.join("edge")),
|
||||||
|
caddy_dir = s(&dir.join("caddy")),
|
||||||
|
certs = s(&dir.join("certs")),
|
||||||
|
caddy_state = s(&dir.join("caddy-state")),
|
||||||
|
root = s(&dir.join("root")),
|
||||||
|
);
|
||||||
|
std::fs::write(dir.join("control.toml"), text).unwrap();
|
||||||
|
let cfg = Config::load(&dir.join("control.toml")).unwrap();
|
||||||
|
|
||||||
|
// The intermediate, signed by the test root (the offline step of docs/pki.md).
|
||||||
|
{
|
||||||
|
let c = ianitor_control::Control::open(cfg.clone()).await.unwrap();
|
||||||
|
let p = c.pki.as_ref().unwrap();
|
||||||
|
let r = p.request_renewal(now, "test").unwrap();
|
||||||
|
let signed = ianitor_core::pki::sign_intermediate(
|
||||||
|
&root_pem,
|
||||||
|
&root_key,
|
||||||
|
r.csr_pem.as_deref().unwrap(),
|
||||||
|
now as i64,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
p.install_intermediate(&r.id, &signed, now).unwrap();
|
||||||
|
}
|
||||||
|
let tokens = Tokens::new(&dir.join("state"));
|
||||||
|
let (_, admin_tok) = tokens.create("admin", None, Scope::Full).unwrap();
|
||||||
|
let (_, fabrica) = tokens.create("fabrica", None, Scope::Previews).unwrap();
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
|
||||||
|
tokio::spawn(ianitor_control::serve(cfg, async {
|
||||||
|
let _ = rx.await;
|
||||||
|
}));
|
||||||
|
assert!(wait_for_port(api, Duration::from_secs(20)));
|
||||||
|
|
||||||
|
let r = call(api, &admin_tok, "GET", "/api/v1/overview", None).await;
|
||||||
|
assert_eq!(r.json["engine"]["running"], "caddy", "{}", r.text);
|
||||||
|
assert_eq!(r.json["engine"]["switchable"], false, "{}", r.text);
|
||||||
|
|
||||||
|
// Fabrica opens the branch's preview.
|
||||||
|
let app = Echo::start("preview-app").await;
|
||||||
|
let r = call(
|
||||||
|
api,
|
||||||
|
&fabrica,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews",
|
||||||
|
Some(json!({"project": "shop", "branch": "fix-42", "upstream": app.url(), "ttl": 3600})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned();
|
||||||
|
assert_eq!(host, "fix-42--shop.pv.test");
|
||||||
|
let done = settle(api, &admin_tok, &r.json["apply"]).await;
|
||||||
|
assert_eq!(done["state"], "kept", "{done}");
|
||||||
|
let steps: Vec<String> = done["steps"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|s| {
|
||||||
|
format!(
|
||||||
|
"{}={}",
|
||||||
|
s["key"].as_str().unwrap(),
|
||||||
|
s["state"].as_str().unwrap()
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert!(
|
||||||
|
steps.contains(&"watch=done".to_owned()),
|
||||||
|
"watched through Caddy: {steps:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The preview answers through Caddy, with a certificate from the Domi CA.
|
||||||
|
let mut roots = rustls::RootCertStore::empty();
|
||||||
|
for der in ianitor_core::pki::chain_der(&root_pem).unwrap() {
|
||||||
|
roots
|
||||||
|
.add(rustls_pki_types::CertificateDer::from(der))
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let roots = Arc::new(roots);
|
||||||
|
let https_addr = local(https);
|
||||||
|
let resp = client::https(https_addr, &host, roots.clone(), &Req::get(&host, "/hello"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resp.status, 200);
|
||||||
|
assert_eq!(resp.header("x-robots-tag"), Some("noindex, nofollow"));
|
||||||
|
assert!(String::from_utf8_lossy(&resp.body).contains("preview-app"));
|
||||||
|
let r = call(
|
||||||
|
api,
|
||||||
|
&fabrica,
|
||||||
|
"GET",
|
||||||
|
&format!("/api/v1/previews/{host}"),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.json["preview"]["state"], "live", "{}", r.text);
|
||||||
|
|
||||||
|
// Closed on merge: Caddy stops serving it.
|
||||||
|
let r = call(
|
||||||
|
api,
|
||||||
|
&fabrica,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews/close",
|
||||||
|
Some(json!({"project": "shop", "branch": "fix-42"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(
|
||||||
|
settle(api, &admin_tok, &r.json["apply"]).await["state"],
|
||||||
|
"kept"
|
||||||
|
);
|
||||||
|
let gone = client::https(https_addr, &host, roots, &Req::get(&host, "/hello")).await;
|
||||||
|
assert!(
|
||||||
|
gone.as_ref()
|
||||||
|
.map_or(true, |r| r.status == 404 || r.status == 421),
|
||||||
|
"{:?}",
|
||||||
|
gone.map(|r| r.status)
|
||||||
|
);
|
||||||
|
let _ = tx.send(());
|
||||||
|
}
|
||||||
@@ -0,0 +1,570 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! A control-plane test environment on 127.0.0.1: an edge running in this process (with its
|
||||||
|
//! admin socket), the real `ianitor-control` binary as a child process (so a test can kill it
|
||||||
|
//! or make it abort at a crash point), a bare routes repository, test upstreams and a test CA.
|
||||||
|
//! The first API token comes from `ianitor-control token create`, as in production.
|
||||||
|
|
||||||
|
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use ianitor_core::compile::{self, CompileOptions};
|
||||||
|
use ianitor_core::{SourceFile, load};
|
||||||
|
use ianitor_testkit::more::{JsonResp, tcp_json, unix_json};
|
||||||
|
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
|
||||||
|
use ianitor_testkit::tls::TestCa;
|
||||||
|
use rustls::RootCertStore;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
pub const HOSTS: [&str; 7] = [
|
||||||
|
"a.test",
|
||||||
|
"b.test",
|
||||||
|
"c.test",
|
||||||
|
"d.test",
|
||||||
|
"e.test",
|
||||||
|
"f.test",
|
||||||
|
"share.test",
|
||||||
|
];
|
||||||
|
pub const SHARE_KEY: &str = "control-test-share-key-0123456789abcdef0123456789";
|
||||||
|
|
||||||
|
pub struct Edge {
|
||||||
|
stop: Option<tokio::sync::oneshot::Sender<()>>,
|
||||||
|
pub http: SocketAddr,
|
||||||
|
pub https: SocketAddr,
|
||||||
|
pub admin: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Edge {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(s) = self.stop.take() {
|
||||||
|
let _ = s.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Env {
|
||||||
|
pub dir: TempDir,
|
||||||
|
pub ca: TestCa,
|
||||||
|
pub edge: Option<Edge>,
|
||||||
|
pub control: Option<ChildGuard>,
|
||||||
|
pub api: SocketAddr,
|
||||||
|
pub token: String,
|
||||||
|
pub opts: CompileOptions,
|
||||||
|
pub watch_secs: u64,
|
||||||
|
pub remote: Option<String>,
|
||||||
|
log_n: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EnvSpec {
|
||||||
|
pub watch_secs: u64,
|
||||||
|
pub site: String,
|
||||||
|
pub remote: Option<String>,
|
||||||
|
/// Appended to control.toml (extra sections such as [pki]).
|
||||||
|
pub extra_config: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for EnvSpec {
|
||||||
|
fn default() -> Self {
|
||||||
|
EnvSpec {
|
||||||
|
watch_secs: 2,
|
||||||
|
site: String::new(),
|
||||||
|
remote: None,
|
||||||
|
extra_config: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn s(p: &Path) -> String {
|
||||||
|
p.to_string_lossy().into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Env {
|
||||||
|
pub async fn new(spec: EnvSpec) -> Env {
|
||||||
|
let dir = TempDir::new("ctl");
|
||||||
|
for d in [
|
||||||
|
"state",
|
||||||
|
"edge",
|
||||||
|
"caddy",
|
||||||
|
"certs",
|
||||||
|
"creds",
|
||||||
|
"logs",
|
||||||
|
"edge-state",
|
||||||
|
] {
|
||||||
|
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||||
|
}
|
||||||
|
let ca = TestCa::new("Ianitor Control Test CA");
|
||||||
|
for h in HOSTS {
|
||||||
|
let leaf = ca.issue(&[h]);
|
||||||
|
std::fs::write(dir.join(&format!("certs/{h}.crt")), leaf.cert_pem).unwrap();
|
||||||
|
std::fs::write(dir.join(&format!("certs/{h}.key")), leaf.key_pem).unwrap();
|
||||||
|
}
|
||||||
|
std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap();
|
||||||
|
let opts = CompileOptions {
|
||||||
|
http_listen: local(free_port()),
|
||||||
|
https_listen: local(free_port()),
|
||||||
|
cert_dir: dir.str("certs"),
|
||||||
|
state_dir: dir.str("edge-state"),
|
||||||
|
access_log: dir.str("logs/access.log"),
|
||||||
|
caddy_credentials_dir: dir.str("creds"),
|
||||||
|
caddy_admin: None,
|
||||||
|
caddy_admin_socket: None,
|
||||||
|
trusted_proxies: Vec::new(),
|
||||||
|
};
|
||||||
|
// Edge starts from an empty config; control brings it in line on its first start.
|
||||||
|
let empty = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
},
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.join("edge/edge.json"),
|
||||||
|
compile::edge(&empty, &opts).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.join("edge/share-revocations.json"),
|
||||||
|
"{\"epoch\":0,\"deny\":[]}",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let api = local(free_port());
|
||||||
|
let mut env = Env {
|
||||||
|
edge: None,
|
||||||
|
control: None,
|
||||||
|
api,
|
||||||
|
token: String::new(),
|
||||||
|
opts,
|
||||||
|
watch_secs: spec.watch_secs,
|
||||||
|
remote: spec.remote.clone(),
|
||||||
|
ca,
|
||||||
|
dir,
|
||||||
|
log_n: 0,
|
||||||
|
};
|
||||||
|
env.write_config(&spec);
|
||||||
|
env.start_edge();
|
||||||
|
// Seed the routes repository with the site file, then make the first token.
|
||||||
|
if !spec.site.is_empty() {
|
||||||
|
env.seed_site(&spec.site);
|
||||||
|
}
|
||||||
|
env.token = env.cli_token("test");
|
||||||
|
env
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_config(&self, spec: &EnvSpec) {
|
||||||
|
let d = |p: &str| s(&self.dir.join(p));
|
||||||
|
let remote = spec
|
||||||
|
.remote
|
||||||
|
.as_ref()
|
||||||
|
.map(|r| format!("remote = \"{r}\"\n"))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let text = format!(
|
||||||
|
r#"listen = "{api}"
|
||||||
|
state_dir = "{state}"
|
||||||
|
credentials_dir = "{creds}"
|
||||||
|
watch_secs = {watch}
|
||||||
|
watch_every_secs = 1
|
||||||
|
trial_margin_secs = 2
|
||||||
|
health_poll_secs = 1
|
||||||
|
|
||||||
|
[routes]
|
||||||
|
repo = "{repo}"
|
||||||
|
{remote}
|
||||||
|
[edge]
|
||||||
|
config = "{edge}/edge.json"
|
||||||
|
admin_socket = "{edge}/admin.sock"
|
||||||
|
share_revocations = "{edge}/share-revocations.json"
|
||||||
|
|
||||||
|
[caddy]
|
||||||
|
config = "{caddy}/caddy.json"
|
||||||
|
|
||||||
|
[compile]
|
||||||
|
http_listen = "{http}"
|
||||||
|
https_listen = "{https}"
|
||||||
|
cert_dir = "{certs}"
|
||||||
|
state_dir = "{edge_state}"
|
||||||
|
access_log = "{log}"
|
||||||
|
caddy_credentials_dir = "{creds}"
|
||||||
|
"#,
|
||||||
|
api = self.api,
|
||||||
|
state = d("state"),
|
||||||
|
creds = d("creds"),
|
||||||
|
watch = spec.watch_secs,
|
||||||
|
repo = d("routes.git"),
|
||||||
|
edge = d("edge"),
|
||||||
|
caddy = d("caddy"),
|
||||||
|
http = self.opts.http_listen,
|
||||||
|
https = self.opts.https_listen,
|
||||||
|
certs = d("certs"),
|
||||||
|
edge_state = d("edge-state"),
|
||||||
|
log = d("logs/access.log"),
|
||||||
|
) + &spec.extra_config;
|
||||||
|
std::fs::write(self.dir.join("control.toml"), text).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn config_path(&self) -> PathBuf {
|
||||||
|
self.dir.join("control.toml")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn repo(&self) -> PathBuf {
|
||||||
|
self.dir.join("routes.git")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_edge(&mut self) {
|
||||||
|
let opts = ianitor_edge::Options {
|
||||||
|
config: self.dir.join("edge/edge.json"),
|
||||||
|
admin_socket: Some(self.dir.join("edge/admin.sock")),
|
||||||
|
share_revocations: Some(self.dir.join("edge/share-revocations.json")),
|
||||||
|
credentials_dir: Some(self.dir.join("creds")),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let shared = ianitor_edge::prepare(&opts).expect("edge config");
|
||||||
|
let server = ianitor_edge::server(shared, &opts).expect("edge server");
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||||
|
std::thread::spawn(move || ianitor_edge::run_until(server, rx));
|
||||||
|
assert!(wait_for_port(
|
||||||
|
self.opts.https_listen,
|
||||||
|
Duration::from_secs(20)
|
||||||
|
));
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while !self.dir.join("edge/admin.sock").exists() && Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
self.edge = Some(Edge {
|
||||||
|
stop: Some(tx),
|
||||||
|
http: self.opts.http_listen,
|
||||||
|
https: self.opts.https_listen,
|
||||||
|
admin: self.dir.join("edge/admin.sock"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop the in-process edge (and wait until its listeners are gone).
|
||||||
|
pub fn stop_edge(&mut self) {
|
||||||
|
self.edge = None;
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(15);
|
||||||
|
while std::net::TcpStream::connect(self.opts.https_listen).is_ok()
|
||||||
|
&& Instant::now() < deadline
|
||||||
|
{
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn command(&self) -> Command {
|
||||||
|
let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control"));
|
||||||
|
c.env_remove("IANITOR_TEST_CRASH_AT");
|
||||||
|
c.env_remove("IANITOR_TEST_FAIL_WRITE");
|
||||||
|
c
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cli_token(&self, name: &str) -> String {
|
||||||
|
let out = self
|
||||||
|
.command()
|
||||||
|
.args(["token", "create", "--name", name, "--config"])
|
||||||
|
.arg(self.config_path())
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
out.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
let t = String::from_utf8_lossy(&out.stdout).trim().to_owned();
|
||||||
|
assert!(t.starts_with("ian_"), "{t}");
|
||||||
|
t
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put an `ianitor.toml` into a fresh repository (before control first starts).
|
||||||
|
fn seed_site(&self, site: &str) {
|
||||||
|
let work = self.dir.join("seed");
|
||||||
|
std::fs::create_dir_all(&work).unwrap();
|
||||||
|
let git = |args: &[&str], cwd: &Path| {
|
||||||
|
let o = Command::new("git")
|
||||||
|
.args([
|
||||||
|
"-c",
|
||||||
|
"user.name=test",
|
||||||
|
"-c",
|
||||||
|
"user.email=t@t",
|
||||||
|
"-c",
|
||||||
|
"init.defaultBranch=main",
|
||||||
|
])
|
||||||
|
.args(args)
|
||||||
|
.current_dir(cwd)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
o.status.success(),
|
||||||
|
"git {args:?}: {}",
|
||||||
|
String::from_utf8_lossy(&o.stderr)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
git(
|
||||||
|
&["init", "--bare", "--quiet", &s(&self.repo())],
|
||||||
|
&self.dir.join("."),
|
||||||
|
);
|
||||||
|
git(&["init", "--quiet"], &work);
|
||||||
|
std::fs::write(work.join("ianitor.toml"), site).unwrap();
|
||||||
|
git(&["add", "ianitor.toml"], &work);
|
||||||
|
git(&["commit", "--quiet", "-m", "Site settings"], &work);
|
||||||
|
git(
|
||||||
|
&["push", "--quiet", &s(&self.repo()), "HEAD:refs/heads/main"],
|
||||||
|
&work,
|
||||||
|
);
|
||||||
|
let _ = std::fs::remove_dir_all(&work);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn control_log(&self) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
for i in 0..=self.log_n {
|
||||||
|
out.push_str(
|
||||||
|
&std::fs::read_to_string(self.dir.join(&format!("logs/control-{i}.log")))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the control binary; with `crash_at`, it aborts when an apply reaches that stage.
|
||||||
|
pub fn start_control(&mut self, crash_at: Option<&str>) {
|
||||||
|
self.start_control_env(crash_at, &[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`Env::start_control`], with extra environment (fault injection).
|
||||||
|
pub fn start_control_env(&mut self, crash_at: Option<&str>, envs: &[(&str, &str)]) {
|
||||||
|
self.log_n += 1;
|
||||||
|
let log = std::fs::File::create(self.dir.join(&format!("logs/control-{}.log", self.log_n)))
|
||||||
|
.unwrap();
|
||||||
|
let mut c = self.command();
|
||||||
|
c.arg("--config").arg(self.config_path());
|
||||||
|
c.env("IANITOR_LOG", "debug");
|
||||||
|
if let Some(stage) = crash_at {
|
||||||
|
c.env("IANITOR_TEST_CRASH_AT", stage);
|
||||||
|
}
|
||||||
|
for (k, v) in envs {
|
||||||
|
c.env(k, v);
|
||||||
|
}
|
||||||
|
c.stdout(Stdio::from(log.try_clone().unwrap()))
|
||||||
|
.stderr(Stdio::from(log));
|
||||||
|
self.control = Some(ChildGuard(c.spawn().unwrap()));
|
||||||
|
if !wait_for_port(self.api, Duration::from_secs(30)) {
|
||||||
|
panic!("control did not start:\n{}", self.control_log());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kill_control(&mut self) {
|
||||||
|
self.control = None;
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
while std::net::TcpStream::connect(self.api).is_ok() && Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait for control to exit by itself (a crash point).
|
||||||
|
pub fn wait_control_exit(&mut self, timeout: Duration) -> Option<std::process::ExitStatus> {
|
||||||
|
let deadline = Instant::now() + timeout;
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
if let Some(c) = &mut self.control
|
||||||
|
&& let Some(st) = c.0.try_wait().unwrap()
|
||||||
|
{
|
||||||
|
self.control = None;
|
||||||
|
return Some(st);
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn call(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
|
||||||
|
let auth = format!("Bearer {}", self.token);
|
||||||
|
self.call_with(method, path, &[("Authorization", &auth)], body)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn call_with(
|
||||||
|
&self,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
headers: &[(&str, &str)],
|
||||||
|
body: Option<Value>,
|
||||||
|
) -> JsonResp {
|
||||||
|
tcp_json(self.api, method, path, headers, body.as_ref())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("{method} {path}: {e}\n{}", self.control_log()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait for an apply to end; returns its record.
|
||||||
|
pub async fn wait_apply(&self, id: &str) -> Value {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(90);
|
||||||
|
loop {
|
||||||
|
let r = self
|
||||||
|
.call("GET", &format!("/api/v1/applies/{id}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
let st = r.json["state"].as_str().unwrap_or("").to_owned();
|
||||||
|
if ["kept", "reverted", "failed", "needs_attention"].contains(&st.as_str()) {
|
||||||
|
return r.json;
|
||||||
|
}
|
||||||
|
if Instant::now() > deadline {
|
||||||
|
panic!("apply {id} still {st}:\n{}", self.control_log());
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Submit and wait.
|
||||||
|
pub async fn apply(&self, method: &str, path: &str, body: Option<Value>) -> Value {
|
||||||
|
let r = self.call(method, path, body).await;
|
||||||
|
assert_eq!(r.status, 202, "{method} {path}: {}", r.text);
|
||||||
|
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
|
||||||
|
self.wait_apply(&id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn add_host(&self, host: Value) -> Value {
|
||||||
|
self.apply("POST", "/api/v1/hosts", Some(json!({ "host": host })))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn edge_status(&self) -> Value {
|
||||||
|
let r = unix_json(&self.dir.join("edge/admin.sock"), "GET", "/v1/status", None)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
r.json
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn roots(&self) -> Arc<RootCertStore> {
|
||||||
|
self.ca.roots()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn git(&self, args: &[&str]) -> String {
|
||||||
|
let o = Command::new("git")
|
||||||
|
.env("GIT_DIR", self.repo())
|
||||||
|
.args(args)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
o.status.success(),
|
||||||
|
"git {args:?}: {}",
|
||||||
|
String::from_utf8_lossy(&o.stderr)
|
||||||
|
);
|
||||||
|
String::from_utf8_lossy(&o.stdout).trim().to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn head(&self) -> String {
|
||||||
|
self.git(&["rev-parse", "refs/heads/main"])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The routes files at the branch head.
|
||||||
|
pub fn head_files(&self) -> Vec<(String, String)> {
|
||||||
|
let list = self.git(&["ls-tree", "-r", "--name-only", "refs/heads/main"]);
|
||||||
|
list.lines()
|
||||||
|
.map(|p| {
|
||||||
|
(
|
||||||
|
p.to_owned(),
|
||||||
|
self.git(&["show", &format!("refs/heads/main:{p}")]) + "\n",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What edge.json and caddy.json must hold for the branch head.
|
||||||
|
pub fn expected_configs(&self) -> (String, String) {
|
||||||
|
let files = self.head_files();
|
||||||
|
let site = files
|
||||||
|
.iter()
|
||||||
|
.find(|(p, _)| p == "ianitor.toml")
|
||||||
|
.map(|(_, c)| c.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let hosts: Vec<SourceFile> = files
|
||||||
|
.iter()
|
||||||
|
.filter(|(p, _)| p != "ianitor.toml")
|
||||||
|
.map(|(p, c)| SourceFile {
|
||||||
|
name: p,
|
||||||
|
contents: c,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let model = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: &site,
|
||||||
|
},
|
||||||
|
&hosts,
|
||||||
|
)
|
||||||
|
.expect("head validates");
|
||||||
|
(
|
||||||
|
compile::edge(&model, &self.opts).unwrap(),
|
||||||
|
compile::caddy(&model, &self.opts).unwrap(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn file(&self, p: &str) -> String {
|
||||||
|
std::fs::read_to_string(self.dir.join(p)).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The repository, both files and edge agree, and nothing is left half done.
|
||||||
|
pub async fn assert_consistent(&self) {
|
||||||
|
let (edge_text, caddy_text) = self.expected_configs();
|
||||||
|
assert_eq!(
|
||||||
|
self.file("edge/edge.json"),
|
||||||
|
edge_text,
|
||||||
|
"edge.json matches the branch head"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
self.file("caddy/caddy.json"),
|
||||||
|
caddy_text,
|
||||||
|
"caddy.json matches the branch head"
|
||||||
|
);
|
||||||
|
let st = self.edge_status().await;
|
||||||
|
assert!(st["trial"].is_null(), "no trial left running: {st}");
|
||||||
|
assert_eq!(
|
||||||
|
st["config_sha256"],
|
||||||
|
sha256(&edge_text),
|
||||||
|
"edge runs edge.json"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!self.dir.join("edge/edge.json.trial").exists(),
|
||||||
|
"no trial file left"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!self.dir.join("caddy/caddy.json.trial").exists(),
|
||||||
|
"no Caddy trial file left"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!self.dir.join("state/journal.json").exists(),
|
||||||
|
"no journal left"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sha256(text: &str) -> String {
|
||||||
|
ring::digest::digest(&ring::digest::SHA256, text.as_bytes())
|
||||||
|
.as_ref()
|
||||||
|
.iter()
|
||||||
|
.map(|b| format!("{b:02x}"))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A host body for the API.
|
||||||
|
pub fn host(name: &str, upstream: &str, health: bool) -> Value {
|
||||||
|
let mut h = json!({
|
||||||
|
"hostname": name,
|
||||||
|
"upstreams": [upstream],
|
||||||
|
"tls": "domi",
|
||||||
|
"auth": "none",
|
||||||
|
"websockets": true,
|
||||||
|
"share_links": false,
|
||||||
|
"access_log": "off",
|
||||||
|
});
|
||||||
|
if health {
|
||||||
|
h["health_check"] = json!({ "path": "/healthz", "interval_secs": 1 });
|
||||||
|
}
|
||||||
|
h
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,769 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! The Domi CA through control (ROADMAP §6 phase 3, tests first): the first intermediate is
|
||||||
|
//! signed offline from control's CSR and installed; `tls = "domi"` hosts then get server
|
||||||
|
//! certificates that chain to the root; device certificates need the match code; the install
|
||||||
|
//! file works once; revocation takes the device off the allow list; no root key file is ever
|
||||||
|
//! in the state directory, and control refuses to start with one there.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux; run it in WSL2",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::common::{Env, EnvSpec};
|
||||||
|
use ianitor_core::pki;
|
||||||
|
use ianitor_testkit::client::{self, Req};
|
||||||
|
use ianitor_testkit::upstream::Echo;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
const PASSWORD: &str = "intermediate-test-password-123";
|
||||||
|
|
||||||
|
/// Whether an allow list names any device (the placeholder that keeps it from being
|
||||||
|
/// empty is not one).
|
||||||
|
fn lists_a_device(allow: &str) -> bool {
|
||||||
|
pki::chain_der(allow)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.iter()
|
||||||
|
.any(|d| pki::inspect_der(d).is_ok_and(|i| i.subject_cn != pki::NO_DEVICE_CN))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> i64 {
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_secs() as i64
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The offline side: a root that lives only in this test's memory (and its cert file).
|
||||||
|
struct Offline {
|
||||||
|
root_pem: String,
|
||||||
|
root_key: pki::KeyPair,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn env_with_pki() -> (Env, Offline) {
|
||||||
|
let (root_pem, root_key) = pki::create_root(now()).unwrap();
|
||||||
|
let env = env_with_root(&root_pem).await;
|
||||||
|
(env, Offline { root_pem, root_key })
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn env_with_root(root_pem: &str) -> Env {
|
||||||
|
// Only the root certificate goes next to control; the key stays in this test.
|
||||||
|
let extra = |dir: &Path| {
|
||||||
|
format!(
|
||||||
|
"\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n",
|
||||||
|
dir.join("offline-root.crt").display()
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let mut env = Env::new(EnvSpec::default()).await;
|
||||||
|
std::fs::write(env.dir.join("offline-root.crt"), root_pem).unwrap();
|
||||||
|
std::fs::write(env.dir.join("creds/pki-password"), PASSWORD).unwrap();
|
||||||
|
let text = std::fs::read_to_string(env.config_path()).unwrap() + &extra(&env.dir.join("."));
|
||||||
|
std::fs::write(env.config_path(), text).unwrap();
|
||||||
|
env.start_control(None);
|
||||||
|
env
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn wait_request(env: &Env, id: &str, want: &str) -> Value {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(20);
|
||||||
|
loop {
|
||||||
|
let r = env
|
||||||
|
.call("GET", &format!("/api/v1/pki-requests/{id}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
if r.json["state"] == want {
|
||||||
|
return r.json;
|
||||||
|
}
|
||||||
|
if Instant::now() > deadline {
|
||||||
|
panic!(
|
||||||
|
"request {id} is {} not {want}\n{}",
|
||||||
|
r.json["state"],
|
||||||
|
env.control_log()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cli(env: &Env, args: &[&str]) -> std::process::Output {
|
||||||
|
env.command()
|
||||||
|
.args(args)
|
||||||
|
.arg("--config")
|
||||||
|
.arg(env.config_path())
|
||||||
|
.output()
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renew (first intermediate), sign offline, install with the CLI.
|
||||||
|
async fn install_intermediate(env: &Env, off: &Offline) -> Value {
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/certs/intermediate/renewal",
|
||||||
|
Some(json!({})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
||||||
|
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
|
||||||
|
// The code the UI shows is the one the offline signer computes from the CSR.
|
||||||
|
assert_eq!(
|
||||||
|
r.json["match_code"].as_str().unwrap(),
|
||||||
|
pki::match_code(&pki::csr_der(&csr).unwrap())
|
||||||
|
);
|
||||||
|
let r2 = env
|
||||||
|
.call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
r2.status,
|
||||||
|
200,
|
||||||
|
"{}
|
||||||
|
{}
|
||||||
|
{}",
|
||||||
|
r.text,
|
||||||
|
r2.text,
|
||||||
|
env.control_log()
|
||||||
|
);
|
||||||
|
assert_eq!(r2.text, csr);
|
||||||
|
let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
|
||||||
|
let f = env.dir.join("signed.crt");
|
||||||
|
std::fs::write(&f, &signed).unwrap();
|
||||||
|
let out = cli(env, &["pki", "install", f.to_str().unwrap()]);
|
||||||
|
assert!(
|
||||||
|
out.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
wait_request(env, &rid, "approved").await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn first_intermediate_from_an_offline_signature_then_domi_hosts_chain_to_the_root() {
|
||||||
|
let (env, off) = env_with_pki().await;
|
||||||
|
let ov = env.call("GET", "/api/v1/overview", None).await;
|
||||||
|
assert_eq!(ov.json["intermediate"]["state"], "missing", "{}", ov.text);
|
||||||
|
|
||||||
|
// Before an intermediate exists a domi host cannot get a certificate.
|
||||||
|
let echo = Echo::start("domi").await;
|
||||||
|
let host = json!({"host": {"hostname": "fresh.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}});
|
||||||
|
let rec = env.apply("POST", "/api/v1/hosts", Some(host.clone())).await;
|
||||||
|
assert_eq!(rec["state"], "failed", "{rec}");
|
||||||
|
assert_eq!(rec["reason"]["code"], "pki.no_intermediate", "{rec}");
|
||||||
|
|
||||||
|
install_intermediate(&env, &off).await;
|
||||||
|
let ov = env.call("GET", "/api/v1/overview", None).await;
|
||||||
|
assert_eq!(ov.json["intermediate"]["state"], "ok", "{}", ov.text);
|
||||||
|
assert!(ov.json["intermediate"]["days_left"].as_i64().unwrap() >= 364);
|
||||||
|
|
||||||
|
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
|
||||||
|
assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log());
|
||||||
|
// The served certificate chains to the Domi root (only the root is trusted here).
|
||||||
|
let roots = ianitor_testkit::tls::roots_from_pem(&off.root_pem);
|
||||||
|
let edge = env.edge.as_ref().unwrap();
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"fresh.test",
|
||||||
|
roots,
|
||||||
|
&Req::get("fresh.test", "/"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
let crt = std::fs::read_to_string(env.dir.join("certs/fresh.test.crt")).unwrap();
|
||||||
|
let info = pki::inspect(&crt).unwrap();
|
||||||
|
assert_eq!(info.dns_names, vec!["fresh.test".to_owned()]);
|
||||||
|
assert_eq!(
|
||||||
|
(info.not_after - now()) / 86_400,
|
||||||
|
i64::from(pki::SERVER_DAYS) - 1
|
||||||
|
);
|
||||||
|
|
||||||
|
// No root key anywhere control writes. (The start of a P-256 PKCS#8 body is the same
|
||||||
|
// for every key, so the unique end is compared.)
|
||||||
|
let key_pem = off.root_key.serialize_pem();
|
||||||
|
let body: String = key_pem
|
||||||
|
.lines()
|
||||||
|
.filter(|l| !l.starts_with("-----"))
|
||||||
|
.collect();
|
||||||
|
for d in ["state", "certs", "edge", "caddy", "edge-state"] {
|
||||||
|
for f in walk(&env.dir.join(d)) {
|
||||||
|
let bytes = std::fs::read(&f).unwrap();
|
||||||
|
let text = String::from_utf8_lossy(&bytes);
|
||||||
|
assert!(
|
||||||
|
!text.contains(&body[body.len() - 40..]),
|
||||||
|
"root key material in {}",
|
||||||
|
f.display()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!contains(&bytes, &off.root_key.serialize_der()),
|
||||||
|
"root key DER in {}",
|
||||||
|
f.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The intermediate key is only stored encrypted.
|
||||||
|
let k = std::fs::read_to_string(env.dir.join("state/pki/intermediate.key")).unwrap();
|
||||||
|
assert!(k.contains(concat!("IANITOR ENCRYPTED ", "PRIVATE KEY")));
|
||||||
|
assert!(!k.contains(concat!("BEGIN ", "PRIVATE KEY")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_wrong_certificate_is_not_installed() {
|
||||||
|
let (env, off) = env_with_pki().await;
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/certs/intermediate/renewal",
|
||||||
|
Some(json!({})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
||||||
|
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
|
||||||
|
// Signed by another root.
|
||||||
|
let (other, other_key) = pki::create_root(now()).unwrap();
|
||||||
|
let wrong = pki::sign_intermediate(&other, &other_key, &csr, now()).unwrap();
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"PUT",
|
||||||
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||||
|
Some(json!({"certificate_pem": wrong})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "pki.not_our_root");
|
||||||
|
// For another key.
|
||||||
|
let k = pki::generate_key().unwrap();
|
||||||
|
let other_csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
|
||||||
|
let wrong =
|
||||||
|
pki::sign_intermediate(&off.root_pem, &off.root_key, &other_csr, now()).unwrap();
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"PUT",
|
||||||
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||||
|
Some(json!({"certificate_pem": wrong})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "pki.wrong_key");
|
||||||
|
// A leaf is not an intermediate.
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"PUT",
|
||||||
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||||
|
Some(json!({"certificate_pem": "garbage"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
let st = env
|
||||||
|
.call("GET", &format!("/api/v1/pki-requests/{rid}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(st.json["state"], "waiting");
|
||||||
|
// The right one through the API works too.
|
||||||
|
let good = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"PUT",
|
||||||
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||||
|
Some(json!({"certificate_pem": good})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
assert_eq!(r.json["state"], "approved");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn device_certificate_needs_the_match_code_and_installs_once() {
|
||||||
|
let (env, off) = env_with_pki().await;
|
||||||
|
install_intermediate(&env, &off).await;
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/certs/devices",
|
||||||
|
Some(json!({"name": "Mark's phone", "kind": "phone"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
||||||
|
let code = r.json["match_code"].as_str().unwrap().to_owned();
|
||||||
|
assert_eq!(code.len(), 8, "{code}");
|
||||||
|
// The same name again while it waits: refused.
|
||||||
|
let again = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/certs/devices",
|
||||||
|
Some(json!({"name": "mark's PHONE", "kind": "phone"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(again.status, 409, "{}", again.text);
|
||||||
|
assert_eq!(again.json["error"]["code"], "pki.device_name_taken");
|
||||||
|
|
||||||
|
// A wrong code does nothing.
|
||||||
|
let wrong = if code.starts_with('0') {
|
||||||
|
"11 11 11"
|
||||||
|
} else {
|
||||||
|
"00 00 00"
|
||||||
|
};
|
||||||
|
let out = cli(&env, &["pki", "approve", wrong]);
|
||||||
|
assert!(!out.status.success());
|
||||||
|
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||||
|
let st = env
|
||||||
|
.call("GET", &format!("/api/v1/pki-requests/{rid}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(st.json["state"], "waiting");
|
||||||
|
|
||||||
|
let out = cli(&env, &["pki", "approve", &code]);
|
||||||
|
assert!(
|
||||||
|
out.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&out.stderr)
|
||||||
|
);
|
||||||
|
let done = wait_request(&env, &rid, "approved").await;
|
||||||
|
let did = done["device_id"].as_str().unwrap().to_owned();
|
||||||
|
|
||||||
|
let certs = env.call("GET", "/api/v1/certs", None).await;
|
||||||
|
assert_eq!(certs.status, 200, "{}", certs.text);
|
||||||
|
assert_eq!(certs.json["root"]["offline"], true);
|
||||||
|
let dev = certs.json["devices"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|d| d["id"] == did.as_str())
|
||||||
|
.unwrap()
|
||||||
|
.clone();
|
||||||
|
assert_eq!(dev["state"], "valid");
|
||||||
|
assert_eq!(dev["name"], "Mark's phone");
|
||||||
|
|
||||||
|
// The allow list both engines read has it.
|
||||||
|
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
|
||||||
|
assert!(lists_a_device(&allow));
|
||||||
|
|
||||||
|
// One-time install file.
|
||||||
|
let b = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
&format!("/api/v1/certs/devices/{did}/bundle"),
|
||||||
|
Some(json!({"format": "qr"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(b.status, 200, "{}", b.text);
|
||||||
|
let url = b.json["download_url"].as_str().unwrap().to_owned();
|
||||||
|
let password = b.json["one_time_password"].as_str().unwrap().to_owned();
|
||||||
|
assert!(b.json["qr_svg"].as_str().unwrap().starts_with("<?xml"));
|
||||||
|
let path = url
|
||||||
|
.split_once("/api/v1/")
|
||||||
|
.map(|(_, p)| format!("/api/v1/{p}"))
|
||||||
|
.unwrap();
|
||||||
|
// Opening the link (GET, as a link preview or prefetcher would) shows a page and
|
||||||
|
// uses nothing up; its button posts.
|
||||||
|
for _ in 0..2 {
|
||||||
|
let g = env.call_with("GET", &path, &[], None).await;
|
||||||
|
assert_eq!(g.status, 200, "{}", g.text);
|
||||||
|
assert!(g.text.contains("<form method=\"post\">"), "{}", g.text);
|
||||||
|
assert!(g.text.contains("Mark's phone"), "{}", g.text);
|
||||||
|
}
|
||||||
|
// No token needed for the download itself (the link is the secret) ...
|
||||||
|
let d = env.call_with("POST", &path, &[], None).await;
|
||||||
|
assert_eq!(d.status, 200, "{}", d.text);
|
||||||
|
assert_eq!(d.header("content-type"), Some("application/x-pkcs12"));
|
||||||
|
let ks = p12_keystore::KeyStore::from_pkcs12(
|
||||||
|
&d.body,
|
||||||
|
&password,
|
||||||
|
p12_keystore::Pkcs12ImportPolicy::Strict,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let (_, chain) = ks.private_key_chain().unwrap();
|
||||||
|
assert_eq!(chain.certs().len(), 3, "leaf, intermediate, root");
|
||||||
|
// ... and it works only once.
|
||||||
|
let d = env.call_with("POST", &path, &[], None).await;
|
||||||
|
assert_eq!(d.status, 410, "{}", d.text);
|
||||||
|
assert_eq!(d.json["error"]["code"], "pki.bundle_used");
|
||||||
|
let g = env.call_with("GET", &path, &[], None).await;
|
||||||
|
assert_eq!(g.status, 410, "{}", g.text);
|
||||||
|
|
||||||
|
// Revoke: off the allow list, no new install file.
|
||||||
|
let r = env
|
||||||
|
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 204, "{}", r.text);
|
||||||
|
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
|
||||||
|
assert!(!lists_a_device(&allow), "{allow}");
|
||||||
|
assert!(
|
||||||
|
allow.contains("BEGIN CERTIFICATE"),
|
||||||
|
"never empty (Caddy refuses that)"
|
||||||
|
);
|
||||||
|
let b = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
&format!("/api/v1/certs/devices/{did}/bundle"),
|
||||||
|
Some(json!({"format": "p12"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(b.status, 409, "{}", b.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn control_refuses_to_start_with_a_root_key_in_its_state_dir() {
|
||||||
|
let (mut env, off) = env_with_pki().await;
|
||||||
|
env.kill_control();
|
||||||
|
std::fs::write(env.dir.join("state/root.key"), off.root_key.serialize_pem()).unwrap();
|
||||||
|
// A control that does not refuse would serve forever: give it 20 s, then kill it.
|
||||||
|
let mut child = env
|
||||||
|
.command()
|
||||||
|
.arg("--config")
|
||||||
|
.arg(env.config_path())
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(20);
|
||||||
|
let status = loop {
|
||||||
|
if let Some(s) = child.try_wait().unwrap() {
|
||||||
|
break Some(s);
|
||||||
|
}
|
||||||
|
if Instant::now() > deadline {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
break None;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
status.is_some_and(|s| !s.success()),
|
||||||
|
"control started with a root key in its state dir"
|
||||||
|
);
|
||||||
|
let mut err = String::new();
|
||||||
|
std::io::Read::read_to_string(&mut child.stderr.take().unwrap(), &mut err).unwrap();
|
||||||
|
assert!(err.contains("root"), "{err}");
|
||||||
|
// And the message never prints the key.
|
||||||
|
assert!(!err.contains("PRIVATE KEY"), "{err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The accepted manual step (Mark, 2026-11-07, Q6): the offline machine runs openssl.
|
||||||
|
/// A root made with openssl signs control's CSR with the extensions file control serves,
|
||||||
|
/// and control installs the result.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn an_intermediate_signed_with_openssl_is_installed() {
|
||||||
|
let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let off = ianitor_testkit::proc::TempDir::new("openssl-root");
|
||||||
|
let run = |args: &[&str]| {
|
||||||
|
let o = std::process::Command::new(&openssl)
|
||||||
|
.args(args)
|
||||||
|
.current_dir(off.join("."))
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
o.status.success(),
|
||||||
|
"openssl {args:?}: {}",
|
||||||
|
String::from_utf8_lossy(&o.stderr)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
run(&[
|
||||||
|
"req",
|
||||||
|
"-x509",
|
||||||
|
"-new",
|
||||||
|
"-newkey",
|
||||||
|
"ec",
|
||||||
|
"-pkeyopt",
|
||||||
|
"ec_paramgen_curve:P-256",
|
||||||
|
"-nodes",
|
||||||
|
"-keyout",
|
||||||
|
"domi-root.key",
|
||||||
|
"-out",
|
||||||
|
"domi-root.crt",
|
||||||
|
"-days",
|
||||||
|
"3653",
|
||||||
|
"-subj",
|
||||||
|
"/CN=Domi PKI Root/O=Fabrica Domi",
|
||||||
|
"-addext",
|
||||||
|
"basicConstraints=critical,CA:TRUE,pathlen:1",
|
||||||
|
"-addext",
|
||||||
|
"keyUsage=critical,keyCertSign,cRLSign",
|
||||||
|
]);
|
||||||
|
let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap();
|
||||||
|
let env = env_with_root(&root_pem).await;
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/certs/intermediate/renewal",
|
||||||
|
Some(json!({})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
||||||
|
let base = r.json["file_base"].as_str().unwrap().to_owned();
|
||||||
|
let cmd = r.json["approve_command"].as_str().unwrap().to_owned();
|
||||||
|
assert!(cmd.starts_with("openssl x509 -req"), "{cmd}");
|
||||||
|
std::fs::write(
|
||||||
|
off.join(&format!("{base}.csr")),
|
||||||
|
r.json["csr_pem"].as_str().unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let ext = env
|
||||||
|
.call("GET", &format!("/api/v1/pki-requests/{rid}/ext"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(ext.status, 200, "{}", ext.text);
|
||||||
|
std::fs::write(off.join(&format!("{base}.ext")), &ext.text).unwrap();
|
||||||
|
// Exactly the command control shows.
|
||||||
|
let args: Vec<&str> = cmd.split_whitespace().skip(1).collect();
|
||||||
|
run(&args);
|
||||||
|
let signed = std::fs::read_to_string(off.join(&format!("{base}.crt"))).unwrap();
|
||||||
|
let info = pki::inspect(&signed).unwrap();
|
||||||
|
assert_eq!(info.path_len, Some(0));
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"PUT",
|
||||||
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||||
|
Some(json!({"certificate_pem": signed})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
assert_eq!(r.json["state"], "approved");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk(dir: &Path) -> Vec<std::path::PathBuf> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut stack = vec![dir.to_path_buf()];
|
||||||
|
while let Some(d) = stack.pop() {
|
||||||
|
let Ok(rd) = std::fs::read_dir(&d) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for e in rd.flatten() {
|
||||||
|
let p = e.path();
|
||||||
|
if p.is_dir() {
|
||||||
|
stack.push(p);
|
||||||
|
} else if p.is_file() {
|
||||||
|
out.push(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
||||||
|
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC: the openssl step can produce intermediates that are CA + pathlen 0 but cannot
|
||||||
|
/// issue what control issues. Control installs them and reissues every Domi host.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn qc_install_refuses_intermediates_that_cannot_issue() {
|
||||||
|
let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let off = ianitor_testkit::proc::TempDir::new("qc-openssl-root");
|
||||||
|
let run = |args: &[&str]| {
|
||||||
|
let o = std::process::Command::new(&openssl)
|
||||||
|
.args(args)
|
||||||
|
.current_dir(off.join("."))
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
o.status.success(),
|
||||||
|
"openssl {args:?}: {}",
|
||||||
|
String::from_utf8_lossy(&o.stderr)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
run(&[
|
||||||
|
"req",
|
||||||
|
"-x509",
|
||||||
|
"-new",
|
||||||
|
"-newkey",
|
||||||
|
"ec",
|
||||||
|
"-pkeyopt",
|
||||||
|
"ec_paramgen_curve:P-256",
|
||||||
|
"-nodes",
|
||||||
|
"-keyout",
|
||||||
|
"domi-root.key",
|
||||||
|
"-out",
|
||||||
|
"domi-root.crt",
|
||||||
|
"-days",
|
||||||
|
"3653",
|
||||||
|
"-subj",
|
||||||
|
"/CN=Domi PKI Root/O=Fabrica Domi",
|
||||||
|
"-addext",
|
||||||
|
"basicConstraints=critical,CA:TRUE,pathlen:1",
|
||||||
|
"-addext",
|
||||||
|
"keyUsage=critical,keyCertSign,cRLSign",
|
||||||
|
]);
|
||||||
|
let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap();
|
||||||
|
let env = env_with_root(&root_pem).await;
|
||||||
|
let good = "basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\n";
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
"keyUsage without keyCertSign",
|
||||||
|
"basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, digitalSignature\n",
|
||||||
|
"365",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"EKU serverAuth only (devices cannot chain)",
|
||||||
|
"basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\nextendedKeyUsage = serverAuth\n",
|
||||||
|
"365",
|
||||||
|
),
|
||||||
|
("valid past the root (-days 4000)", good, "4000"),
|
||||||
|
];
|
||||||
|
let mut accepted = Vec::new();
|
||||||
|
for (label, ext, days) in cases {
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/certs/intermediate/renewal",
|
||||||
|
Some(json!({})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
||||||
|
std::fs::write(off.join("q.csr"), r.json["csr_pem"].as_str().unwrap()).unwrap();
|
||||||
|
std::fs::write(off.join("q.ext"), ext).unwrap();
|
||||||
|
run(&[
|
||||||
|
"x509",
|
||||||
|
"-req",
|
||||||
|
"-in",
|
||||||
|
"q.csr",
|
||||||
|
"-CA",
|
||||||
|
"domi-root.crt",
|
||||||
|
"-CAkey",
|
||||||
|
"domi-root.key",
|
||||||
|
"-days",
|
||||||
|
days,
|
||||||
|
"-sha256",
|
||||||
|
"-extfile",
|
||||||
|
"q.ext",
|
||||||
|
"-out",
|
||||||
|
"q.crt",
|
||||||
|
]);
|
||||||
|
let signed = std::fs::read_to_string(off.join("q.crt")).unwrap();
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"PUT",
|
||||||
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
||||||
|
Some(json!({"certificate_pem": signed})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
eprintln!("QC {label}: {} {}", r.status, r.json["state"]);
|
||||||
|
if r.status == 200 {
|
||||||
|
accepted.push(label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
accepted.is_empty(),
|
||||||
|
"control installed unusable intermediates: {accepted:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC: the root key name that `ianitor-control ca init` and docs/pki.md's openssl
|
||||||
|
/// command write is `domi-root.key`.
|
||||||
|
#[test]
|
||||||
|
fn qc_root_key_check_finds_the_names_ianitor_itself_uses() {
|
||||||
|
let d = ianitor_testkit::proc::TempDir::new("qc-rootkey");
|
||||||
|
let mut missed = Vec::new();
|
||||||
|
for name in [
|
||||||
|
"domi-root.key",
|
||||||
|
"offline/domi-root.key",
|
||||||
|
"Domi_Root_CA.pem",
|
||||||
|
"ca.key",
|
||||||
|
] {
|
||||||
|
let p = d.join(name);
|
||||||
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
&p,
|
||||||
|
// (Split so that this file does not match the pre-commit hook itself.)
|
||||||
|
concat!(
|
||||||
|
"-----BEGIN ",
|
||||||
|
"PRIVATE KEY-----\nx\n-----END ",
|
||||||
|
"PRIVATE KEY-----\n"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
if ianitor_control::pki::root_key_files(&d.join(".")).is_empty() {
|
||||||
|
missed.push(name);
|
||||||
|
}
|
||||||
|
std::fs::remove_file(&p).unwrap();
|
||||||
|
}
|
||||||
|
assert!(missed.is_empty(), "root_key_files missed: {missed:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC M2: a revocation that cannot be written (or not told to edge) must not answer 204 and
|
||||||
|
/// be forgotten. It answers an error, the certificates screen says so, and once the disk
|
||||||
|
/// works again (here: a restart without the fault) the allow list catches up; a repeated
|
||||||
|
/// DELETE nudges again.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_revocation_that_cannot_be_written_is_an_error_and_catches_up() {
|
||||||
|
let (mut env, off) = env_with_pki().await;
|
||||||
|
install_intermediate(&env, &off).await;
|
||||||
|
let r = env
|
||||||
|
.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/certs/devices",
|
||||||
|
Some(json!({"name": "tablet", "kind": "phone"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
||||||
|
let code = r.json["match_code"].as_str().unwrap().to_owned();
|
||||||
|
assert!(cli(&env, &["pki", "approve", &code]).status.success());
|
||||||
|
let done = wait_request(&env, &rid, "approved").await;
|
||||||
|
let did = done["device_id"].as_str().unwrap().to_owned();
|
||||||
|
let allow_file = env.dir.join("certs/domi-devices.pem");
|
||||||
|
let on_list = || lists_a_device(&std::fs::read_to_string(&allow_file).unwrap_or_default());
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
while !on_list() {
|
||||||
|
assert!(
|
||||||
|
Instant::now() < deadline,
|
||||||
|
"the device never reached the allow list"
|
||||||
|
);
|
||||||
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||||
|
}
|
||||||
|
// From now on the allow list cannot be written.
|
||||||
|
env.kill_control();
|
||||||
|
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "domi-devices.pem")]);
|
||||||
|
let d = env
|
||||||
|
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(d.status, 503, "{}", d.text);
|
||||||
|
assert_eq!(
|
||||||
|
d.json["error"]["code"], "pki.devices_unwritten",
|
||||||
|
"{}",
|
||||||
|
d.text
|
||||||
|
);
|
||||||
|
// The certificates screen keeps saying so; the device is still on the list.
|
||||||
|
let c = env.call("GET", "/api/v1/certs", None).await;
|
||||||
|
assert_eq!(
|
||||||
|
c.json["devices_problem"]["code"], "pki.devices_unwritten",
|
||||||
|
"{}",
|
||||||
|
c.text
|
||||||
|
);
|
||||||
|
assert!(on_list());
|
||||||
|
// The disk works again: the list catches up by itself, without another Revoke.
|
||||||
|
env.kill_control();
|
||||||
|
env.start_control(None);
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
while on_list() {
|
||||||
|
assert!(Instant::now() < deadline, "the revocation never caught up");
|
||||||
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||||
|
}
|
||||||
|
// A repeated Revoke is fine and nudges the engine again.
|
||||||
|
let d = env
|
||||||
|
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(d.status, 204, "{}", d.text);
|
||||||
|
let c = env.call("GET", "/api/v1/certs", None).await;
|
||||||
|
assert!(c.json["devices_problem"].is_null(), "{}", c.text);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,539 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Branch previews for Fabrica (T4, tests first). `POST /api/v1/previews {project, branch,
|
||||||
|
//! upstream, ttl}` gives the branch the host `<branch>--<project>.<preview domain>`; a token
|
||||||
|
//! scoped to previews may do that and nothing else. These tests run control in this process
|
||||||
|
//! without an edge (applies are kept at once), so they run on Windows too; the end-to-end
|
||||||
|
//! runs through Pingora and Caddy are in tests/diff and scripts/preview-smoke.*.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use ianitor_control::Config;
|
||||||
|
use ianitor_control::tokens::{Scope, Tokens};
|
||||||
|
use ianitor_testkit::more::{JsonResp, tcp_json};
|
||||||
|
use ianitor_testkit::proc::{TempDir, free_port, local, wait_for_port};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
const DOMAIN: &str = "pv.example.test";
|
||||||
|
|
||||||
|
struct Ctl {
|
||||||
|
_dir: TempDir,
|
||||||
|
api: SocketAddr,
|
||||||
|
admin: String,
|
||||||
|
preview: String,
|
||||||
|
stop: Option<tokio::sync::oneshot::Sender<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Ctl {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(s) = self.stop.take() {
|
||||||
|
let _ = s.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn s(p: &std::path::Path) -> String {
|
||||||
|
p.to_string_lossy().replace('\\', "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ctl {
|
||||||
|
async fn start(extra: &str) -> Ctl {
|
||||||
|
let dir = TempDir::new("pv");
|
||||||
|
for d in ["state", "edge", "caddy", "certs", "creds", "edge-state"] {
|
||||||
|
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||||
|
}
|
||||||
|
let api = local(free_port());
|
||||||
|
let text = format!(
|
||||||
|
r#"listen = "{api}"
|
||||||
|
state_dir = "{state}"
|
||||||
|
credentials_dir = "{creds}"
|
||||||
|
|
||||||
|
[routes]
|
||||||
|
repo = "{repo}"
|
||||||
|
|
||||||
|
[edge]
|
||||||
|
config = "{edge}/edge.json"
|
||||||
|
share_revocations = "{edge}/share-revocations.json"
|
||||||
|
|
||||||
|
[caddy]
|
||||||
|
config = "{caddy}/caddy.json"
|
||||||
|
|
||||||
|
[compile]
|
||||||
|
http_listen = "127.0.0.1:{http}"
|
||||||
|
https_listen = "127.0.0.1:{https}"
|
||||||
|
cert_dir = "{certs}"
|
||||||
|
state_dir = "{edge_state}"
|
||||||
|
access_log = "{edge_state}/access.log"
|
||||||
|
caddy_credentials_dir = "{creds}"
|
||||||
|
|
||||||
|
[previews]
|
||||||
|
domain = "{DOMAIN}"
|
||||||
|
tls = "letsencrypt"
|
||||||
|
upstreams = ["10.0.0.0/8", "127.0.0.1:20000-29999", "app.internal"]
|
||||||
|
min_ttl_secs = 1
|
||||||
|
sweep_secs = 1
|
||||||
|
{extra}
|
||||||
|
"#,
|
||||||
|
state = s(&dir.join("state")),
|
||||||
|
creds = s(&dir.join("creds")),
|
||||||
|
repo = s(&dir.join("routes.git")),
|
||||||
|
edge = s(&dir.join("edge")),
|
||||||
|
caddy = s(&dir.join("caddy")),
|
||||||
|
certs = s(&dir.join("certs")),
|
||||||
|
edge_state = s(&dir.join("edge-state")),
|
||||||
|
http = free_port(),
|
||||||
|
https = free_port(),
|
||||||
|
);
|
||||||
|
let path = dir.join("control.toml");
|
||||||
|
std::fs::write(&path, text).unwrap();
|
||||||
|
let cfg = Config::load(&path).unwrap();
|
||||||
|
let tokens = Tokens::new(&dir.join("state"));
|
||||||
|
let (_, admin) = tokens.create("admin", None, Scope::Full).unwrap();
|
||||||
|
let (_, preview) = tokens
|
||||||
|
.create("fabrica previews", None, Scope::Previews)
|
||||||
|
.unwrap();
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = ianitor_control::serve(cfg, async {
|
||||||
|
let _ = rx.await;
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
panic!("control stopped: {e}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
wait_for_port(api, Duration::from_secs(20)),
|
||||||
|
"control did not listen"
|
||||||
|
);
|
||||||
|
Ctl {
|
||||||
|
_dir: dir,
|
||||||
|
api,
|
||||||
|
admin,
|
||||||
|
preview,
|
||||||
|
stop: Some(tx),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn call(&self, token: &str, method: &str, path: &str, body: Option<Value>) -> JsonResp {
|
||||||
|
let auth = format!("Bearer {token}");
|
||||||
|
tcp_json(
|
||||||
|
self.api,
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
&[("Authorization", &auth)],
|
||||||
|
body.as_ref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn admin(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
|
||||||
|
self.call(&self.admin, method, path, body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fabrica(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
|
||||||
|
self.call(&self.preview, method, path, body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait for an apply to end; returns its final state.
|
||||||
|
async fn settle(&self, apply: &Value) -> String {
|
||||||
|
let id = apply["id"].as_str().expect("an apply id").to_owned();
|
||||||
|
let t = Instant::now();
|
||||||
|
loop {
|
||||||
|
let r = self
|
||||||
|
.admin("GET", &format!("/api/v1/applies/{id}"), None)
|
||||||
|
.await;
|
||||||
|
let state = r.json["state"].as_str().unwrap_or("").to_owned();
|
||||||
|
if ["kept", "reverted", "failed"].contains(&state.as_str()) {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
t.elapsed() < Duration::from_secs(30),
|
||||||
|
"apply {id} stuck: {}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
tokio::time::sleep(Duration::from_millis(700)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn host_names(&self) -> Vec<String> {
|
||||||
|
let r = self.admin("GET", "/api/v1/hosts", None).await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
r.json["hosts"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|h| h["hostname"].as_str().unwrap().to_owned())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn add_plain_host(&self, hostname: &str) {
|
||||||
|
let r = self
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
Some(json!({"host": {"hostname": hostname, "upstreams": ["http://10.0.0.9:80"]}})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(self.settle(&r.json["apply"]).await, "kept");
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_preview(&self, project: &str, branch: &str, upstream: &str) -> JsonResp {
|
||||||
|
self.fabrica(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews",
|
||||||
|
Some(json!({"project": project, "branch": branch, "upstream": upstream, "ttl": 3600})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_preview_token_cannot_touch_non_preview_hosts() {
|
||||||
|
let c = Ctl::start("").await;
|
||||||
|
c.add_plain_host("www.example.test").await;
|
||||||
|
let www =
|
||||||
|
json!({"host": {"hostname": "www.example.test", "upstreams": ["http://10.6.6.6:80"]}});
|
||||||
|
|
||||||
|
// Everything outside /api/v1/previews is refused, reads included.
|
||||||
|
let refused: Vec<(&str, &str, Option<Value>)> = vec![
|
||||||
|
("GET", "/api/v1/overview", None),
|
||||||
|
("GET", "/api/v1/hosts", None),
|
||||||
|
("GET", "/api/v1/hosts/www.example.test", None),
|
||||||
|
(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
Some(
|
||||||
|
json!({"host": {"hostname": "evil.example.test", "upstreams": ["http://10.6.6.6:80"]}}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("PUT", "/api/v1/hosts/www.example.test", Some(www.clone())),
|
||||||
|
(
|
||||||
|
"PATCH",
|
||||||
|
"/api/v1/hosts/www.example.test",
|
||||||
|
Some(json!({"share_links": true})),
|
||||||
|
),
|
||||||
|
("DELETE", "/api/v1/hosts/www.example.test", None),
|
||||||
|
("POST", "/api/v1/hosts/validate", Some(www["host"].clone())),
|
||||||
|
("POST", "/api/v1/undo", Some(json!({}))),
|
||||||
|
("POST", "/api/v1/restore", Some(json!({"change_id": "x"}))),
|
||||||
|
("GET", "/api/v1/history", None),
|
||||||
|
("GET", "/api/v1/applies", None),
|
||||||
|
("GET", "/api/v1/tokens", None),
|
||||||
|
("POST", "/api/v1/tokens", Some(json!({"name": "escalate"}))),
|
||||||
|
(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts/www.example.test/share-links",
|
||||||
|
Some(json!({})),
|
||||||
|
),
|
||||||
|
("POST", "/api/v1/share-links/stop-all", None),
|
||||||
|
("GET", "/api/v1/certs", None),
|
||||||
|
("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))),
|
||||||
|
("POST", "/api/v1/repo/push", None),
|
||||||
|
("GET", "/api/v1/settings", None),
|
||||||
|
("GET", "/api/v1/team", None),
|
||||||
|
];
|
||||||
|
for (m, p, b) in refused {
|
||||||
|
let r = c.fabrica(m, p, b).await;
|
||||||
|
assert_eq!(r.status, 403, "{m} {p}: {}", r.text);
|
||||||
|
assert_eq!(
|
||||||
|
r.json["error"]["code"], "token.scope",
|
||||||
|
"{m} {p}: {}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The previews API refuses a host that is not a preview.
|
||||||
|
let r = c
|
||||||
|
.fabrica("DELETE", "/api/v1/previews/www.example.test", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 404, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "preview.not_found");
|
||||||
|
let r = c
|
||||||
|
.fabrica("GET", "/api/v1/previews/www.example.test", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 404, "{}", r.text);
|
||||||
|
|
||||||
|
// A non-preview host at exactly the name a preview would get is not taken over.
|
||||||
|
let taken = format!("main--shop.{DOMAIN}");
|
||||||
|
c.add_plain_host(&taken).await;
|
||||||
|
let r = c.open_preview("shop", "main", "http://10.0.0.5:8080").await;
|
||||||
|
assert_eq!(r.status, 409, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "preview.taken");
|
||||||
|
let r = c
|
||||||
|
.admin("GET", &format!("/api/v1/hosts/{taken}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
r.json["host"]["upstreams"][0], "http://10.0.0.9:80",
|
||||||
|
"{}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
let r = c
|
||||||
|
.fabrica(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews/close",
|
||||||
|
Some(json!({"project": "shop", "branch": "main"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 404, "{}", r.text);
|
||||||
|
|
||||||
|
// A preview the token made touches only its own file, and the list holds only previews.
|
||||||
|
let r = c
|
||||||
|
.open_preview("shop", "fix-1", "http://10.0.0.5:8080")
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
let hosts = r.json["apply"]["hosts"].as_array().unwrap().clone();
|
||||||
|
assert_eq!(hosts, vec![json!(format!("fix-1--shop.{DOMAIN}"))]);
|
||||||
|
let r = c.fabrica("GET", "/api/v1/previews", None).await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
let listed: Vec<&str> = r.json["items"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|p| p["hostname"].as_str().unwrap())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(listed, vec![format!("fix-1--shop.{DOMAIN}").as_str()]);
|
||||||
|
let mut names = c.host_names().await;
|
||||||
|
names.sort();
|
||||||
|
assert_eq!(
|
||||||
|
names,
|
||||||
|
vec![
|
||||||
|
format!("fix-1--shop.{DOMAIN}"),
|
||||||
|
taken.clone(),
|
||||||
|
"www.example.test".into()
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
// An admin can still kill a preview; the scoped token was never needed for that.
|
||||||
|
let r = c
|
||||||
|
.admin(
|
||||||
|
"DELETE",
|
||||||
|
&format!("/api/v1/previews/fix-1--shop.{DOMAIN}"),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
assert!(
|
||||||
|
!c.host_names()
|
||||||
|
.await
|
||||||
|
.iter()
|
||||||
|
.any(|h| h.starts_with("fix-1--"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_preview_token_cannot_point_a_preview_at_this_machine_s_admin_ports() {
|
||||||
|
let c = Ctl::start("").await;
|
||||||
|
let control_port = c.api.port();
|
||||||
|
for upstream in [
|
||||||
|
// control itself, Caddy's admin API, anything on loopback outside the allowed range
|
||||||
|
format!("http://127.0.0.1:{control_port}"),
|
||||||
|
"http://127.0.0.1:2019".to_owned(),
|
||||||
|
"http://localhost:20001".to_owned(),
|
||||||
|
"http://[::1]:20001".to_owned(),
|
||||||
|
"http://0.0.0.0:20001".to_owned(),
|
||||||
|
"http://169.254.169.254:80".to_owned(),
|
||||||
|
// not in the allow list
|
||||||
|
"http://192.168.1.10:8080".to_owned(),
|
||||||
|
"http://other.internal:8080".to_owned(),
|
||||||
|
// not an upstream at all
|
||||||
|
"http://user:pw@10.0.0.5:8080".to_owned(),
|
||||||
|
"http://10.0.0.5:8080/path".to_owned(),
|
||||||
|
"file:///etc/passwd".to_owned(),
|
||||||
|
"".to_owned(),
|
||||||
|
] {
|
||||||
|
let r = c.open_preview("shop", "main", &upstream).await;
|
||||||
|
assert!(
|
||||||
|
r.status == 422 || r.status == 403,
|
||||||
|
"{upstream}: {} {}",
|
||||||
|
r.status,
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.json["error"]["code"].as_str().is_some_and(
|
||||||
|
|c| c.starts_with("preview.upstream") || c.starts_with("host.upstream")
|
||||||
|
),
|
||||||
|
"{upstream}: {}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(c.host_names().await.is_empty());
|
||||||
|
// Allowed: the private range, the loopback port range, the listed name.
|
||||||
|
for (b, u) in [
|
||||||
|
("a", "http://10.1.2.3:8080"),
|
||||||
|
("b", "http://127.0.0.1:20001"),
|
||||||
|
("c", "http://app.internal:3000"),
|
||||||
|
] {
|
||||||
|
let r = c.open_preview("shop", b, u).await;
|
||||||
|
assert_eq!(r.status, 202, "{u}: {}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_preview_lives_until_closed_or_expired() {
|
||||||
|
let c = Ctl::start("").await;
|
||||||
|
// Open, with a hostile branch name: the host is safe and the API says where it is.
|
||||||
|
let r = c
|
||||||
|
.open_preview(
|
||||||
|
"github:acme/Web.App",
|
||||||
|
"feature/Ünï ../../etc",
|
||||||
|
"http://10.0.0.5:8080",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned();
|
||||||
|
assert!(host.ends_with(&format!(".{DOMAIN}")), "{host}");
|
||||||
|
assert!(host.split('.').next().unwrap().contains("--"));
|
||||||
|
assert_eq!(r.json["preview"]["url"], format!("https://{host}/"));
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
let r = c
|
||||||
|
.fabrica("GET", &format!("/api/v1/previews/{host}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
assert_eq!(r.json["preview"]["branch"], "feature/Ünï ../../etc");
|
||||||
|
assert_eq!(r.json["preview"]["state"], "live", "{}", r.text);
|
||||||
|
|
||||||
|
// A new deploy of the same branch moves the same host, it does not add one.
|
||||||
|
let r = c
|
||||||
|
.open_preview(
|
||||||
|
"github:acme/Web.App",
|
||||||
|
"feature/Ünï ../../etc",
|
||||||
|
"http://10.0.0.6:8080",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(r.json["preview"]["hostname"], host.as_str());
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
let r = c.admin("GET", &format!("/api/v1/hosts/{host}"), None).await;
|
||||||
|
assert_eq!(r.json["host"]["upstreams"][0], "http://10.0.0.6:8080");
|
||||||
|
assert_eq!(c.host_names().await.len(), 1);
|
||||||
|
|
||||||
|
// Closed on merge, by project and branch.
|
||||||
|
let r = c
|
||||||
|
.fabrica(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews/close",
|
||||||
|
Some(json!({"project": "github:acme/Web.App", "branch": "feature/Ünï ../../etc"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
assert!(c.host_names().await.is_empty());
|
||||||
|
|
||||||
|
// Expired: removed by control by itself.
|
||||||
|
let r = c
|
||||||
|
.fabrica(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews",
|
||||||
|
Some(json!({"project": "shop", "branch": "short", "upstream": "http://10.0.0.5:80", "ttl": 2})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
|
||||||
|
let t = Instant::now();
|
||||||
|
while !c.host_names().await.is_empty() {
|
||||||
|
assert!(
|
||||||
|
t.elapsed() < Duration::from_secs(30),
|
||||||
|
"the expired preview stayed"
|
||||||
|
);
|
||||||
|
tokio::time::sleep(Duration::from_millis(700)).await;
|
||||||
|
}
|
||||||
|
let r = c.admin("GET", "/api/v1/history", None).await;
|
||||||
|
assert!(r.text.contains("expired"), "{}", r.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn bad_preview_requests_are_refused_with_a_reason() {
|
||||||
|
let c = Ctl::start(
|
||||||
|
"max_ttl_secs = 86400
|
||||||
|
default_ttl_secs = 3600",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
for (body, code) in [
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "a\nb", "upstream": "http://10.0.0.5:80"}),
|
||||||
|
"preview.branch",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "", "upstream": "http://10.0.0.5:80"}),
|
||||||
|
"preview.branch",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "sh op", "branch": "main", "upstream": "http://10.0.0.5:80"}),
|
||||||
|
"preview.project",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 0}),
|
||||||
|
"preview.ttl",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 864000}),
|
||||||
|
"preview.ttl",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "auth": "none"}),
|
||||||
|
"request.body_unknown_field",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let r = c
|
||||||
|
.fabrica("POST", "/api/v1/previews", Some(body.clone()))
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.json["error"]["code"], code, "{body}: {}", r.text);
|
||||||
|
assert!(r.status == 422 || r.status == 400, "{body}: {}", r.text);
|
||||||
|
}
|
||||||
|
assert!(c.host_names().await.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn without_a_preview_domain_the_api_says_previews_are_off() {
|
||||||
|
let c = Ctl::start("").await;
|
||||||
|
// Replace the config with one that has no [previews] section, then restart.
|
||||||
|
drop(c);
|
||||||
|
let c2 = {
|
||||||
|
let dir = TempDir::new("pv-off");
|
||||||
|
std::fs::create_dir_all(dir.join("state")).unwrap();
|
||||||
|
let api = local(free_port());
|
||||||
|
let text = format!(
|
||||||
|
"listen = \"{api}\"\nstate_dir = \"{st}\"\n\n[routes]\nrepo = \"{repo}\"\n\n[edge]\nconfig = \"{d}/edge.json\"\nshare_revocations = \"{d}/rev.json\"\n\n[caddy]\nconfig = \"{d}/caddy.json\"\n\n[compile]\nhttp_listen = \"127.0.0.1:{h}\"\nhttps_listen = \"127.0.0.1:{hs}\"\ncert_dir = \"{d}\"\nstate_dir = \"{d}\"\naccess_log = \"{d}/a.log\"\ncaddy_credentials_dir = \"{d}\"\n",
|
||||||
|
st = s(&dir.join("state")),
|
||||||
|
repo = s(&dir.join("routes.git")),
|
||||||
|
d = s(dir.path()),
|
||||||
|
h = free_port(),
|
||||||
|
hs = free_port(),
|
||||||
|
);
|
||||||
|
std::fs::write(dir.join("control.toml"), text).unwrap();
|
||||||
|
let cfg = Config::load(&dir.join("control.toml")).unwrap();
|
||||||
|
let (_, tok) = Tokens::new(&dir.join("state"))
|
||||||
|
.create("fabrica", None, Scope::Previews)
|
||||||
|
.unwrap();
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
|
||||||
|
tokio::spawn(ianitor_control::serve(cfg, async {
|
||||||
|
let _ = rx.await;
|
||||||
|
}));
|
||||||
|
assert!(wait_for_port(api, Duration::from_secs(20)));
|
||||||
|
(dir, api, tok, tx)
|
||||||
|
};
|
||||||
|
let auth = format!("Bearer {}", c2.2);
|
||||||
|
let r = tcp_json(
|
||||||
|
c2.1,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/previews",
|
||||||
|
&[("Authorization", &auth)],
|
||||||
|
Some(&json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80"})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 409, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "preview.off");
|
||||||
|
let _ = c2.3.send(());
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Token and share-link stores (QC fix round 1, M2 and M4): a CLI revoke is never lost to the
|
||||||
|
//! server recording token use at the same time, and losing `share-links.json` never revives a
|
||||||
|
//! stopped link.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use ianitor_control::shares::Shares;
|
||||||
|
use ianitor_control::tokens::{Refusal, Tokens};
|
||||||
|
use ianitor_core::share::ShareKey;
|
||||||
|
use ianitor_testkit::proc::TempDir;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
fn revocations(p: &std::path::Path) -> Value {
|
||||||
|
serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() {
|
||||||
|
let bin = env!("CARGO_BIN_EXE_ianitor-control");
|
||||||
|
let rounds = 20;
|
||||||
|
let mut lost = 0;
|
||||||
|
for _ in 0..rounds {
|
||||||
|
let d = TempDir::new("tok-race");
|
||||||
|
let server = Tokens::new(d.path());
|
||||||
|
let values: Vec<_> = (0..150)
|
||||||
|
.map(|i| {
|
||||||
|
server
|
||||||
|
.create(&format!("t{i}"), None, Default::default())
|
||||||
|
.unwrap()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let victim = values[75].0.id.clone();
|
||||||
|
let mut cli = std::process::Command::new(bin)
|
||||||
|
.args(["token", "revoke", &victim, "--state-dir"])
|
||||||
|
.arg(d.path())
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
for (_, v) in &values {
|
||||||
|
let _ = server.check(Some(&format!("Bearer {v}")));
|
||||||
|
}
|
||||||
|
assert!(cli.wait().unwrap().success());
|
||||||
|
if !matches!(
|
||||||
|
server.check(Some(&format!("Bearer {}", values[75].1))),
|
||||||
|
Err(Refusal::Revoked(_))
|
||||||
|
) {
|
||||||
|
lost += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
lost, 0,
|
||||||
|
"the CLI said revoked but the token still worked in {lost}/{rounds} rounds"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn concurrent_creates_from_the_cli_and_the_server_all_survive() {
|
||||||
|
let bin = env!("CARGO_BIN_EXE_ianitor-control");
|
||||||
|
let d = TempDir::new("tok-create");
|
||||||
|
let server = Tokens::new(d.path());
|
||||||
|
let mut clis: Vec<_> = (0..8)
|
||||||
|
.map(|i| {
|
||||||
|
std::process::Command::new(bin)
|
||||||
|
.args([
|
||||||
|
"token",
|
||||||
|
"create",
|
||||||
|
"--name",
|
||||||
|
&format!("cli{i}"),
|
||||||
|
"--state-dir",
|
||||||
|
])
|
||||||
|
.arg(d.path())
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.unwrap()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
for i in 0..40 {
|
||||||
|
server
|
||||||
|
.create(&format!("srv{i}"), None, Default::default())
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
for c in &mut clis {
|
||||||
|
assert!(c.wait().unwrap().success());
|
||||||
|
}
|
||||||
|
assert_eq!(server.list().unwrap().len(), 48);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn losing_share_links_json_never_lowers_the_revocation_epoch() {
|
||||||
|
let d = TempDir::new("epoch");
|
||||||
|
let rev = d.join("share-revocations.json");
|
||||||
|
let s = Shares::new(d.path(), &rev);
|
||||||
|
let key = ShareKey::new(&[9u8; 32]).unwrap();
|
||||||
|
let m = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||||
|
s.stop(&m.record.id).unwrap();
|
||||||
|
s.stop_all().unwrap();
|
||||||
|
s.stop_all().unwrap();
|
||||||
|
assert_eq!(revocations(&rev)["epoch"], 2);
|
||||||
|
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
||||||
|
Shares::new(d.path(), &rev)
|
||||||
|
.ensure_revocation_file()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
revocations(&rev)["epoch"].as_u64().unwrap() >= 2,
|
||||||
|
"{}",
|
||||||
|
revocations(&rev)
|
||||||
|
);
|
||||||
|
// Minting after the loss continues from there.
|
||||||
|
let m2 = Shares::new(d.path(), &rev)
|
||||||
|
.mint(&key, "a.test", "/", 3600, None, None, "t")
|
||||||
|
.unwrap();
|
||||||
|
assert!(m2.record.epoch >= 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_lost_deny_list_raises_the_epoch_instead_of_shrinking() {
|
||||||
|
let d = TempDir::new("deny");
|
||||||
|
let rev = d.join("share-revocations.json");
|
||||||
|
let s = Shares::new(d.path(), &rev);
|
||||||
|
let key = ShareKey::new(&[9u8; 32]).unwrap();
|
||||||
|
let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||||
|
let _b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||||
|
s.stop(&a.record.id).unwrap();
|
||||||
|
let before = revocations(&rev);
|
||||||
|
assert_eq!(before["deny"][0], a.record.id);
|
||||||
|
assert_eq!(before["epoch"], 0);
|
||||||
|
// The records are gone (or an older backup without the stop is restored).
|
||||||
|
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
||||||
|
Shares::new(d.path(), &rev)
|
||||||
|
.ensure_revocation_file()
|
||||||
|
.unwrap();
|
||||||
|
let after = revocations(&rev);
|
||||||
|
let still_denied = after["deny"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.any(|x| x == &before["deny"][0]);
|
||||||
|
assert!(
|
||||||
|
still_denied || after["epoch"].as_u64().unwrap() > 0,
|
||||||
|
"stopped link {} works again: {after}",
|
||||||
|
a.record.id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_deny_list_that_would_overflow_raises_the_epoch() {
|
||||||
|
let d = TempDir::new("overflow");
|
||||||
|
let rev = d.join("share-revocations.json");
|
||||||
|
let s = Shares::new(d.path(), &rev);
|
||||||
|
let t = ianitor_control::util::now();
|
||||||
|
let links: Vec<Value> = (0..10_050u32)
|
||||||
|
.map(|i| {
|
||||||
|
serde_json::json!({
|
||||||
|
"id": format!("{:032x}", i + 1), "hostname": "a.test", "path_prefix": "/", "epoch": 0,
|
||||||
|
"created_at": t, "expires_at": t + 3600, "has_password": false, "created_by": "t",
|
||||||
|
"stopped_at": t
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
std::fs::write(
|
||||||
|
d.join("share-links.json"),
|
||||||
|
serde_json::json!({ "epoch": 0, "links": links }).to_string(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
s.ensure_revocation_file().unwrap();
|
||||||
|
let r = revocations(&rev);
|
||||||
|
assert!(
|
||||||
|
r["epoch"].as_u64().unwrap() >= 1,
|
||||||
|
"an overflowing deny list must raise the epoch: {}",
|
||||||
|
r["epoch"]
|
||||||
|
);
|
||||||
|
assert!(r["deny"].as_array().unwrap().len() < 10_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_link_minted_after_the_records_were_lost_works() {
|
||||||
|
let d = TempDir::new("doa");
|
||||||
|
let rev = d.join("share-revocations.json");
|
||||||
|
let s = Shares::new(d.path(), &rev);
|
||||||
|
let key = ShareKey::new(&[9u8; 32]).unwrap();
|
||||||
|
let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||||
|
s.stop(&a.record.id).unwrap();
|
||||||
|
std::fs::remove_file(d.join("share-links.json")).unwrap();
|
||||||
|
let b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap();
|
||||||
|
let published = revocations(&rev);
|
||||||
|
assert!(
|
||||||
|
u64::from(b.record.epoch) >= published["epoch"].as_u64().unwrap(),
|
||||||
|
"dead on arrival: link epoch {} < published {}",
|
||||||
|
b.record.epoch,
|
||||||
|
published["epoch"]
|
||||||
|
);
|
||||||
|
let list = s.load().unwrap();
|
||||||
|
let rec = list.links.iter().find(|l| l.id == b.record.id).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
rec.state(list.epoch, ianitor_control::util::now()),
|
||||||
|
"active"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Team sign-in without Authelia (T4): the setup link makes the founding admin, invites make
|
||||||
|
//! members, a session cookie identifies them, members cannot do admin things, and browser
|
||||||
|
//! writes need the UI header. Runs on Windows and Linux (control in this process, no edge).
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use ianitor_control::Config;
|
||||||
|
use ianitor_control::team::Team;
|
||||||
|
use ianitor_testkit::more::{JsonResp, tcp_json};
|
||||||
|
use ianitor_testkit::proc::{TempDir, free_port, local, wait_for_port};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
fn s(p: &std::path::Path) -> String {
|
||||||
|
p.to_string_lossy().replace('\\', "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn start() -> (TempDir, SocketAddr, tokio::sync::oneshot::Sender<()>) {
|
||||||
|
let dir = TempDir::new("team");
|
||||||
|
std::fs::create_dir_all(dir.join("state")).unwrap();
|
||||||
|
let api = local(free_port());
|
||||||
|
let text = format!(
|
||||||
|
"listen = \"{api}\"\nstate_dir = \"{st}\"\n\n[routes]\nrepo = \"{repo}\"\n\n[edge]\nconfig = \"{d}/edge.json\"\nshare_revocations = \"{d}/rev.json\"\n\n[caddy]\nconfig = \"{d}/caddy.json\"\n\n[compile]\nhttp_listen = \"127.0.0.1:{h}\"\nhttps_listen = \"127.0.0.1:{hs}\"\ncert_dir = \"{d}\"\nstate_dir = \"{d}\"\naccess_log = \"{d}/a.log\"\ncaddy_credentials_dir = \"{d}\"\n",
|
||||||
|
st = s(&dir.join("state")),
|
||||||
|
repo = s(&dir.join("routes.git")),
|
||||||
|
d = s(dir.path()),
|
||||||
|
h = free_port(),
|
||||||
|
hs = free_port(),
|
||||||
|
);
|
||||||
|
std::fs::write(dir.join("control.toml"), text).unwrap();
|
||||||
|
let cfg = Config::load(&dir.join("control.toml")).unwrap();
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
|
||||||
|
tokio::spawn(ianitor_control::serve(cfg, async {
|
||||||
|
let _ = rx.await;
|
||||||
|
}));
|
||||||
|
assert!(wait_for_port(api, Duration::from_secs(20)));
|
||||||
|
(dir, api, tx)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn req(api: SocketAddr, m: &str, p: &str, h: &[(&str, &str)], b: Option<Value>) -> JsonResp {
|
||||||
|
tcp_json(api, m, p, h, b.as_ref()).await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cookie_of(r: &JsonResp) -> String {
|
||||||
|
let set = r
|
||||||
|
.headers
|
||||||
|
.iter()
|
||||||
|
.find(|(n, _)| n == "set-cookie")
|
||||||
|
.map(|(_, v)| v.clone())
|
||||||
|
.expect("a Set-Cookie");
|
||||||
|
for part in ["HttpOnly", "Secure", "SameSite=Strict", "Path=/"] {
|
||||||
|
assert!(set.contains(part), "{set}");
|
||||||
|
}
|
||||||
|
assert!(set.starts_with("__Host-ianitor=ise_"), "{set}");
|
||||||
|
set.split(';').next().unwrap().to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn sign_in(api: SocketAddr, code: &str, name: &str) -> (JsonResp, String) {
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/session",
|
||||||
|
&[("X-Ianitor-UI", "1"), ("Sec-Fetch-Site", "same-origin")],
|
||||||
|
Some(json!({"code": code, "name": name, "device": "Laptop"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
let c = cookie_of(&r);
|
||||||
|
(r, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_setup_link_then_invites_sign_a_team_in() {
|
||||||
|
let (dir, api, _stop) = start().await;
|
||||||
|
let (setup, _) = Team::new(&dir.join("state")).setup_code().unwrap();
|
||||||
|
|
||||||
|
// The door refuses bad codes, other sites and pages that are not the UI.
|
||||||
|
for (headers, code) in [
|
||||||
|
(vec![("X-Ianitor-UI", "1")], "isc_wrong"),
|
||||||
|
(vec![], setup.as_str()),
|
||||||
|
(
|
||||||
|
vec![("X-Ianitor-UI", "1"), ("Sec-Fetch-Site", "cross-site")],
|
||||||
|
setup.as_str(),
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/session",
|
||||||
|
&headers,
|
||||||
|
Some(json!({"code": code})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(
|
||||||
|
r.status == 401 || r.status == 403,
|
||||||
|
"{headers:?}: {}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
assert!(!r.headers.iter().any(|(n, _)| n == "set-cookie"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let (r, mark) = sign_in(api, &setup, "Mark").await;
|
||||||
|
assert_eq!(r.json["member"]["role"], "admin");
|
||||||
|
let ov = req(api, "GET", "/api/v1/overview", &[("Cookie", &mark)], None).await;
|
||||||
|
assert_eq!(ov.status, 200, "{}", ov.text);
|
||||||
|
assert_eq!(ov.json["viewer"]["via"], "session");
|
||||||
|
assert_eq!(ov.json["viewer"]["name"], "Mark");
|
||||||
|
// The setup link worked once.
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/session",
|
||||||
|
&[("X-Ianitor-UI", "1")],
|
||||||
|
Some(json!({"code": setup})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 401, "{}", r.text);
|
||||||
|
|
||||||
|
// A browser write without the UI header is refused (CSRF), with it it works.
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/team/invites",
|
||||||
|
&[("Cookie", &mark)],
|
||||||
|
Some(json!({"name": "Petra"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 403, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "request.csrf");
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/team/invites",
|
||||||
|
&[("Cookie", &mark), ("X-Ianitor-UI", "1")],
|
||||||
|
Some(json!({"name": "Petra", "role": "member"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 201, "{}", r.text);
|
||||||
|
let code = r.json["link_fragment"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.strip_prefix("#signin=")
|
||||||
|
.unwrap()
|
||||||
|
.to_owned();
|
||||||
|
|
||||||
|
// Petra is a member: hosts yes, tokens, the team and the engine no.
|
||||||
|
let (_, petra) = sign_in(api, &code, "Not Petra").await;
|
||||||
|
let team = req(api, "GET", "/api/v1/team", &[("Cookie", &petra)], None).await;
|
||||||
|
assert_eq!(team.json["me"]["name"], "Petra", "{}", team.text);
|
||||||
|
for (m, p, b) in [
|
||||||
|
("GET", "/api/v1/tokens", None),
|
||||||
|
("POST", "/api/v1/tokens", Some(json!({"name": "x"}))),
|
||||||
|
(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/team/invites",
|
||||||
|
Some(json!({"name": "Eve", "role": "admin"})),
|
||||||
|
),
|
||||||
|
("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))),
|
||||||
|
] {
|
||||||
|
let r = req(api, m, p, &[("Cookie", &petra), ("X-Ianitor-UI", "1")], b).await;
|
||||||
|
assert_eq!(r.status, 403, "{m} {p}: {}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "team.admin_only", "{m} {p}");
|
||||||
|
}
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/hosts",
|
||||||
|
&[("Cookie", &petra), ("X-Ianitor-UI", "1")],
|
||||||
|
Some(
|
||||||
|
json!({"host": {"hostname": "wiki.example.test", "upstreams": ["http://10.0.0.2:80"]}}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 202, "{}", r.text);
|
||||||
|
|
||||||
|
// A member records their Tessera root; the list shows its match code.
|
||||||
|
let root = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"PUT",
|
||||||
|
"/api/v1/team/me/root",
|
||||||
|
&[("Cookie", &petra), ("X-Ianitor-UI", "1")],
|
||||||
|
Some(json!({"tessera_root": root})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
let team = req(api, "GET", "/api/v1/team", &[("Cookie", &mark)], None).await;
|
||||||
|
let p = team.json["members"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|m| m["name"] == "Petra")
|
||||||
|
.unwrap()
|
||||||
|
.clone();
|
||||||
|
assert_eq!(p["match_code"], "016 810");
|
||||||
|
|
||||||
|
// Removing Petra signs her out; a forged cookie gets nothing; the last admin stays.
|
||||||
|
let id = p["id"].as_str().unwrap();
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"DELETE",
|
||||||
|
&format!("/api/v1/team/members/{id}"),
|
||||||
|
&[("Cookie", &mark), ("X-Ianitor-UI", "1")],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
let r = req(api, "GET", "/api/v1/overview", &[("Cookie", &petra)], None).await;
|
||||||
|
assert_eq!(r.status, 401, "{}", r.text);
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"GET",
|
||||||
|
"/api/v1/overview",
|
||||||
|
&[("Cookie", "__Host-ianitor=ise_forged")],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 401);
|
||||||
|
let me = team.json["members"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|m| m["name"] == "Mark")
|
||||||
|
.unwrap()["id"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.to_owned();
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"DELETE",
|
||||||
|
&format!("/api/v1/team/members/{me}"),
|
||||||
|
&[("Cookie", &mark), ("X-Ianitor-UI", "1")],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 409, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "team.last_admin");
|
||||||
|
|
||||||
|
// Signing out ends this browser's session.
|
||||||
|
let r = req(
|
||||||
|
api,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/session/end",
|
||||||
|
&[("Cookie", &mark), ("X-Ianitor-UI", "1")],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
let r = req(api, "GET", "/api/v1/overview", &[("Cookie", &mark)], None).await;
|
||||||
|
assert_eq!(r.status, 401);
|
||||||
|
}
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Sign-in for the web UI (G14, tests first). The UI reaches control through edge on the
|
||||||
|
//! admin host, behind Authelia; edge adds a per-boot secret header (`X-Ianitor-Proof`, from a
|
||||||
|
//! systemd credential only edge and control can read). Control trusts `Remote-User` only on a
|
||||||
|
//! request that carries that proof: any local process can send `Remote-User` to loopback, but
|
||||||
|
//! none can send the proof. API tokens keep working for scripts.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux; run it in WSL2",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
use crate::common::{Env, EnvSpec};
|
||||||
|
use ianitor_testkit::authelia::MockAuthelia;
|
||||||
|
use ianitor_testkit::client::{self, Req};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
const PROOF: &str = "per-boot-proof-0123456789abcdef0123456789abcdef";
|
||||||
|
|
||||||
|
async fn env(site: String) -> Env {
|
||||||
|
env_for(site, "ui.test").await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn env_for(site: String, ui_host: &str) -> Env {
|
||||||
|
let mut env = Env::new(EnvSpec {
|
||||||
|
site,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
std::fs::write(env.dir.join("creds/ui-proof"), format!("{PROOF}\n")).unwrap();
|
||||||
|
let text = std::fs::read_to_string(env.config_path()).unwrap()
|
||||||
|
+ &format!("\n[ui]\nhostname = \"{ui_host}\"\nproof_credential = \"ui-proof\"\n");
|
||||||
|
std::fs::write(env.config_path(), text).unwrap();
|
||||||
|
env.start_control(None);
|
||||||
|
env
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_forged_remote_user_without_the_proof_gets_401() {
|
||||||
|
let env = env(String::new()).await;
|
||||||
|
for headers in [
|
||||||
|
vec![("Remote-User", "mark")],
|
||||||
|
vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "guess")],
|
||||||
|
vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "")],
|
||||||
|
vec![("remote-user", "mark"), ("Remote-Groups", "admins")],
|
||||||
|
] {
|
||||||
|
let r = env
|
||||||
|
.call_with("GET", "/api/v1/overview", &headers, None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 401, "{headers:?}: {}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "ui.no_proof", "{}", r.text);
|
||||||
|
}
|
||||||
|
// A valid API token does not make a forged identity acceptable either.
|
||||||
|
let auth = format!("Bearer {}", env.token);
|
||||||
|
let r = env
|
||||||
|
.call_with(
|
||||||
|
"GET",
|
||||||
|
"/api/v1/overview",
|
||||||
|
&[("Authorization", &auth), ("Remote-User", "mark")],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 401, "{}", r.text);
|
||||||
|
// Nothing was trusted: the log does not show the forged user as an actor.
|
||||||
|
assert!(!env.control_log().contains("by mark"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn the_proof_with_a_remote_user_signs_the_ui_in() {
|
||||||
|
let env = env(String::new()).await;
|
||||||
|
let ok = [("Remote-User", "mark"), ("X-Ianitor-Proof", PROOF)];
|
||||||
|
let r = env.call_with("GET", "/api/v1/overview", &ok, None).await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
// Through edge the Host is the admin host's.
|
||||||
|
let r = env
|
||||||
|
.call_with(
|
||||||
|
"GET",
|
||||||
|
"/api/v1/overview",
|
||||||
|
&[
|
||||||
|
("Remote-User", "mark"),
|
||||||
|
("X-Ianitor-Proof", PROOF),
|
||||||
|
("Host", "ui.test"),
|
||||||
|
],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
// Writes need the UI header (CSRF), browser or not.
|
||||||
|
let r = env
|
||||||
|
.call_with(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/tokens",
|
||||||
|
&ok,
|
||||||
|
Some(json!({"name": "from ui"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 403, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "request.csrf");
|
||||||
|
let mut w = ok.to_vec();
|
||||||
|
w.push(("X-Ianitor-UI", "1"));
|
||||||
|
let r = env
|
||||||
|
.call_with(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/tokens",
|
||||||
|
&w,
|
||||||
|
Some(json!({"name": "from ui"})),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 201, "{}", r.text);
|
||||||
|
// The proof without a user is not a sign-in.
|
||||||
|
let r = env
|
||||||
|
.call_with(
|
||||||
|
"GET",
|
||||||
|
"/api/v1/overview",
|
||||||
|
&[("X-Ianitor-Proof", PROOF)],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 401, "{}", r.text);
|
||||||
|
assert_eq!(r.json["error"]["code"], "ui.no_user");
|
||||||
|
// API tokens still work for scripts.
|
||||||
|
let r = env.call("GET", "/api/v1/overview", None).await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn through_edge_authelia_decides_and_a_client_cannot_bring_its_own_proof() {
|
||||||
|
let auth = MockAuthelia::start().await;
|
||||||
|
let site = format!(
|
||||||
|
"secrets = [\"ui-proof\"]\n[forward_auth]\nurl = \"{}\"\n",
|
||||||
|
auth.url()
|
||||||
|
);
|
||||||
|
let env = env_for(site, "a.test").await;
|
||||||
|
// The admin host: forward-auth, upstream control, the proof header from the secret.
|
||||||
|
let host = json!({"host": {
|
||||||
|
"hostname": "a.test", "upstreams": [format!("http://{}", env.api)],
|
||||||
|
"tls": "domi", "auth": "forward-auth",
|
||||||
|
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
|
||||||
|
}});
|
||||||
|
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
|
||||||
|
assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log());
|
||||||
|
let edge = env.edge.as_ref().unwrap();
|
||||||
|
let roots = env.ca.roots();
|
||||||
|
// Signed in at Authelia (mock: alice): the UI gets in.
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"a.test",
|
||||||
|
roots.clone(),
|
||||||
|
&Req::get("a.test", "/api/v1/overview").header("cookie", "authelia_session=good"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text());
|
||||||
|
assert!(r.text().contains("\"hosts\""), "{}", r.text());
|
||||||
|
// Not signed in: Authelia's answer, control never sees it.
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"a.test",
|
||||||
|
roots.clone(),
|
||||||
|
&Req::get("a.test", "/api/v1/overview"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_ne!(r.status, 200);
|
||||||
|
// A client that sends its own proof and user gets neither through: edge replaces
|
||||||
|
// the proof with the real one only after Authelia allowed the request, and strips
|
||||||
|
// Remote-* from clients.
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"a.test",
|
||||||
|
roots,
|
||||||
|
&Req::get("a.test", "/api/v1/overview")
|
||||||
|
.header("x-ianitor-proof", "guess")
|
||||||
|
.header("remote-user", "mallory"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_ne!(r.status, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC: an admin host (the proof header rule) without forward-auth. Edge strips Remote-*
|
||||||
|
/// only on forward-auth hosts and sets the proof on every request, so any client that
|
||||||
|
/// can reach the host names any user. Control accepts such a host file.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn qc_proof_on_a_host_without_forward_auth_is_refused() {
|
||||||
|
let env = env_for("secrets = [\"ui-proof\"]\n".into(), "a.test").await;
|
||||||
|
let host = json!({"host": {
|
||||||
|
"hostname": "a.test", "upstreams": [format!("http://{}", env.api)],
|
||||||
|
"tls": "domi", "auth": "none",
|
||||||
|
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
|
||||||
|
}});
|
||||||
|
let r = env.call("POST", "/api/v1/hosts", Some(host)).await;
|
||||||
|
// Refused at the door: the proof belongs to the [ui] host behind forward-auth.
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
assert_eq!(
|
||||||
|
r.json["errors"][0]["code"], "host.header.proof",
|
||||||
|
"{}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
env.call("GET", "/api/v1/hosts/a.test", None).await.status == 404,
|
||||||
|
"the host went live"
|
||||||
|
);
|
||||||
|
if r.status != 202 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let edge = env.edge.as_ref().unwrap();
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"a.test",
|
||||||
|
env.ca.roots(),
|
||||||
|
&Req::new("POST", "a.test", "/api/v1/tokens")
|
||||||
|
.body(br#"{"name":"pwned"}"#)
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.header("x-ianitor-ui", "1")
|
||||||
|
.header("remote-user", "mallory"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
eprintln!("QC POST /tokens as mallory: {} {}", r.status, r.text());
|
||||||
|
assert_ne!(
|
||||||
|
r.status,
|
||||||
|
201,
|
||||||
|
"a client minted an API token as mallory: {}",
|
||||||
|
r.text()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC: signed in at Authelia (alice) but the client also sends a proof guess: edge must
|
||||||
|
/// replace, not append, the proof; and Remote-User must be Authelia's.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn qc_signed_in_client_with_own_proof_and_user_is_alice() {
|
||||||
|
let auth = MockAuthelia::start().await;
|
||||||
|
let site = format!(
|
||||||
|
"secrets = [\"ui-proof\"]\n[forward_auth]\nurl = \"{}\"\n",
|
||||||
|
auth.url()
|
||||||
|
);
|
||||||
|
let env = env_for(site, "a.test").await;
|
||||||
|
let host = json!({"host": {
|
||||||
|
"hostname": "a.test", "upstreams": [format!("http://{}", env.api)],
|
||||||
|
"tls": "domi", "auth": "forward-auth",
|
||||||
|
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
|
||||||
|
}});
|
||||||
|
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
|
||||||
|
assert_eq!(rec["state"], "kept", "{rec}");
|
||||||
|
let edge = env.edge.as_ref().unwrap();
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"a.test",
|
||||||
|
env.ca.roots(),
|
||||||
|
&Req::get("a.test", "/api/v1/overview")
|
||||||
|
.header("cookie", "authelia_session=good")
|
||||||
|
.header("x-ianitor-proof", "guess")
|
||||||
|
.header("remote-user", "mallory")
|
||||||
|
.header("remote-name", "Mallory"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text());
|
||||||
|
eprintln!(
|
||||||
|
"QC viewer: {}",
|
||||||
|
r.text()[r.text().find("\"viewer\"").unwrap_or(0)..]
|
||||||
|
.chars()
|
||||||
|
.take(80)
|
||||||
|
.collect::<String>()
|
||||||
|
);
|
||||||
|
assert!(!r.text().contains("allory"), "{}", r.text());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
[package]
|
||||||
|
name = "ianitor-core"
|
||||||
|
description = "Ianitor Domi config model, validation and compilers (Pingora runtime + Caddy JSON). Pure: no I/O."
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
toml.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
url.workspace = true
|
||||||
|
ring.workspace = true
|
||||||
|
base64.workspace = true
|
||||||
|
unicode-normalization = "0.1.24"
|
||||||
|
domi-pki.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
rustls-pki-types.workspace = true
|
||||||
|
webpki = { package = "rustls-webpki", version = "0.103", default-features = false, features = ["ring", "std"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -0,0 +1,388 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Model → Caddy JSON (Caddy v2 native config) for the caddy-fallback unit.
|
||||||
|
//!
|
||||||
|
//! Built with `serde_json::Value`, whose maps are ordered, so the output is deterministic.
|
||||||
|
//! The forward-auth block mirrors what `caddy adapt` produces for Authelia's documented
|
||||||
|
//! `forward_auth … { uri /api/authz/forward-auth; copy_headers … }` snippet.
|
||||||
|
|
||||||
|
use serde_json::{Map, Value, json};
|
||||||
|
|
||||||
|
use super::{CompileOptions, DEVICE_ALLOW_FILE, DEVICE_CA_FILE, join, strip_headers};
|
||||||
|
use crate::{
|
||||||
|
AccessLog, AuthMode, ForwardAuth, HeaderRule, HeaderValue, Host, Model, Scheme, TlsMode,
|
||||||
|
Upstream,
|
||||||
|
};
|
||||||
|
|
||||||
|
const ACCESS_LOGGER: &str = "ianitor_access";
|
||||||
|
const HTTPS_SERVER: &str = "ianitor_https";
|
||||||
|
const HTTP_SERVER: &str = "ianitor_http";
|
||||||
|
|
||||||
|
pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
|
||||||
|
let hosts = model.hosts();
|
||||||
|
let mut root = Map::new();
|
||||||
|
|
||||||
|
root.insert(
|
||||||
|
"admin".into(),
|
||||||
|
match (&o.caddy_admin_socket, o.caddy_admin) {
|
||||||
|
// Only the ianitor group (control) can reach it; no TCP port for local processes.
|
||||||
|
(Some(s), _) => {
|
||||||
|
json!({ "listen": format!("unix//{}|0660", s.trim_start_matches('/')) })
|
||||||
|
}
|
||||||
|
(None, Some(addr)) => json!({ "listen": addr.to_string() }),
|
||||||
|
(None, None) => json!({ "disabled": true }),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
root.insert(
|
||||||
|
"storage".into(),
|
||||||
|
json!({ "module": "file_system", "root": join(&o.state_dir, "caddy") }),
|
||||||
|
);
|
||||||
|
|
||||||
|
let logged: Vec<&Host> = hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| h.access_log == AccessLog::Truncated)
|
||||||
|
.collect();
|
||||||
|
if !logged.is_empty() {
|
||||||
|
root.insert("logging".into(), logging(&o.access_log));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- HTTPS server: one route per host, then a catch-all 404.
|
||||||
|
let mut routes: Vec<Value> = hosts
|
||||||
|
.iter()
|
||||||
|
.map(|h| host_route(h, model.site().forward_auth.as_ref(), o))
|
||||||
|
.collect();
|
||||||
|
routes.push(not_found());
|
||||||
|
|
||||||
|
let domi: Vec<&Host> = hosts.iter().filter(|h| h.tls == TlsMode::Domi).collect();
|
||||||
|
// One policy per host that needs one: a Domi certificate, device certificates, or both.
|
||||||
|
let mut policies: Vec<Value> = hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| h.tls == TlsMode::Domi || h.device_certs)
|
||||||
|
.map(|h| {
|
||||||
|
let mut p = Map::new();
|
||||||
|
p.insert("match".into(), json!({ "sni": [h.hostname.as_str()] }));
|
||||||
|
if h.tls == TlsMode::Domi {
|
||||||
|
p.insert(
|
||||||
|
"certificate_selection".into(),
|
||||||
|
json!({ "any_tag": [cert_tag(h)] }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if h.device_certs {
|
||||||
|
p.insert("client_authentication".into(), client_auth(o));
|
||||||
|
}
|
||||||
|
Value::Object(p)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
policies.push(json!({}));
|
||||||
|
|
||||||
|
let mut https = Map::new();
|
||||||
|
https.insert("listen".into(), json!([o.https_listen.to_string()]));
|
||||||
|
https.insert("routes".into(), Value::Array(routes));
|
||||||
|
https.insert("tls_connection_policies".into(), Value::Array(policies));
|
||||||
|
https.insert(
|
||||||
|
"automatic_https".into(),
|
||||||
|
json!({
|
||||||
|
"disable_redirects": true,
|
||||||
|
"skip_certificates": domi.iter().map(|h| h.hostname.as_str()).collect::<Vec<_>>()
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
https.insert("protocols".into(), json!(["h1", "h2"]));
|
||||||
|
if !o.trusted_proxies.is_empty() {
|
||||||
|
// Like edge: X-Forwarded-For from these peers names the client (logs, `client_ip`).
|
||||||
|
https.insert(
|
||||||
|
"trusted_proxies".into(),
|
||||||
|
json!({
|
||||||
|
"source": "static",
|
||||||
|
"ranges": o.trusted_proxies.iter().map(ToString::to_string).collect::<Vec<_>>()
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
https.insert("client_ip_headers".into(), json!(["X-Forwarded-For"]));
|
||||||
|
https.insert("trusted_proxies_strict".into(), json!(1));
|
||||||
|
}
|
||||||
|
if !logged.is_empty() {
|
||||||
|
let names: Map<String, Value> = logged
|
||||||
|
.iter()
|
||||||
|
.map(|h| (h.hostname.to_string(), json!([ACCESS_LOGGER])))
|
||||||
|
.collect();
|
||||||
|
https.insert(
|
||||||
|
"logs".into(),
|
||||||
|
json!({ "logger_names": names, "skip_unmapped_hosts": true }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- HTTP server: redirect known hosts to HTTPS (ACME HTTP-01 is answered by Caddy itself).
|
||||||
|
let port = o.https_listen.port();
|
||||||
|
let location = if port == 443 {
|
||||||
|
"https://{http.request.host}{http.request.uri}".to_owned()
|
||||||
|
} else {
|
||||||
|
format!("https://{{http.request.host}}:{port}{{http.request.uri}}")
|
||||||
|
};
|
||||||
|
let mut http_routes = Vec::new();
|
||||||
|
if !hosts.is_empty() {
|
||||||
|
http_routes.push(json!({
|
||||||
|
"match": [{ "host": hosts.iter().map(|h| h.hostname.as_str()).collect::<Vec<_>>() }],
|
||||||
|
"handle": [{
|
||||||
|
"handler": "static_response",
|
||||||
|
"status_code": 308,
|
||||||
|
"headers": { "Location": [location] }
|
||||||
|
}],
|
||||||
|
"terminal": true
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
http_routes.push(not_found());
|
||||||
|
let http = json!({
|
||||||
|
"listen": [o.http_listen.to_string()],
|
||||||
|
"routes": http_routes,
|
||||||
|
"automatic_https": { "disable_redirects": true },
|
||||||
|
"protocols": ["h1"]
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut servers = Map::new();
|
||||||
|
servers.insert(HTTPS_SERVER.into(), Value::Object(https));
|
||||||
|
servers.insert(HTTP_SERVER.into(), http);
|
||||||
|
|
||||||
|
let mut tls = Map::new();
|
||||||
|
if !domi.is_empty() {
|
||||||
|
let files: Vec<Value> = domi
|
||||||
|
.iter()
|
||||||
|
.map(|h| {
|
||||||
|
json!({
|
||||||
|
"certificate": join(&o.cert_dir, &format!("{}.crt", h.hostname)),
|
||||||
|
"key": join(&o.cert_dir, &format!("{}.key", h.hostname)),
|
||||||
|
"tags": [cert_tag(h)]
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
tls.insert("certificates".into(), json!({ "load_files": files }));
|
||||||
|
}
|
||||||
|
let acme_hosts: Vec<&str> = hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| h.tls == TlsMode::LetsEncrypt)
|
||||||
|
.map(|h| h.hostname.as_str())
|
||||||
|
.collect();
|
||||||
|
if !acme_hosts.is_empty() {
|
||||||
|
let acme = &model.site().acme;
|
||||||
|
let mut issuer = Map::new();
|
||||||
|
issuer.insert("module".into(), json!("acme"));
|
||||||
|
issuer.insert("ca".into(), json!(acme.directory));
|
||||||
|
if let Some(email) = &acme.email {
|
||||||
|
issuer.insert("email".into(), json!(email));
|
||||||
|
}
|
||||||
|
tls.insert(
|
||||||
|
"automation".into(),
|
||||||
|
json!({ "policies": [{ "subjects": acme_hosts, "issuers": [Value::Object(issuer)] }] }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut apps = Map::new();
|
||||||
|
apps.insert(
|
||||||
|
"http".into(),
|
||||||
|
json!({
|
||||||
|
"http_port": o.http_listen.port(),
|
||||||
|
"https_port": o.https_listen.port(),
|
||||||
|
"servers": servers
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
if !tls.is_empty() {
|
||||||
|
apps.insert("tls".into(), Value::Object(tls));
|
||||||
|
}
|
||||||
|
root.insert("apps".into(), Value::Object(apps));
|
||||||
|
Value::Object(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cert_tag(h: &Host) -> String {
|
||||||
|
format!("ianitor:{}", h.hostname)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn not_found() -> Value {
|
||||||
|
json!({ "handle": [{ "handler": "static_response", "status_code": 404 }] })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn logging(file: &str) -> Value {
|
||||||
|
let mask = json!({ "filter": "ip_mask", "ipv4_cidr": 24, "ipv6_cidr": 48 });
|
||||||
|
let delete = json!({ "filter": "delete" });
|
||||||
|
json!({
|
||||||
|
"logs": {
|
||||||
|
"default": { "exclude": [format!("http.log.access.{ACCESS_LOGGER}")] },
|
||||||
|
"ianitor_access": {
|
||||||
|
"writer": { "output": "file", "filename": file },
|
||||||
|
"encoder": {
|
||||||
|
"format": "filter",
|
||||||
|
"wrap": { "format": "json" },
|
||||||
|
"fields": {
|
||||||
|
"request>remote_ip": mask,
|
||||||
|
"request>client_ip": mask,
|
||||||
|
"request>remote_port": delete,
|
||||||
|
"request>headers": delete,
|
||||||
|
"request>tls": delete,
|
||||||
|
"request>uri": { "filter": "regexp", "regexp": "\\?.*$", "value": "" },
|
||||||
|
"resp_headers": delete
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": [format!("http.log.access.{ACCESS_LOGGER}")]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn host_route(h: &Host, fa: Option<&ForwardAuth>, o: &CompileOptions) -> Value {
|
||||||
|
let mut steps = Vec::new();
|
||||||
|
if h.device_certs {
|
||||||
|
// No client certificate on this connection: 403, like edge. A certificate that is not
|
||||||
|
// trusted or not on the allow list never gets this far (the handshake fails).
|
||||||
|
steps.push(json!({
|
||||||
|
"match": [{ "vars": { "{http.request.tls.client.fingerprint}": [""] } }],
|
||||||
|
"handle": [{ "handler": "static_response", "status_code": 403 }]
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if let (AuthMode::ForwardAuth, Some(fa)) = (h.auth, fa) {
|
||||||
|
// Client-sent identity headers never reach the auth server or the upstream.
|
||||||
|
steps.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": strip_headers(fa) } }] }));
|
||||||
|
steps.push(json!({ "handle": [forward_auth(fa)] }));
|
||||||
|
}
|
||||||
|
if !h.websockets {
|
||||||
|
steps.push(json!({
|
||||||
|
"match": [{ "header_regexp": { "Upgrade": { "pattern": "(?i)(^|,)\\s*websocket\\s*(,|$)" } } }],
|
||||||
|
"handle": [{ "handler": "static_response", "status_code": 403 }]
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
steps.push(json!({ "handle": [reverse_proxy(h, o)] }));
|
||||||
|
json!({
|
||||||
|
"match": [{ "host": [h.hostname.as_str()] }],
|
||||||
|
"handle": [{ "handler": "subroute", "routes": steps }],
|
||||||
|
"terminal": true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn upstreams(list: &[&Upstream]) -> Value {
|
||||||
|
Value::Array(
|
||||||
|
list.iter()
|
||||||
|
.map(|u| json!({ "dial": u.authority() }))
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transport(list: &[&Upstream]) -> Option<Value> {
|
||||||
|
// Validation guarantees one scheme per host.
|
||||||
|
list.first()
|
||||||
|
.filter(|u| u.scheme == Scheme::Https)
|
||||||
|
.map(|_| json!({ "protocol": "http", "tls": {} }))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reverse_proxy(h: &Host, o: &CompileOptions) -> Value {
|
||||||
|
let ups: Vec<&Upstream> = h.upstreams.iter().collect();
|
||||||
|
let mut rp = Map::new();
|
||||||
|
rp.insert("handler".into(), json!("reverse_proxy"));
|
||||||
|
rp.insert("upstreams".into(), upstreams(&ups));
|
||||||
|
rp.insert(
|
||||||
|
"load_balancing".into(),
|
||||||
|
json!({ "selection_policy": { "policy": "round_robin" } }),
|
||||||
|
);
|
||||||
|
if let Some(t) = transport(&ups) {
|
||||||
|
rp.insert("transport".into(), t);
|
||||||
|
}
|
||||||
|
if let Some(hc) = &h.health_check {
|
||||||
|
rp.insert(
|
||||||
|
"health_checks".into(),
|
||||||
|
json!({ "active": { "uri": hc.path, "interval": format!("{}s", hc.interval_secs), "timeout": "5s" } }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut headers = Map::new();
|
||||||
|
if let Some(ops) = header_ops(&h.request_headers, o) {
|
||||||
|
headers.insert("request".into(), ops);
|
||||||
|
}
|
||||||
|
if let Some(ops) = header_ops(&h.response_headers, o) {
|
||||||
|
headers.insert("response".into(), ops);
|
||||||
|
}
|
||||||
|
if !headers.is_empty() {
|
||||||
|
rp.insert("headers".into(), Value::Object(headers));
|
||||||
|
}
|
||||||
|
Value::Object(rp)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header_ops(rules: &[HeaderRule], o: &CompileOptions) -> Option<Value> {
|
||||||
|
if rules.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut set = Map::new();
|
||||||
|
let mut delete = Vec::new();
|
||||||
|
for r in rules {
|
||||||
|
match r {
|
||||||
|
HeaderRule::Set { name, value } => {
|
||||||
|
let v = match value {
|
||||||
|
HeaderValue::Literal(v) => v.clone(),
|
||||||
|
// Caddy reads the credential file itself; the value never enters the config.
|
||||||
|
HeaderValue::Secret(s) => {
|
||||||
|
format!("{{file.{}}}", join(&o.caddy_credentials_dir, s.as_str()))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
set.insert(name.clone(), json!([v]));
|
||||||
|
}
|
||||||
|
HeaderRule::Remove { name } => delete.push(json!(name)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut ops = Map::new();
|
||||||
|
if !set.is_empty() {
|
||||||
|
ops.insert("set".into(), Value::Object(set));
|
||||||
|
}
|
||||||
|
if !delete.is_empty() {
|
||||||
|
ops.insert("delete".into(), Value::Array(delete));
|
||||||
|
}
|
||||||
|
Some(Value::Object(ops))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exactly the handler `caddy adapt` builds from Caddy's `forward_auth` directive.
|
||||||
|
fn forward_auth(fa: &ForwardAuth) -> Value {
|
||||||
|
let mut copy_routes = vec![json!({ "handle": [{ "handler": "vars" }] })];
|
||||||
|
for name in &fa.copy_headers {
|
||||||
|
let placeholder = format!("{{http.reverse_proxy.header.{name}}}");
|
||||||
|
copy_routes
|
||||||
|
.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": [name] } }] }));
|
||||||
|
let mut vars = Map::new();
|
||||||
|
vars.insert(placeholder.clone(), json!([""]));
|
||||||
|
let mut set = Map::new();
|
||||||
|
set.insert(name.clone(), json!([placeholder]));
|
||||||
|
copy_routes.push(json!({
|
||||||
|
"match": [{ "not": [{ "vars": Value::Object(vars) }] }],
|
||||||
|
"handle": [{ "handler": "headers", "request": { "set": Value::Object(set) } }]
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
let ups = [&fa.upstream];
|
||||||
|
let mut rp = Map::new();
|
||||||
|
rp.insert("handler".into(), json!("reverse_proxy"));
|
||||||
|
rp.insert("upstreams".into(), upstreams(&ups));
|
||||||
|
if let Some(t) = transport(&ups) {
|
||||||
|
rp.insert("transport".into(), t);
|
||||||
|
}
|
||||||
|
rp.insert(
|
||||||
|
"rewrite".into(),
|
||||||
|
json!({ "method": "GET", "uri": fa.path_and_query }),
|
||||||
|
);
|
||||||
|
rp.insert(
|
||||||
|
"headers".into(),
|
||||||
|
json!({ "request": { "set": {
|
||||||
|
"X-Forwarded-Method": ["{http.request.method}"],
|
||||||
|
"X-Forwarded-Uri": ["{http.request.uri}"]
|
||||||
|
} } }),
|
||||||
|
);
|
||||||
|
rp.insert(
|
||||||
|
"handle_response".into(),
|
||||||
|
json!([{ "match": { "status_code": [2] }, "routes": copy_routes }]),
|
||||||
|
);
|
||||||
|
Value::Object(rp)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Device certificates: optional in the handshake (a missing one is a 403 in the route, as in
|
||||||
|
/// edge), but one that is presented must chain to the Domi CA bundle and be on the allow list.
|
||||||
|
fn client_auth(o: &CompileOptions) -> Value {
|
||||||
|
json!({
|
||||||
|
"ca": { "provider": "file", "pem_files": [join(&o.cert_dir, DEVICE_CA_FILE)] },
|
||||||
|
"verifiers": [{
|
||||||
|
"verifier": "leaf",
|
||||||
|
"leaf_certs_loaders": [{ "loader": "file", "files": [join(&o.cert_dir, DEVICE_ALLOW_FILE)] }]
|
||||||
|
}],
|
||||||
|
"mode": "verify_if_given"
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Model → [`EdgeConfig`] for the Pingora data plane.
|
||||||
|
|
||||||
|
use super::{CompileOptions, DEVICE_ALLOW_FILE, DEVICE_CA_FILE, join, strip_headers};
|
||||||
|
use crate::edge_config::{
|
||||||
|
EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeDeviceCerts, EdgeForwardAuth, EdgeHeaderOp,
|
||||||
|
EdgeHealthCheck, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
|
||||||
|
};
|
||||||
|
use crate::{AccessLog, AuthMode, HeaderRule, HeaderValue, Model, Scheme, TlsMode, Upstream};
|
||||||
|
|
||||||
|
pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
|
||||||
|
let site = model.site();
|
||||||
|
let any_acme = model.hosts().iter().any(|h| h.tls == TlsMode::LetsEncrypt);
|
||||||
|
EdgeConfig {
|
||||||
|
version: EDGE_CONFIG_VERSION,
|
||||||
|
http_listen: o.http_listen.to_string(),
|
||||||
|
https_listen: o.https_listen.to_string(),
|
||||||
|
https_port: o.https_listen.port(),
|
||||||
|
cert_dir: o.cert_dir.clone(),
|
||||||
|
state_dir: o.state_dir.clone(),
|
||||||
|
access_log: o.access_log.clone(),
|
||||||
|
acme: any_acme.then(|| EdgeAcme {
|
||||||
|
directory: site.acme.directory.clone(),
|
||||||
|
email: site.acme.email.clone(),
|
||||||
|
}),
|
||||||
|
device_certs: model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.any(|h| h.device_certs)
|
||||||
|
.then(|| EdgeDeviceCerts {
|
||||||
|
ca: join(&o.cert_dir, DEVICE_CA_FILE),
|
||||||
|
allow: join(&o.cert_dir, DEVICE_ALLOW_FILE),
|
||||||
|
}),
|
||||||
|
trusted_proxies: o.trusted_proxies.iter().map(ToString::to_string).collect(),
|
||||||
|
forward_auth: site.forward_auth.as_ref().map(|fa| EdgeForwardAuth {
|
||||||
|
upstream: upstream(&fa.upstream),
|
||||||
|
path_and_query: fa.path_and_query.clone(),
|
||||||
|
copy_headers: fa.copy_headers.clone(),
|
||||||
|
strip_headers: strip_headers(fa),
|
||||||
|
}),
|
||||||
|
hosts: model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.map(|h| EdgeHost {
|
||||||
|
hostname: h.hostname.to_string(),
|
||||||
|
tls: match h.tls {
|
||||||
|
TlsMode::LetsEncrypt => EdgeTls::Acme,
|
||||||
|
TlsMode::Domi => EdgeTls::Files {
|
||||||
|
cert: join(&o.cert_dir, &format!("{}.crt", h.hostname)),
|
||||||
|
key: join(&o.cert_dir, &format!("{}.key", h.hostname)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
upstreams: h.upstreams.iter().map(upstream).collect(),
|
||||||
|
forward_auth: h.auth == AuthMode::ForwardAuth,
|
||||||
|
websockets: h.websockets,
|
||||||
|
request_headers: h.request_headers.iter().map(op).collect(),
|
||||||
|
response_headers: h.response_headers.iter().map(op).collect(),
|
||||||
|
health_check: h.health_check.as_ref().map(|hc| EdgeHealthCheck {
|
||||||
|
path: hc.path.clone(),
|
||||||
|
interval_secs: hc.interval_secs,
|
||||||
|
}),
|
||||||
|
access_log: h.access_log == AccessLog::Truncated,
|
||||||
|
share_links: h.share_links,
|
||||||
|
device_certs: h.device_certs,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn upstream(u: &Upstream) -> EdgeUpstream {
|
||||||
|
EdgeUpstream {
|
||||||
|
address: u.authority(),
|
||||||
|
tls: u.scheme == Scheme::Https,
|
||||||
|
// Like Go's TLS client in Caddy: the dial host is the server name; for an IP literal
|
||||||
|
// rustls sends no SNI and checks the IP SAN.
|
||||||
|
sni: u.host_str(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn op(r: &HeaderRule) -> EdgeHeaderOp {
|
||||||
|
match r {
|
||||||
|
HeaderRule::Set { name, value } => EdgeHeaderOp::Set {
|
||||||
|
name: name.clone(),
|
||||||
|
value: match value {
|
||||||
|
HeaderValue::Literal(v) => EdgeValue::Literal { value: v.clone() },
|
||||||
|
HeaderValue::Secret(s) => EdgeValue::Secret {
|
||||||
|
name: s.to_string(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
HeaderRule::Remove { name } => EdgeHeaderOp::Remove { name: name.clone() },
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Compilers from the validated [`Model`] to the two engines. Both are pure and deterministic:
|
||||||
|
//! the same model and options always give byte-identical output (no hash maps, hosts sorted,
|
||||||
|
//! rules in file order). Neither ever sees a secret value, only secret names.
|
||||||
|
//!
|
||||||
|
//! Shared semantics, kept honest by the differential tests in `tests/diff`:
|
||||||
|
//! - HTTP listener: `308` to `https://host[:port]/uri` for known hosts, `404` otherwise.
|
||||||
|
//! - HTTPS listener: host chosen by the `Host` header (certificate by SNI); unknown host `404`.
|
||||||
|
//! - Per host, in order: forward-auth (non-2xx auth answer goes back to the client verbatim;
|
||||||
|
//! on 2xx the identity headers are copied onto the request), websocket refusal (`403` when
|
||||||
|
//! `websockets = false`), then the reverse proxy with header rules, round-robin over healthy
|
||||||
|
//! upstreams, `503` when none is healthy, `502` when the upstream cannot be reached.
|
||||||
|
|
||||||
|
mod caddy;
|
||||||
|
mod edge;
|
||||||
|
|
||||||
|
/// In the certificate directory: the CA bundle for device certificates (written by control).
|
||||||
|
pub const DEVICE_CA_FILE: &str = "domi-devices-ca.pem";
|
||||||
|
/// In the certificate directory: every allowed (issued, not revoked) device certificate.
|
||||||
|
pub const DEVICE_ALLOW_FILE: &str = "domi-devices.pem";
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
use crate::Model;
|
||||||
|
|
||||||
|
/// Deployment facts that are not part of the routes repo (they change only with a rebuild).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct CompileOptions {
|
||||||
|
pub http_listen: SocketAddr,
|
||||||
|
pub https_listen: SocketAddr,
|
||||||
|
/// Absolute directory with Domi certificates: `<hostname>.crt` and `<hostname>.key`.
|
||||||
|
pub cert_dir: String,
|
||||||
|
/// Absolute state directory (edge ACME state, Caddy storage).
|
||||||
|
pub state_dir: String,
|
||||||
|
/// Absolute path of the access log file.
|
||||||
|
pub access_log: String,
|
||||||
|
/// `$CREDENTIALS_DIRECTORY` of the Caddy fallback unit, used in `{file.*}` placeholders.
|
||||||
|
pub caddy_credentials_dir: String,
|
||||||
|
/// Caddy admin endpoint; `None` disables the admin API.
|
||||||
|
pub caddy_admin: Option<SocketAddr>,
|
||||||
|
/// Caddy admin endpoint on a Unix socket (mode 0660), which control uses to load a changed
|
||||||
|
/// config while Caddy serves. Takes precedence over `caddy_admin`.
|
||||||
|
pub caddy_admin_socket: Option<String>,
|
||||||
|
/// Peers whose `X-Forwarded-For` is believed (a proxy in front, such as Caddy beside
|
||||||
|
/// Ianitor on loopback): the share-link throttle and the access log then see the real
|
||||||
|
/// client. Empty (the default): only the connection's own address counts.
|
||||||
|
pub trusted_proxies: Vec<std::net::IpAddr>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum CompileError {
|
||||||
|
#[error("compile option `{option}` is not usable: {reason}")]
|
||||||
|
BadOption {
|
||||||
|
option: &'static str,
|
||||||
|
reason: &'static str,
|
||||||
|
},
|
||||||
|
#[error("could not serialise the compiled config: {0}")]
|
||||||
|
Serialize(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compile to the Pingora runtime config read by ianitor-edge.
|
||||||
|
pub fn edge(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
|
||||||
|
check_options(options)?;
|
||||||
|
let cfg = edge::compile(model, options);
|
||||||
|
serde_json::to_string_pretty(&cfg)
|
||||||
|
.map(|s| s + "\n")
|
||||||
|
.map_err(|e| CompileError::Serialize(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compile to Caddy JSON for the caddy-fallback unit.
|
||||||
|
pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
|
||||||
|
check_options(options)?;
|
||||||
|
let v = caddy::compile(model, options);
|
||||||
|
serde_json::to_string_pretty(&v)
|
||||||
|
.map(|s| s + "\n")
|
||||||
|
.map_err(|e| CompileError::Serialize(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_options(o: &CompileOptions) -> Result<(), CompileError> {
|
||||||
|
if let Some(s) = &o.caddy_admin_socket {
|
||||||
|
check_path(s).map_err(|reason| CompileError::BadOption {
|
||||||
|
option: "caddy_admin_socket",
|
||||||
|
reason,
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
for (option, value) in [
|
||||||
|
("cert_dir", &o.cert_dir),
|
||||||
|
("state_dir", &o.state_dir),
|
||||||
|
("access_log", &o.access_log),
|
||||||
|
("caddy_credentials_dir", &o.caddy_credentials_dir),
|
||||||
|
] {
|
||||||
|
check_path(value).map_err(|reason| CompileError::BadOption { option, reason })?;
|
||||||
|
}
|
||||||
|
if o.http_listen.port() == 0 || o.https_listen.port() == 0 {
|
||||||
|
return Err(CompileError::BadOption {
|
||||||
|
option: "listen",
|
||||||
|
reason: "port 0 is not usable",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if o.http_listen == o.https_listen {
|
||||||
|
return Err(CompileError::BadOption {
|
||||||
|
option: "listen",
|
||||||
|
reason: "HTTP and HTTPS need different addresses",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders. Absolute: `/…` on
|
||||||
|
/// Linux, or a drive path with forward slashes on Windows (`C:/ProgramData/Ianitor/…`, which
|
||||||
|
/// Caddy and Go read as is; control writes backslashes as `/`, see [`windows_path`]).
|
||||||
|
fn check_path(p: &str) -> Result<(), &'static str> {
|
||||||
|
let drive =
|
||||||
|
p.len() >= 3 && p.as_bytes()[0].is_ascii_alphabetic() && &p.as_bytes()[1..3] == b":/";
|
||||||
|
if !p.starts_with('/') && !drive {
|
||||||
|
return Err("it must be an absolute path");
|
||||||
|
}
|
||||||
|
if p.len() > 1024 {
|
||||||
|
return Err("it is longer than 1024 characters");
|
||||||
|
}
|
||||||
|
if !p
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}' && c != b'\\')
|
||||||
|
{
|
||||||
|
return Err("only visible ASCII without '{', '}' or '\\' is allowed");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Windows path as the compilers take it: `C:\ProgramData\Ianitor` → `C:/ProgramData/Ianitor`.
|
||||||
|
/// Anything that is not a drive path is returned unchanged (and a Linux path with a backslash
|
||||||
|
/// is still refused by the option check).
|
||||||
|
pub fn windows_path(p: &str) -> String {
|
||||||
|
let b = p.as_bytes();
|
||||||
|
if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/')
|
||||||
|
{
|
||||||
|
p.replace('\\', "/")
|
||||||
|
} else {
|
||||||
|
p.to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then
|
||||||
|
/// any other configured copy header (case-insensitive, no duplicates).
|
||||||
|
fn strip_headers(fa: &crate::ForwardAuth) -> Vec<String> {
|
||||||
|
let mut out: Vec<String> = crate::AUTHELIA_COPY_HEADERS
|
||||||
|
.iter()
|
||||||
|
.map(|h| (*h).to_owned())
|
||||||
|
.collect();
|
||||||
|
for h in &fa.copy_headers {
|
||||||
|
if !out.iter().any(|o| o.eq_ignore_ascii_case(h)) {
|
||||||
|
out.push(h.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Join a validated directory and a validated file name.
|
||||||
|
fn join(dir: &str, file: &str) -> String {
|
||||||
|
format!("{}/{}", dir.trim_end_matches('/'), file)
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
// 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 compiled runtime config read by ianitor-edge. Produced only by [`crate::compile::edge`].
|
||||||
|
//! Edge never decides policy: everything it does is spelled out here. Secret values are never
|
||||||
|
//! part of it, only secret names, resolved by edge from `$CREDENTIALS_DIRECTORY`.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Bumped on any incompatible change; edge refuses other versions.
|
||||||
|
pub const EDGE_CONFIG_VERSION: u32 = 3;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EdgeConfig {
|
||||||
|
pub version: u32,
|
||||||
|
/// Plain-HTTP listener: ACME HTTP-01 challenges and redirects to HTTPS.
|
||||||
|
pub http_listen: String,
|
||||||
|
/// TLS listener serving every host by SNI.
|
||||||
|
pub https_listen: String,
|
||||||
|
/// Port used in HTTP→HTTPS redirects (omitted from `Location` when 443).
|
||||||
|
pub https_port: u16,
|
||||||
|
/// Directory holding Domi certificates as `<hostname>.crt` / `<hostname>.key`.
|
||||||
|
pub cert_dir: String,
|
||||||
|
/// Edge state; ACME account and certificates live in `<state_dir>/acme`.
|
||||||
|
pub state_dir: String,
|
||||||
|
/// Access log file (JSON lines). Only hosts with `access_log` enabled write to it.
|
||||||
|
pub access_log: String,
|
||||||
|
pub acme: Option<EdgeAcme>,
|
||||||
|
pub forward_auth: Option<EdgeForwardAuth>,
|
||||||
|
/// Device certificates (mTLS); present when any host has `device_certs`.
|
||||||
|
pub device_certs: Option<EdgeDeviceCerts>,
|
||||||
|
/// Peers whose `X-Forwarded-For` is believed (IP addresses); empty: none.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub trusted_proxies: Vec<String>,
|
||||||
|
/// Sorted by hostname.
|
||||||
|
pub hosts: Vec<EdgeHost>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EdgeAcme {
|
||||||
|
pub directory: String,
|
||||||
|
pub email: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EdgeForwardAuth {
|
||||||
|
pub upstream: EdgeUpstream,
|
||||||
|
pub path_and_query: String,
|
||||||
|
pub copy_headers: Vec<String>,
|
||||||
|
/// Removed from every client request on a forward-auth host before the auth check:
|
||||||
|
/// Authelia's four identity headers plus the copy headers.
|
||||||
|
pub strip_headers: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EdgeUpstream {
|
||||||
|
/// `host:port`, IPv6 in brackets.
|
||||||
|
pub address: String,
|
||||||
|
pub tls: bool,
|
||||||
|
/// Server name for TLS (SNI and certificate check): the host name or IP literal.
|
||||||
|
pub sni: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "source")]
|
||||||
|
pub enum EdgeTls {
|
||||||
|
/// Obtain and renew through ACME; stored under `<state_dir>/acme`.
|
||||||
|
Acme,
|
||||||
|
/// Load from files (Domi CA certificates).
|
||||||
|
Files { cert: String, key: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "kind")]
|
||||||
|
pub enum EdgeValue {
|
||||||
|
Literal { value: String },
|
||||||
|
Secret { name: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "op")]
|
||||||
|
pub enum EdgeHeaderOp {
|
||||||
|
Set { name: String, value: EdgeValue },
|
||||||
|
Remove { name: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EdgeHealthCheck {
|
||||||
|
pub path: String,
|
||||||
|
pub interval_secs: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EdgeHost {
|
||||||
|
pub hostname: String,
|
||||||
|
pub tls: EdgeTls,
|
||||||
|
pub upstreams: Vec<EdgeUpstream>,
|
||||||
|
pub forward_auth: bool,
|
||||||
|
pub websockets: bool,
|
||||||
|
pub request_headers: Vec<EdgeHeaderOp>,
|
||||||
|
pub response_headers: Vec<EdgeHeaderOp>,
|
||||||
|
pub health_check: Option<EdgeHealthCheck>,
|
||||||
|
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,
|
||||||
|
/// Only visitors with an allowed Domi device certificate get in (403 otherwise).
|
||||||
|
pub device_certs: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where edge finds what it needs to check device certificates. Both files are written by
|
||||||
|
/// control: the CA bundle (the Domi intermediates that issue device certificates) and the
|
||||||
|
/// allow list (every device certificate that is issued and not revoked, PEM). A certificate
|
||||||
|
/// that chains to the bundle but is not on the list is refused in the handshake.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EdgeDeviceCerts {
|
||||||
|
pub ca: String,
|
||||||
|
pub allow: String,
|
||||||
|
}
|
||||||
@@ -0,0 +1,443 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! 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/<hostname>.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 {
|
||||||
|
#[error("{file}: the file is not valid TOML{}: {message}", line_suffix(*line))]
|
||||||
|
Syntax {
|
||||||
|
file: String,
|
||||||
|
line: Option<usize>,
|
||||||
|
message: String,
|
||||||
|
},
|
||||||
|
#[error("{file}: unknown field `{field}`")]
|
||||||
|
UnknownField { file: String, field: String },
|
||||||
|
#[error("{file}: required field `{field}` is missing")]
|
||||||
|
MissingField { file: String, field: String },
|
||||||
|
#[error("{file}: {message}")]
|
||||||
|
InvalidValue { file: String, message: String },
|
||||||
|
#[error("{file} appears twice in the routes")]
|
||||||
|
DuplicateFile { file: String },
|
||||||
|
#[error("{file} is larger than {max} bytes")]
|
||||||
|
FileTooLarge { file: String, max: usize },
|
||||||
|
#[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}")]
|
||||||
|
InvalidHostname {
|
||||||
|
file: String,
|
||||||
|
hostname: String,
|
||||||
|
reason: &'static str,
|
||||||
|
},
|
||||||
|
#[error("hostname `{hostname}` is defined twice: in {first} and in {second}")]
|
||||||
|
DuplicateHostname {
|
||||||
|
hostname: String,
|
||||||
|
first: String,
|
||||||
|
second: String,
|
||||||
|
},
|
||||||
|
#[error("{file}: at least one upstream is needed")]
|
||||||
|
NoUpstreams { file: String },
|
||||||
|
#[error("{file}: upstream `{url}` is not usable: {reason}")]
|
||||||
|
BadUpstreamUrl {
|
||||||
|
file: String,
|
||||||
|
url: String,
|
||||||
|
reason: &'static str,
|
||||||
|
/// Position in `upstreams`; `None` when the problem is about the list as a whole.
|
||||||
|
index: Option<usize>,
|
||||||
|
},
|
||||||
|
#[error("{file}: upstream `{url}` is listed twice")]
|
||||||
|
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,
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
#[error(
|
||||||
|
"{file}: response header `{header}` may not use a secret; secrets only go to upstreams"
|
||||||
|
)]
|
||||||
|
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,
|
||||||
|
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,
|
||||||
|
field: String,
|
||||||
|
},
|
||||||
|
#[error("{file}: header `{header}` has more than one rule in the same list")]
|
||||||
|
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 },
|
||||||
|
#[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")]
|
||||||
|
ForwardAuthNotConfigured { file: String },
|
||||||
|
#[error(
|
||||||
|
"{file}: only a host behind sign-in (auth = \"forward-auth\") may send the `ui-proof` secret; it is the web UI's admin host"
|
||||||
|
)]
|
||||||
|
ProofWithoutSignIn { file: String },
|
||||||
|
#[error("{file}: forward_auth is not usable: {reason}")]
|
||||||
|
BadForwardAuth { file: String, reason: &'static str },
|
||||||
|
#[error("{file}: acme is not usable: {reason}")]
|
||||||
|
BadAcme { file: String, reason: &'static str },
|
||||||
|
#[error("{file}: the preview is not usable: {reason}")]
|
||||||
|
BadPreview { file: String, reason: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
fn line_suffix(line: Option<usize>) -> String {
|
||||||
|
match line {
|
||||||
|
Some(l) => format!(" (line {l})"),
|
||||||
|
None => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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::ProofWithoutSignIn { file }
|
||||||
|
| E::BadForwardAuth { file, .. }
|
||||||
|
| E::BadAcme { file, .. }
|
||||||
|
| E::BadPreview { 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 {
|
||||||
|
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::ProofWithoutSignIn { .. } => "host.header.proof",
|
||||||
|
E::BadForwardAuth { .. } => "site.forward_auth",
|
||||||
|
E::BadAcme { .. } => "site.acme",
|
||||||
|
E::BadPreview { .. } => "host.preview",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<String> {
|
||||||
|
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()),
|
||||||
|
E::ProofWithoutSignIn { .. } => Some("auth".into()),
|
||||||
|
E::BadPreview { .. } => Some("preview".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> {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<ValidationError>);
|
||||||
|
|
||||||
|
impl ValidationErrors {
|
||||||
|
pub fn errors(&self) -> &[ValidationError] {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_errors(self) -> Vec<ValidationError> {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wrap errors found outside [`crate::load`] (e.g. by [`crate::routes::check_path`]).
|
||||||
|
pub fn from_errors(errors: Vec<ValidationError>) -> ValidationErrors {
|
||||||
|
ValidationErrors(errors)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for ValidationErrors {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
for (i, e) in self.0.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
writeln!(f)?;
|
||||||
|
}
|
||||||
|
write!(f, "{e}")?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for ValidationErrors {}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Ianitor core: host-file model, validation and compilers. Pure: no I/O, no network.
|
||||||
|
//!
|
||||||
|
//! The routes repo holds `ianitor.toml` (site settings) and one TOML file per host.
|
||||||
|
//! [`load`] turns them into a validated [`Model`]; [`compile::edge`] and [`compile::caddy`]
|
||||||
|
//! turn the model into the configs of the two engines.
|
||||||
|
|
||||||
|
pub mod compile;
|
||||||
|
pub mod edge_config;
|
||||||
|
mod error;
|
||||||
|
mod model;
|
||||||
|
pub mod pki;
|
||||||
|
pub mod preview;
|
||||||
|
pub mod routes;
|
||||||
|
pub mod share;
|
||||||
|
pub mod time;
|
||||||
|
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, MAX_FILE_BYTES,
|
||||||
|
MAX_UPSTREAMS, Model, Preview, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream,
|
||||||
|
UpstreamHost,
|
||||||
|
};
|
||||||
|
pub use validate::{SourceFile, load};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user