Compare commits
69 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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,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
|
||||||
@@ -8,8 +8,9 @@ crates/core config model, schema, compilers (Pingora runtime + Caddy JSON),
|
|||||||
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.
|
||||||
|
|
||||||
@@ -20,6 +21,11 @@ pnpm --filter web dev # 127.0.0.1 only, never --host
|
|||||||
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.
|
||||||
@@ -31,7 +37,7 @@ nix flake check # includes NixOS VM tests (Linux + KVM)
|
|||||||
- 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
+3385
File diff suppressed because it is too large
Load Diff
+49
@@ -0,0 +1,49 @@
|
|||||||
|
[workspace]
|
||||||
|
resolver = "3"
|
||||||
|
members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"]
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
version = "0.1.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" }
|
||||||
|
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,10 @@
|
|||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"license": "MPL-2.0",
|
||||||
|
"description": "Ianitor Domi web UI (Svelte 5). Placeholder until phase 3.",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "node -e \"console.log('web: placeholder, the UI arrives in phase 3; nothing is listening')\""
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
[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"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
ianitor-core.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
|
||||||
|
# Dev mode only: a throw-away CA for the dev hosts (the Domi CA arrives in phase 3).
|
||||||
|
rcgen.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
ianitor-testkit.workspace = true
|
||||||
|
ianitor-edge.workspace = true
|
||||||
|
rustls.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,521 @@
|
|||||||
|
// 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 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.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Actor {
|
||||||
|
pub token_id: String,
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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}"),
|
||||||
|
];
|
||||||
|
ok.iter().any(|o| o.eq_ignore_ascii_case(host))
|
||||||
|
|| ctl
|
||||||
|
.cfg
|
||||||
|
.allowed_hosts
|
||||||
|
.iter()
|
||||||
|
.any(|a| a.eq_ignore_ascii_case(host))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
})?;
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
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.contains_key("error") {
|
||||||
|
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/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);
|
||||||
|
api.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,797 @@
|
|||||||
|
// 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,
|
||||||
|
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` (the Caddy switch waits on Mark, ROADMAP §10 (b)).
|
||||||
|
pub running: String,
|
||||||
|
/// `running` or `stopped` (control cannot reach it).
|
||||||
|
pub state: String,
|
||||||
|
pub since: Option<String>,
|
||||||
|
#[schema(value_type = Option<Object>)]
|
||||||
|
pub fallback_ready: Option<serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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>,
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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; arrives in phase 3.
|
||||||
|
#[schema(value_type = Option<Object>)]
|
||||||
|
pub intermediate: Option<serde_json::Value>,
|
||||||
|
pub site: Option<SiteView>,
|
||||||
|
pub paused: Option<Blocked>,
|
||||||
|
/// Set when control cannot read health from edge (`health.unavailable`).
|
||||||
|
pub health_error: Option<Blocked>,
|
||||||
|
pub rev: Option<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.paused() {
|
||||||
|
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),
|
||||||
|
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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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,282 @@
|
|||||||
|
// 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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Compile {
|
||||||
|
pub fn options(&self) -> CompileOptions {
|
||||||
|
CompileOptions {
|
||||||
|
http_listen: self.http_listen,
|
||||||
|
https_listen: self.https_listen,
|
||||||
|
cert_dir: self.cert_dir.clone(),
|
||||||
|
state_dir: self.state_dir.clone(),
|
||||||
|
access_log: self.access_log.clone(),
|
||||||
|
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
|
||||||
|
caddy_admin: self.caddy_admin,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
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()
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// 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 aborts (no cleanup, like a kill -9) when an apply reaches that stage.
|
||||||
|
//! Without the variable this does nothing; the NixOS unit never sets it.
|
||||||
|
//!
|
||||||
|
//! `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).
|
||||||
|
|
||||||
|
/// The stages, in order.
|
||||||
|
pub const STAGES: [&str; 9] = [
|
||||||
|
"prepared",
|
||||||
|
"committed",
|
||||||
|
"trial_written",
|
||||||
|
"trial_loaded",
|
||||||
|
"watching",
|
||||||
|
"watched",
|
||||||
|
"confirmed",
|
||||||
|
"promoted",
|
||||||
|
"reverting",
|
||||||
|
];
|
||||||
|
|
||||||
|
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}: aborting on purpose");
|
||||||
|
std::process::abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fail a state-file write when `IANITOR_TEST_FAIL_WRITE` names this file.
|
||||||
|
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(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
// 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};
|
||||||
|
|
||||||
|
/// Hosts that get a certificate from the dev CA, so `tls = "domi"` works for them.
|
||||||
|
const DEV_HOSTS: [&str; 3] = ["app.dev.test", "wiki.dev.test", "photos.dev.test"];
|
||||||
|
|
||||||
|
/// A throw-away CA and certificates for [`DEV_HOSTS`] in `certs/`; the CA as `dev-ca.crt`.
|
||||||
|
fn dev_certs(dir: &Path) -> Result<(), String> {
|
||||||
|
use rcgen::{
|
||||||
|
BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair, KeyUsagePurpose,
|
||||||
|
};
|
||||||
|
let e = |x: rcgen::Error| x.to_string();
|
||||||
|
let ca_key = KeyPair::generate().map_err(e)?;
|
||||||
|
let mut ca = CertificateParams::new(Vec::<String>::new()).map_err(e)?;
|
||||||
|
ca.distinguished_name
|
||||||
|
.push(DnType::CommonName, "Ianitor dev CA");
|
||||||
|
ca.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
|
||||||
|
ca.key_usages = vec![
|
||||||
|
KeyUsagePurpose::KeyCertSign,
|
||||||
|
KeyUsagePurpose::DigitalSignature,
|
||||||
|
];
|
||||||
|
let ca_cert = ca.self_signed(&ca_key).map_err(e)?;
|
||||||
|
std::fs::write(dir.join("certs/dev-ca.crt"), ca_cert.pem()).map_err(|x| x.to_string())?;
|
||||||
|
let issuer = Issuer::new(ca, ca_key);
|
||||||
|
for h in DEV_HOSTS {
|
||||||
|
let key = KeyPair::generate().map_err(e)?;
|
||||||
|
let mut p = CertificateParams::new(vec![h.to_owned()]).map_err(e)?;
|
||||||
|
p.distinguished_name.push(DnType::CommonName, h);
|
||||||
|
let cert = p.signed_by(&key, &issuer).map_err(e)?;
|
||||||
|
std::fs::write(dir.join(format!("certs/{h}.crt")), cert.pem())
|
||||||
|
.map_err(|x| x.to_string())?;
|
||||||
|
write_atomic(
|
||||||
|
&dir.join(format!("certs/{h}.key")),
|
||||||
|
key.serialize_pem().as_bytes(),
|
||||||
|
0o600,
|
||||||
|
)
|
||||||
|
.map_err(|x| x.to_string())?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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",
|
||||||
|
] {
|
||||||
|
std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
dev_certs(&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,
|
||||||
|
},
|
||||||
|
compile_caddy: None,
|
||||||
|
};
|
||||||
|
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)?;
|
||||||
|
|
||||||
|
// 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?;
|
||||||
|
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 {}; CA: {}",
|
||||||
|
b.display(),
|
||||||
|
DEV_HOSTS.join(", "),
|
||||||
|
dir.join("certs/dev-ca.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!("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,220 @@
|
|||||||
|
// 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())
|
||||||
|
}
|
||||||
|
|
||||||
|
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,187 @@
|
|||||||
|
// 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,
|
||||||
|
/// `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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
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,
|
||||||
|
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![],
|
||||||
|
};
|
||||||
|
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,81 @@
|
|||||||
|
// 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 config;
|
||||||
|
pub mod crash;
|
||||||
|
pub mod edgelink;
|
||||||
|
pub mod engine;
|
||||||
|
pub mod hostspec;
|
||||||
|
pub mod logger;
|
||||||
|
pub mod messages;
|
||||||
|
pub mod records;
|
||||||
|
pub mod repo;
|
||||||
|
pub mod shares;
|
||||||
|
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());
|
||||||
|
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,61 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
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",
|
||||||
|
};
|
||||||
|
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>) {
|
||||||
|
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 })).is_ok() {
|
||||||
|
log::set_max_level(own);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
// 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> [--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 check --config <control.toml> check the config and exit
|
||||||
|
//! ```
|
||||||
|
//! 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;
|
||||||
|
|
||||||
|
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>"
|
||||||
|
);
|
||||||
|
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 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,
|
||||||
|
"--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).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 {} ({}) created. It is shown once; save it in Custos now:",
|
||||||
|
rec.id, rec.name
|
||||||
|
);
|
||||||
|
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()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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 main() -> ExitCode {
|
||||||
|
if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") {
|
||||||
|
return askpass();
|
||||||
|
}
|
||||||
|
logger::init(std::env::var("IANITOR_LOG").ok().as_deref());
|
||||||
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
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("openapi") => {
|
||||||
|
println!("{}", ianitor_control::api::openapi_json());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")),
|
||||||
|
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,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/.
|
||||||
|
|
||||||
|
//! 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.",
|
||||||
|
"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."
|
||||||
|
}
|
||||||
|
"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('{'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,263 @@
|
|||||||
|
// 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};
|
||||||
|
|
||||||
|
#[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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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>,
|
||||||
|
) -> 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,
|
||||||
|
};
|
||||||
|
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).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)).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,543 @@
|
|||||||
|
// 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() {
|
||||||
|
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 do not authenticate (docs/ui-api.md G14).
|
||||||
|
(
|
||||||
|
"remote-user".into(),
|
||||||
|
vec![
|
||||||
|
("Remote-User".into(), "mark".into()),
|
||||||
|
("Remote-Groups".into(), "admins".into()),
|
||||||
|
],
|
||||||
|
"token.missing",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
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
|
||||||
|
);
|
||||||
|
assert_eq!(env.call_with("GET", "/", &[], None).await.status, 401);
|
||||||
|
|
||||||
|
// 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,565 @@
|
|||||||
|
// 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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for EnvSpec {
|
||||||
|
fn default() -> Self {
|
||||||
|
EnvSpec {
|
||||||
|
watch_secs: 2,
|
||||||
|
site: String::new(),
|
||||||
|
remote: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
// 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"),
|
||||||
|
);
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
// 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).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).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,21 @@
|
|||||||
|
[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"
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
// 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, 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 {
|
||||||
|
Some(addr) => json!({ "listen": addr.to_string() }),
|
||||||
|
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();
|
||||||
|
let mut policies: Vec<Value> = domi
|
||||||
|
.iter()
|
||||||
|
.map(|h| {
|
||||||
|
json!({
|
||||||
|
"match": { "sni": [h.hostname.as_str()] },
|
||||||
|
"certificate_selection": { "any_tag": [cert_tag(h)] }
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.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 !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 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)
|
||||||
|
}
|
||||||
@@ -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/.
|
||||||
|
|
||||||
|
//! Model → [`EdgeConfig`] for the Pingora data plane.
|
||||||
|
|
||||||
|
use super::{CompileOptions, join, strip_headers};
|
||||||
|
use crate::edge_config::{
|
||||||
|
EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, 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(),
|
||||||
|
}),
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
.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,129 @@
|
|||||||
|
// 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;
|
||||||
|
|
||||||
|
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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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> {
|
||||||
|
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.
|
||||||
|
fn check_path(p: &str) -> Result<(), &'static str> {
|
||||||
|
if !p.starts_with('/') {
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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,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/.
|
||||||
|
|
||||||
|
//! 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 = 2;
|
||||||
|
|
||||||
|
#[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>,
|
||||||
|
/// 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,
|
||||||
|
}
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
// 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}: 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 },
|
||||||
|
}
|
||||||
|
|
||||||
|
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::BadForwardAuth { file, .. }
|
||||||
|
| E::BadAcme { file, .. } => file,
|
||||||
|
E::DuplicateHostname { second, .. } => second,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when the problem is in the site file (or a stray file), not in a host file.
|
||||||
|
pub fn in_site_file(&self) -> bool {
|
||||||
|
!self.file().starts_with("hosts/")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A stable code the UI switches on, e.g. `host.upstream.no_port` (docs/ui-api.md §3.1).
|
||||||
|
pub fn code(&self) -> &'static str {
|
||||||
|
use ValidationError as E;
|
||||||
|
use reason as r;
|
||||||
|
let site = self.in_site_file();
|
||||||
|
match self {
|
||||||
|
E::Syntax { .. } => "file.syntax",
|
||||||
|
E::UnknownField { .. } if site => "site.field.unknown",
|
||||||
|
E::UnknownField { .. } => "host.field.unknown",
|
||||||
|
E::MissingField { field, .. } if !site && field == "hostname" => {
|
||||||
|
"host.hostname.missing"
|
||||||
|
}
|
||||||
|
E::MissingField { field, .. } if !site && field == "upstreams" => {
|
||||||
|
"host.upstreams.missing"
|
||||||
|
}
|
||||||
|
E::MissingField { .. } => "file.field.missing",
|
||||||
|
E::InvalidValue { .. } => "file.field.invalid",
|
||||||
|
E::DuplicateFile { .. } => "repo.duplicate_file",
|
||||||
|
E::FileTooLarge { .. } => "file.too_large",
|
||||||
|
E::FileNameMismatch { .. } => "host.file_name",
|
||||||
|
E::UnexpectedFile { .. } => "repo.unexpected_file",
|
||||||
|
E::TooManyUpstreams { .. } => "host.upstream.too_many",
|
||||||
|
E::InvalidHostname { reason, .. } => match *reason {
|
||||||
|
x if x == r::HOST_EMPTY => "host.hostname.missing",
|
||||||
|
x if x == r::HOST_TOO_LONG => "host.hostname.too_long",
|
||||||
|
x if x == r::HOST_IP || x == r::HOST_NUMERIC => "host.hostname.numeric",
|
||||||
|
x if x == r::HOST_WILDCARD => "host.hostname.wildcard",
|
||||||
|
x if x == r::HOST_TRAILING_DOT => "host.hostname.trailing_dot",
|
||||||
|
x if x == r::HOST_UPPERCASE => "host.hostname.uppercase",
|
||||||
|
x if x == r::HOST_SPACES => "host.hostname.spaces",
|
||||||
|
x if x == r::HOST_EMPTY_LABEL => "host.hostname.empty_label",
|
||||||
|
x if x == r::HOST_LABEL_LONG => "host.hostname.label_long",
|
||||||
|
x if x == r::HOST_LABEL_DASH => "host.hostname.label_dash",
|
||||||
|
_ => "host.hostname.characters",
|
||||||
|
},
|
||||||
|
E::DuplicateHostname { .. } => "host.hostname.taken",
|
||||||
|
E::NoUpstreams { .. } => "host.upstreams.missing",
|
||||||
|
E::BadUpstreamUrl { reason, .. } => match *reason {
|
||||||
|
x if x == r::URL_SCHEME => "host.upstream.scheme",
|
||||||
|
x if x == r::URL_CREDENTIALS => "host.upstream.credentials",
|
||||||
|
x if x == r::URL_FRAGMENT => "host.upstream.fragment",
|
||||||
|
x if x == r::URL_NO_HOST => "host.upstream.no_host",
|
||||||
|
x if x == r::URL_HOST_NAME => "host.upstream.host_name",
|
||||||
|
x if x == r::URL_NO_PORT => "host.upstream.no_port",
|
||||||
|
x if x == r::URL_PORT_ZERO => "host.upstream.port_zero",
|
||||||
|
x if x == r::URL_PATH => "host.upstream.path",
|
||||||
|
x if x == r::URL_QUERY => "host.upstream.query",
|
||||||
|
x if x == r::URL_MIXED => "host.upstream.mixed_schemes",
|
||||||
|
_ => "host.upstream.not_url",
|
||||||
|
},
|
||||||
|
E::DuplicateUpstream { .. } => "host.upstream.duplicate",
|
||||||
|
E::UndefinedSecret { .. } => "host.header.secret_unknown",
|
||||||
|
E::SecretInResponseHeader { .. } => "host.header.secret_response",
|
||||||
|
E::InvalidSecretName { .. } => "site.secret.name",
|
||||||
|
E::InvalidHeaderName { .. } | E::ProtectedHeader { .. } if site => {
|
||||||
|
"site.forward_auth.header"
|
||||||
|
}
|
||||||
|
E::InvalidHeaderName { .. } => "host.header.name",
|
||||||
|
E::InvalidHeaderValue { reason, .. } if *reason == r::VALUE_EMPTY => {
|
||||||
|
"host.header.empty"
|
||||||
|
}
|
||||||
|
E::InvalidHeaderValue { .. } => "host.header.value",
|
||||||
|
E::ProtectedHeader { .. } => "host.header.protected",
|
||||||
|
E::DuplicateHeaderRule { .. } => "host.header.duplicate",
|
||||||
|
E::BadHeaderRule { reason, .. } => match *reason {
|
||||||
|
x if x == r::RULE_BOTH => "host.header.both",
|
||||||
|
x if x == r::RULE_REMOVE_VALUE => "host.header.remove_value",
|
||||||
|
_ => "host.header.empty",
|
||||||
|
},
|
||||||
|
E::BadHealthCheck { reason, .. } if *reason == r::HEALTH_INTERVAL => {
|
||||||
|
"host.health.interval"
|
||||||
|
}
|
||||||
|
E::BadHealthCheck { .. } => "host.health.path",
|
||||||
|
E::ForwardAuthNotConfigured { .. } => "host.auth.not_configured",
|
||||||
|
E::BadForwardAuth { .. } => "site.forward_auth",
|
||||||
|
E::BadAcme { .. } => "site.acme",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The form field the problem is about, as a path into the host body (`hostname`,
|
||||||
|
/// `upstreams[0]`, `request_headers[2].name`, `health_check.path`), or `None`.
|
||||||
|
pub fn field(&self) -> Option<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()),
|
||||||
|
_ => 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,26 @@
|
|||||||
|
// 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 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, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
|
||||||
|
};
|
||||||
|
pub use validate::{SourceFile, load};
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
// 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 validated model. Values of these types only come out of [`crate::load`], so every
|
||||||
|
//! compiler can rely on them being valid: the structs are `#[non_exhaustive]` and cannot be
|
||||||
|
//! built outside this crate.
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
/// A validated, lowercase DNS hostname (no wildcard, no trailing dot, not an IP address).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub struct Hostname(pub(crate) String);
|
||||||
|
|
||||||
|
impl Hostname {
|
||||||
|
pub fn as_str(&self) -> &str {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Hostname {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str(&self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A validated secret name. It is also the credential file name under `$CREDENTIALS_DIRECTORY`,
|
||||||
|
/// so it can never contain a path separator.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub struct SecretName(pub(crate) String);
|
||||||
|
|
||||||
|
impl SecretName {
|
||||||
|
pub fn as_str(&self) -> &str {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for SecretName {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str(&self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&str> for SecretName {
|
||||||
|
/// For tests and comparisons only; validation happens in [`crate::load`].
|
||||||
|
fn from(s: &str) -> Self {
|
||||||
|
SecretName(s.to_owned())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub enum Scheme {
|
||||||
|
Http,
|
||||||
|
Https,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Scheme {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Scheme::Http => "http",
|
||||||
|
Scheme::Https => "https",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the upstream host is: a DNS name or an IP literal (IPv6 without brackets).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub enum UpstreamHost {
|
||||||
|
Name(String),
|
||||||
|
Ip(std::net::IpAddr),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A validated upstream: scheme, host and explicit port. No path, query, fragment or userinfo.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct Upstream {
|
||||||
|
pub scheme: Scheme,
|
||||||
|
pub host: UpstreamHost,
|
||||||
|
pub port: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Upstream {
|
||||||
|
/// `host:port` as used for dialing, with IPv6 in brackets.
|
||||||
|
pub fn authority(&self) -> String {
|
||||||
|
match &self.host {
|
||||||
|
UpstreamHost::Name(n) => format!("{n}:{}", self.port),
|
||||||
|
UpstreamHost::Ip(std::net::IpAddr::V6(ip)) => format!("[{ip}]:{}", self.port),
|
||||||
|
UpstreamHost::Ip(ip) => format!("{ip}:{}", self.port),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host part for TLS SNI and certificate verification.
|
||||||
|
pub fn host_str(&self) -> String {
|
||||||
|
match &self.host {
|
||||||
|
UpstreamHost::Name(n) => n.clone(),
|
||||||
|
UpstreamHost::Ip(ip) => ip.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Upstream {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "{}://{}", self.scheme.as_str(), self.authority())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum TlsMode {
|
||||||
|
/// Public certificate from Let's Encrypt via ACME (HTTP-01).
|
||||||
|
LetsEncrypt,
|
||||||
|
/// Certificate issued by the Domi CA, read from the certificate directory.
|
||||||
|
Domi,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum AuthMode {
|
||||||
|
None,
|
||||||
|
/// Every request is first checked with the site's forward-auth endpoint (Authelia).
|
||||||
|
ForwardAuth,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum AccessLog {
|
||||||
|
Off,
|
||||||
|
/// Logged with IPv4 truncated to /24 and IPv6 to /48.
|
||||||
|
Truncated,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum HeaderValue {
|
||||||
|
Literal(String),
|
||||||
|
/// Resolved by the engine at load time; never part of any compiled output.
|
||||||
|
Secret(SecretName),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum HeaderRule {
|
||||||
|
Set { name: String, value: HeaderValue },
|
||||||
|
Remove { name: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HeaderRule {
|
||||||
|
pub fn name(&self) -> &str {
|
||||||
|
match self {
|
||||||
|
HeaderRule::Set { name, .. } | HeaderRule::Remove { name } => name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct HealthCheck {
|
||||||
|
pub path: String,
|
||||||
|
pub interval_secs: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One validated host file.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct Host {
|
||||||
|
pub hostname: Hostname,
|
||||||
|
/// The route file this host came from, for messages.
|
||||||
|
pub source: String,
|
||||||
|
pub upstreams: Vec<Upstream>,
|
||||||
|
pub tls: TlsMode,
|
||||||
|
pub auth: AuthMode,
|
||||||
|
pub request_headers: Vec<HeaderRule>,
|
||||||
|
pub response_headers: Vec<HeaderRule>,
|
||||||
|
pub websockets: bool,
|
||||||
|
pub health_check: Option<HealthCheck>,
|
||||||
|
pub share_links: bool,
|
||||||
|
pub access_log: AccessLog,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The forward-auth endpoint (Authelia's `/api/authz/forward-auth`).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct ForwardAuth {
|
||||||
|
pub upstream: Upstream,
|
||||||
|
/// Path plus optional query, e.g. `/api/authz/forward-auth`.
|
||||||
|
pub path_and_query: String,
|
||||||
|
/// Headers copied from a 2xx auth response onto the upstream request.
|
||||||
|
pub copy_headers: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct Acme {
|
||||||
|
pub email: Option<String>,
|
||||||
|
pub directory: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Site-wide settings from `ianitor.toml`.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct Site {
|
||||||
|
pub secrets: BTreeSet<SecretName>,
|
||||||
|
pub forward_auth: Option<ForwardAuth>,
|
||||||
|
pub acme: Acme,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole validated routes tree. Hosts are sorted by hostname.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Model {
|
||||||
|
pub(crate) site: Site,
|
||||||
|
pub(crate) hosts: Vec<Host>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Model {
|
||||||
|
pub fn site(&self) -> &Site {
|
||||||
|
&self.site
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hosts(&self) -> &[Host] {
|
||||||
|
&self.hosts
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Let's Encrypt production directory, the default when `[acme] directory` is not set.
|
||||||
|
pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/directory";
|
||||||
|
/// Let's Encrypt staging directory.
|
||||||
|
pub const LETSENCRYPT_STAGING: &str = "https://acme-staging-v02.api.letsencrypt.org/directory";
|
||||||
|
/// Largest route file accepted (site or host).
|
||||||
|
pub const MAX_FILE_BYTES: usize = 1 << 20;
|
||||||
|
/// Most upstreams one host may list.
|
||||||
|
pub const MAX_UPSTREAMS: usize = 64;
|
||||||
|
/// Identity headers Authelia returns on success (Authelia's Caddy integration guide).
|
||||||
|
pub const AUTHELIA_COPY_HEADERS: [&str; 4] = [
|
||||||
|
"Remote-User",
|
||||||
|
"Remote-Groups",
|
||||||
|
"Remote-Email",
|
||||||
|
"Remote-Name",
|
||||||
|
];
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! The shape of the routes repository: exactly `ianitor.toml` and `hosts/<hostname>.toml`,
|
||||||
|
//! regular files only. Anything else (other names, folders inside `hosts/`, symbolic links,
|
||||||
|
//! submodules, executables) is refused, so the repository can never hold something the
|
||||||
|
//! compilers do not read.
|
||||||
|
|
||||||
|
use crate::error::{ValidationError, reason};
|
||||||
|
use crate::validate::check_hostname;
|
||||||
|
|
||||||
|
/// The site file at the root of the repository.
|
||||||
|
pub const SITE_FILE: &str = "ianitor.toml";
|
||||||
|
/// The folder holding one file per host.
|
||||||
|
pub const HOSTS_DIR: &str = "hosts";
|
||||||
|
/// Most host files one repository may hold.
|
||||||
|
pub const MAX_HOST_FILES: usize = 1000;
|
||||||
|
|
||||||
|
/// What a tree entry is, as git reports it (`git ls-tree` modes).
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum EntryKind {
|
||||||
|
/// Mode 100644.
|
||||||
|
File,
|
||||||
|
/// Mode 100755.
|
||||||
|
Executable,
|
||||||
|
/// Mode 120000.
|
||||||
|
Symlink,
|
||||||
|
/// Mode 160000.
|
||||||
|
Submodule,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A path the repository may hold.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum RoutePath {
|
||||||
|
Site,
|
||||||
|
Host { hostname: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The path of the file for `hostname`.
|
||||||
|
pub fn host_path(hostname: &str) -> String {
|
||||||
|
format!("{HOSTS_DIR}/{hostname}.toml")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check one path of the repository tree (as listed recursively, `/`-separated).
|
||||||
|
pub fn check_path(path: &str, kind: EntryKind) -> Result<RoutePath, ValidationError> {
|
||||||
|
let bad = |reason| ValidationError::UnexpectedFile {
|
||||||
|
file: path.to_owned(),
|
||||||
|
reason,
|
||||||
|
};
|
||||||
|
if kind != EntryKind::File {
|
||||||
|
return Err(bad(reason::PATH_KIND));
|
||||||
|
}
|
||||||
|
if path == SITE_FILE {
|
||||||
|
return Ok(RoutePath::Site);
|
||||||
|
}
|
||||||
|
let Some(rest) = path.strip_prefix("hosts/") else {
|
||||||
|
return Err(bad(reason::PATH_LAYOUT));
|
||||||
|
};
|
||||||
|
if rest.contains(['/', '\\']) {
|
||||||
|
return Err(bad(reason::PATH_SUBDIR));
|
||||||
|
}
|
||||||
|
let Some(hostname) = rest.strip_suffix(".toml") else {
|
||||||
|
return Err(bad(reason::PATH_NAME));
|
||||||
|
};
|
||||||
|
if check_hostname(hostname).is_err() {
|
||||||
|
return Err(bad(reason::PATH_NAME));
|
||||||
|
}
|
||||||
|
Ok(RoutePath::Host {
|
||||||
|
hostname: hostname.to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check a whole tree listing. Returns every problem; at most [`MAX_HOST_FILES`] host files.
|
||||||
|
pub fn check_tree<'a>(
|
||||||
|
entries: impl IntoIterator<Item = (&'a str, EntryKind)>,
|
||||||
|
) -> Result<(), Vec<ValidationError>> {
|
||||||
|
let mut errors = Vec::new();
|
||||||
|
let mut hosts = 0usize;
|
||||||
|
let mut site = false;
|
||||||
|
for (path, kind) in entries {
|
||||||
|
match check_path(path, kind) {
|
||||||
|
Ok(RoutePath::Site) => site = true,
|
||||||
|
Ok(RoutePath::Host { .. }) => hosts += 1,
|
||||||
|
Err(e) => errors.push(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !site {
|
||||||
|
errors.push(ValidationError::MissingField {
|
||||||
|
file: SITE_FILE.into(),
|
||||||
|
field: "(the file itself)".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if hosts > MAX_HOST_FILES {
|
||||||
|
errors.push(ValidationError::UnexpectedFile {
|
||||||
|
file: HOSTS_DIR.into(),
|
||||||
|
reason: "more than 1000 host files",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if errors.is_empty() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(errors)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,554 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Share links: stateless tokens minted by control and checked by edge.
|
||||||
|
//!
|
||||||
|
//! A link token is `ish1.` + base64url(payload ‖ mac):
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! payload = version (1) ‖ id (16) ‖ epoch (u32 BE) ‖ expires_at (u64 BE, Unix s) ‖ flags (1) ‖ path prefix
|
||||||
|
//! mac = HMAC-SHA256(key, "ianitor share link v1" 0 host 0 payload [0 HMAC-SHA256(key, "ianitor share password v1" 0 id password)])
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! - The host is not in the token but in the MAC, so a token for one host fails on another.
|
||||||
|
//! - With a password (flag bit 0), the MAC can only be checked by someone who has both the key
|
||||||
|
//! and the password: the token carries no password hash, so holding a link does not allow
|
||||||
|
//! guessing its password offline. Edge rate-limits guesses.
|
||||||
|
//! - The session cookie edge sets after a successful check is `iss1.` + base64url(payload ‖
|
||||||
|
//! HMAC(key, "ianitor share session v1" 0 host 0 payload)): a different domain, so a link
|
||||||
|
//! token is never accepted as a cookie and a cookie never as a link (and a cookie for a
|
||||||
|
//! password link proves the password was given).
|
||||||
|
//! - Revocation: every token carries the epoch it was minted in; edge refuses tokens from an
|
||||||
|
//! older epoch ("stop all") and ids on the deny list ("stop this link").
|
||||||
|
//!
|
||||||
|
//! [`path_within`] decides whether a raw request path lies under a link's prefix. It refuses
|
||||||
|
//! anything an upstream might read differently from a plain byte comparison.
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
use base64::Engine as _;
|
||||||
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||||
|
use ring::hmac;
|
||||||
|
|
||||||
|
/// Name of the credential (`$CREDENTIALS_DIRECTORY/<name>`) holding the share-link key, read by
|
||||||
|
/// both edge and control.
|
||||||
|
pub const KEY_CREDENTIAL: &str = "share-link-key";
|
||||||
|
/// Shortest key accepted, in bytes.
|
||||||
|
pub const MIN_KEY_LEN: usize = 32;
|
||||||
|
/// Query parameter carrying a link token. Edge only takes values that start with
|
||||||
|
/// [`LINK_PREFIX`]; anything else is left to the upstream.
|
||||||
|
pub const QUERY_PARAM: &str = "share";
|
||||||
|
/// Start of every link token.
|
||||||
|
pub const LINK_PREFIX: &str = "ish1.";
|
||||||
|
/// Start of every session cookie value.
|
||||||
|
pub const SESSION_PREFIX: &str = "iss1.";
|
||||||
|
/// Session cookie name (`__Secure-`: browsers only accept it with `Secure`).
|
||||||
|
pub const COOKIE_NAME: &str = "__Secure-ianitor-share";
|
||||||
|
/// Path the password form posts to, on hosts with share links.
|
||||||
|
pub const PASSWORD_PATH: &str = "/.well-known/ianitor/share";
|
||||||
|
/// Longest path prefix.
|
||||||
|
pub const MAX_PREFIX_LEN: usize = 256;
|
||||||
|
/// Password length limits, in characters.
|
||||||
|
pub const MIN_PASSWORD_CHARS: usize = 8;
|
||||||
|
pub const MAX_PASSWORD_CHARS: usize = 128;
|
||||||
|
|
||||||
|
const VERSION: u8 = 1;
|
||||||
|
const FLAG_PASSWORD: u8 = 1;
|
||||||
|
const FIXED_LEN: usize = 1 + 16 + 4 + 8 + 1;
|
||||||
|
const MAC_LEN: usize = 32;
|
||||||
|
/// Longest token or cookie accepted before decoding.
|
||||||
|
const MAX_ENCODED_LEN: usize = 1024;
|
||||||
|
|
||||||
|
/// A link id: 16 random bytes, written as 32 lowercase hex digits.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub struct ShareId(pub [u8; 16]);
|
||||||
|
|
||||||
|
impl ShareId {
|
||||||
|
pub fn to_hex(&self) -> String {
|
||||||
|
self.0.iter().map(|b| format!("{b:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_hex(s: &str) -> Option<ShareId> {
|
||||||
|
if s.len() != 32
|
||||||
|
|| !s
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut out = [0u8; 16];
|
||||||
|
for (i, o) in out.iter_mut().enumerate() {
|
||||||
|
*o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?;
|
||||||
|
}
|
||||||
|
Some(ShareId(out))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for ShareId {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str(&self.to_hex())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The HMAC key. Never printed.
|
||||||
|
pub struct ShareKey(hmac::Key);
|
||||||
|
|
||||||
|
impl fmt::Debug for ShareKey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("ShareKey(<redacted>)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum ShareError {
|
||||||
|
#[error("the share-link key must be at least {MIN_KEY_LEN} bytes")]
|
||||||
|
KeyTooShort,
|
||||||
|
#[error("the path prefix is not usable: {0}")]
|
||||||
|
Prefix(&'static str),
|
||||||
|
#[error("the password must be {MIN_PASSWORD_CHARS} to {MAX_PASSWORD_CHARS} characters")]
|
||||||
|
Password,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ShareKey {
|
||||||
|
pub fn new(bytes: &[u8]) -> Result<ShareKey, ShareError> {
|
||||||
|
if bytes.len() < MIN_KEY_LEN {
|
||||||
|
return Err(ShareError::KeyTooShort);
|
||||||
|
}
|
||||||
|
Ok(ShareKey(hmac::Key::new(hmac::HMAC_SHA256, bytes)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a token says. For a token checked with [`verify_link`] or [`verify_session`], all of
|
||||||
|
/// it is proven by the MAC; from [`peek`], none of it is.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Claims {
|
||||||
|
pub id: ShareId,
|
||||||
|
pub epoch: u32,
|
||||||
|
pub expires_at: u64,
|
||||||
|
pub password: bool,
|
||||||
|
pub prefix: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What to mint.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct LinkSpec<'a> {
|
||||||
|
pub id: ShareId,
|
||||||
|
pub epoch: u32,
|
||||||
|
pub expires_at: u64,
|
||||||
|
/// Already checked with [`check_prefix`].
|
||||||
|
pub prefix: &'a str,
|
||||||
|
pub password: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a token was refused.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Rejection {
|
||||||
|
/// Not a token at all (bad encoding, wrong version, too long).
|
||||||
|
Malformed,
|
||||||
|
/// The MAC does not match: altered, minted for another host, made with another key, or
|
||||||
|
/// (for a password link) the wrong password.
|
||||||
|
Invalid,
|
||||||
|
/// The link needs a password and none was given.
|
||||||
|
PasswordRequired,
|
||||||
|
/// Proven genuine, but past its expiry.
|
||||||
|
Expired { expires_at: u64 },
|
||||||
|
/// Proven genuine, but stopped (deny list or an older epoch).
|
||||||
|
Revoked,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The revocation state edge checks against (from the deny-list file control writes).
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct Revocations {
|
||||||
|
/// Tokens minted in an older epoch are refused ("stop all").
|
||||||
|
pub epoch: u32,
|
||||||
|
/// Stopped links.
|
||||||
|
pub deny: BTreeSet<ShareId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Revocations {
|
||||||
|
pub fn is_revoked(&self, c: &Claims) -> bool {
|
||||||
|
c.epoch < self.epoch || self.deny.contains(&c.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn payload(spec: &LinkSpec<'_>) -> Vec<u8> {
|
||||||
|
let mut p = Vec::with_capacity(FIXED_LEN + spec.prefix.len());
|
||||||
|
p.push(VERSION);
|
||||||
|
p.extend_from_slice(&spec.id.0);
|
||||||
|
p.extend_from_slice(&spec.epoch.to_be_bytes());
|
||||||
|
p.extend_from_slice(&spec.expires_at.to_be_bytes());
|
||||||
|
p.push(if spec.password.is_some() {
|
||||||
|
FLAG_PASSWORD
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
});
|
||||||
|
p.extend_from_slice(spec.prefix.as_bytes());
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
fn password_tag(key: &ShareKey, id: &ShareId, password: &str) -> hmac::Tag {
|
||||||
|
let mut ctx = hmac::Context::with_key(&key.0);
|
||||||
|
ctx.update(b"ianitor share password v1\0");
|
||||||
|
ctx.update(&id.0);
|
||||||
|
ctx.update(password.as_bytes());
|
||||||
|
ctx.sign()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn link_message(
|
||||||
|
key: &ShareKey,
|
||||||
|
host: &str,
|
||||||
|
payload: &[u8],
|
||||||
|
id: &ShareId,
|
||||||
|
password: Option<&str>,
|
||||||
|
) -> Vec<u8> {
|
||||||
|
let mut m = Vec::with_capacity(64 + host.len() + payload.len());
|
||||||
|
m.extend_from_slice(b"ianitor share link v1\0");
|
||||||
|
m.extend_from_slice(host.as_bytes());
|
||||||
|
m.push(0);
|
||||||
|
m.extend_from_slice(payload);
|
||||||
|
if let Some(pw) = password {
|
||||||
|
m.push(0);
|
||||||
|
m.extend_from_slice(password_tag(key, id, pw).as_ref());
|
||||||
|
}
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session_message(host: &str, payload: &[u8]) -> Vec<u8> {
|
||||||
|
let mut m = Vec::with_capacity(64 + host.len() + payload.len());
|
||||||
|
m.extend_from_slice(b"ianitor share session v1\0");
|
||||||
|
m.extend_from_slice(host.as_bytes());
|
||||||
|
m.push(0);
|
||||||
|
m.extend_from_slice(payload);
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_password(pw: &str) -> Result<(), ShareError> {
|
||||||
|
let n = pw.chars().count();
|
||||||
|
if (MIN_PASSWORD_CHARS..=MAX_PASSWORD_CHARS).contains(&n) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(ShareError::Password)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mint a link token for `host` (a validated hostname).
|
||||||
|
pub fn mint(key: &ShareKey, host: &str, spec: &LinkSpec<'_>) -> Result<String, ShareError> {
|
||||||
|
let prefix = check_prefix(spec.prefix).map_err(ShareError::Prefix)?;
|
||||||
|
if prefix != spec.prefix {
|
||||||
|
return Err(ShareError::Prefix("it is not in its normal form"));
|
||||||
|
}
|
||||||
|
if let Some(pw) = spec.password {
|
||||||
|
check_password(pw)?;
|
||||||
|
}
|
||||||
|
let p = payload(spec);
|
||||||
|
let tag = hmac::sign(
|
||||||
|
&key.0,
|
||||||
|
&link_message(key, host, &p, &spec.id, spec.password),
|
||||||
|
);
|
||||||
|
let mut raw = p;
|
||||||
|
raw.extend_from_slice(tag.as_ref());
|
||||||
|
Ok(format!("{LINK_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Split and decode without checking the MAC. Only for showing a password page.
|
||||||
|
fn decode(token: &str, prefix: &str) -> Result<(Claims, Vec<u8>, Vec<u8>), Rejection> {
|
||||||
|
if token.len() > MAX_ENCODED_LEN {
|
||||||
|
return Err(Rejection::Malformed);
|
||||||
|
}
|
||||||
|
let body = token.strip_prefix(prefix).ok_or(Rejection::Malformed)?;
|
||||||
|
let raw = URL_SAFE_NO_PAD
|
||||||
|
.decode(body)
|
||||||
|
.map_err(|_| Rejection::Malformed)?;
|
||||||
|
if raw.len() < FIXED_LEN + MAC_LEN + 1 {
|
||||||
|
return Err(Rejection::Malformed);
|
||||||
|
}
|
||||||
|
let (p, mac) = raw.split_at(raw.len() - MAC_LEN);
|
||||||
|
if p[0] != VERSION || p[FIXED_LEN - 1] & !FLAG_PASSWORD != 0 {
|
||||||
|
return Err(Rejection::Malformed);
|
||||||
|
}
|
||||||
|
let mut id = [0u8; 16];
|
||||||
|
id.copy_from_slice(&p[1..17]);
|
||||||
|
let mut e = [0u8; 4];
|
||||||
|
e.copy_from_slice(&p[17..21]);
|
||||||
|
let mut x = [0u8; 8];
|
||||||
|
x.copy_from_slice(&p[21..29]);
|
||||||
|
let prefix = std::str::from_utf8(&p[FIXED_LEN..]).map_err(|_| Rejection::Malformed)?;
|
||||||
|
// A token whose prefix is not in normal form was never minted.
|
||||||
|
if check_prefix(prefix).ok().as_deref() != Some(prefix) {
|
||||||
|
return Err(Rejection::Malformed);
|
||||||
|
}
|
||||||
|
Ok((
|
||||||
|
Claims {
|
||||||
|
id: ShareId(id),
|
||||||
|
epoch: u32::from_be_bytes(e),
|
||||||
|
expires_at: u64::from_be_bytes(x),
|
||||||
|
password: p[FIXED_LEN - 1] & FLAG_PASSWORD != 0,
|
||||||
|
prefix: prefix.to_owned(),
|
||||||
|
},
|
||||||
|
p.to_vec(),
|
||||||
|
mac.to_vec(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a link token claims, unchecked (for the password page: is a password needed, and
|
||||||
|
/// until when does it claim to work). Never grant anything on this alone.
|
||||||
|
pub fn peek(token: &str) -> Result<Claims, Rejection> {
|
||||||
|
decode(token, LINK_PREFIX).map(|(c, _, _)| c)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check a link token for `host`. The order of checks fixes what a visitor learns: a password
|
||||||
|
/// is asked for before anything else is proven; expiry and revocation are reported only for
|
||||||
|
/// tokens proven genuine.
|
||||||
|
pub fn verify_link(
|
||||||
|
key: &ShareKey,
|
||||||
|
host: &str,
|
||||||
|
token: &str,
|
||||||
|
password: Option<&str>,
|
||||||
|
now: u64,
|
||||||
|
revocations: &Revocations,
|
||||||
|
) -> Result<Claims, Rejection> {
|
||||||
|
let (claims, p, mac) = decode(token, LINK_PREFIX)?;
|
||||||
|
let password = match (claims.password, password) {
|
||||||
|
(true, None) => return Err(Rejection::PasswordRequired),
|
||||||
|
(true, Some(pw)) => Some(pw),
|
||||||
|
(false, _) => None,
|
||||||
|
};
|
||||||
|
let msg = link_message(key, host, &p, &claims.id, password);
|
||||||
|
hmac::verify(&key.0, &msg, &mac).map_err(|_| Rejection::Invalid)?;
|
||||||
|
finish(claims, now, revocations)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result<Claims, Rejection> {
|
||||||
|
if now >= claims.expires_at {
|
||||||
|
return Err(Rejection::Expired {
|
||||||
|
expires_at: claims.expires_at,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if revocations.is_revoked(&claims) {
|
||||||
|
return Err(Rejection::Revoked);
|
||||||
|
}
|
||||||
|
Ok(claims)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session cookie value for claims proven by [`verify_link`].
|
||||||
|
pub fn session_value(key: &ShareKey, host: &str, claims: &Claims) -> String {
|
||||||
|
let spec = LinkSpec {
|
||||||
|
id: claims.id,
|
||||||
|
epoch: claims.epoch,
|
||||||
|
expires_at: claims.expires_at,
|
||||||
|
prefix: &claims.prefix,
|
||||||
|
password: claims.password.then_some(""),
|
||||||
|
};
|
||||||
|
let p = payload(&spec);
|
||||||
|
let tag = hmac::sign(&key.0, &session_message(host, &p));
|
||||||
|
let mut raw = p;
|
||||||
|
raw.extend_from_slice(tag.as_ref());
|
||||||
|
format!("{SESSION_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check a session cookie value for `host`.
|
||||||
|
pub fn verify_session(
|
||||||
|
key: &ShareKey,
|
||||||
|
host: &str,
|
||||||
|
value: &str,
|
||||||
|
now: u64,
|
||||||
|
revocations: &Revocations,
|
||||||
|
) -> Result<Claims, Rejection> {
|
||||||
|
let (claims, p, mac) = decode(value, SESSION_PREFIX)?;
|
||||||
|
hmac::verify(&key.0, &session_message(host, &p), &mac).map_err(|_| Rejection::Invalid)?;
|
||||||
|
finish(claims, now, revocations)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Normalise and check a path prefix: starts with `/`, at most [`MAX_PREFIX_LEN`] bytes, only
|
||||||
|
/// unreserved characters and `!$&'()*+,=:@-._~`, no `%`, `;`, backslash, empty segment or dot
|
||||||
|
/// segment. A trailing `/` is dropped (except for `/` itself).
|
||||||
|
pub fn check_prefix(prefix: &str) -> Result<String, &'static str> {
|
||||||
|
if !prefix.starts_with('/') {
|
||||||
|
return Err("it must start with /");
|
||||||
|
}
|
||||||
|
if prefix.len() > MAX_PREFIX_LEN {
|
||||||
|
return Err("it is longer than 256 characters");
|
||||||
|
}
|
||||||
|
let ok = |c: u8| c.is_ascii_alphanumeric() || b"/!$&'()*+,=:@-._~".contains(&c);
|
||||||
|
if !prefix.bytes().all(ok) {
|
||||||
|
return Err("only letters, digits, / and -._~!$&'()*+,=:@ are allowed");
|
||||||
|
}
|
||||||
|
if prefix.contains("//") {
|
||||||
|
return Err("it has an empty segment (//)");
|
||||||
|
}
|
||||||
|
let trimmed = if prefix.len() > 1 {
|
||||||
|
prefix.strip_suffix('/').unwrap_or(prefix)
|
||||||
|
} else {
|
||||||
|
prefix
|
||||||
|
};
|
||||||
|
if trimmed == "/" {
|
||||||
|
return Ok("/".into());
|
||||||
|
}
|
||||||
|
for seg in trimmed[1..].split('/') {
|
||||||
|
if seg.is_empty() {
|
||||||
|
return Err("it has an empty segment (//)");
|
||||||
|
}
|
||||||
|
if seg.bytes().all(|c| c == b'.') {
|
||||||
|
return Err("it has a . or .. segment");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(trimmed.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Percent-encodings no plain path needs (lowercased before matching): `.`, `/`, `\`, `%`
|
||||||
|
/// itself (double encoding), NUL, and IIS `%u` escapes.
|
||||||
|
pub const REFUSED_ENCODINGS: &[&str] = &["%2e", "%2f", "%5c", "%25", "%00", "%u"];
|
||||||
|
|
||||||
|
/// ASCII characters a look-alike must not stand for after NFKC normalisation.
|
||||||
|
/// ASCII characters a non-ASCII character must not turn into under NFKC.
|
||||||
|
const STRUCTURAL: &[char] = &['/', '\\', ';', '?', '#', '%'];
|
||||||
|
|
||||||
|
/// Slash and backslash look-alikes NFKC leaves alone (some upstreams still treat them as
|
||||||
|
/// separators): division slash, fraction slash, big solidus, big reverse solidus, set minus,
|
||||||
|
/// reverse solidus operator, box-drawing diagonals.
|
||||||
|
const SLASH_LOOKALIKES: &[char] = &[
|
||||||
|
'\u{2215}', '\u{2044}', '\u{29F8}', '\u{29F9}', '\u{2216}', '\u{29F5}', '\u{2571}', '\u{2572}',
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Unicode's Default_Ignorable_Code_Point (DerivedCoreProperties.txt, Unicode 15).
|
||||||
|
fn default_ignorable(c: char) -> bool {
|
||||||
|
matches!(
|
||||||
|
c as u32,
|
||||||
|
0x00AD
|
||||||
|
| 0x034F
|
||||||
|
| 0x061C
|
||||||
|
| 0x115F..=0x1160
|
||||||
|
| 0x17B4..=0x17B5
|
||||||
|
| 0x180B..=0x180F
|
||||||
|
| 0x200B..=0x200F
|
||||||
|
| 0x202A..=0x202E
|
||||||
|
| 0x2060..=0x206F
|
||||||
|
| 0x3164
|
||||||
|
| 0xFE00..=0xFE0F
|
||||||
|
| 0xFEFF
|
||||||
|
| 0xFFA0
|
||||||
|
| 0xFFF0..=0xFFF8
|
||||||
|
| 0x1BCA0..=0x1BCA3
|
||||||
|
| 0x1D173..=0x1D17A
|
||||||
|
| 0xE0000..=0xE0FFF
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode `%xx` escapes once. `None` for a broken escape.
|
||||||
|
fn percent_decode(raw: &str) -> Option<Vec<u8>> {
|
||||||
|
let b = raw.as_bytes();
|
||||||
|
let mut out = Vec::with_capacity(b.len());
|
||||||
|
let mut i = 0;
|
||||||
|
while i < b.len() {
|
||||||
|
if b[i] == b'%' {
|
||||||
|
let hex = raw.get(i + 1..i + 3)?;
|
||||||
|
// from_str_radix would also take "+f".
|
||||||
|
if !hex.bytes().all(|c| c.is_ascii_hexdigit()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
out.push(u8::from_str_radix(hex, 16).ok()?);
|
||||||
|
i += 3;
|
||||||
|
} else {
|
||||||
|
out.push(b[i]);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Is `raw_path` (the request path exactly as sent, still percent-encoded) under `prefix`?
|
||||||
|
///
|
||||||
|
/// Refused outright, whatever the prefix:
|
||||||
|
/// - anything but visible ASCII, a backslash, an empty segment (`//`);
|
||||||
|
/// - the encodings in [`REFUSED_ENCODINGS`] and broken `%` escapes;
|
||||||
|
/// - escapes that do not decode to valid UTF-8 (this refuses every overlong form, such as
|
||||||
|
/// `%c0%ae`);
|
||||||
|
/// - any encoded character that NFKC normalisation turns into something containing `/`, `\`,
|
||||||
|
/// `;`, `?`, `#`, `%` or a control character (fullwidth and small forms), and the slash
|
||||||
|
/// look-alikes NFKC leaves alone ([`SLASH_LOOKALIKES`]);
|
||||||
|
/// - a segment that NFKC turns into only dots or nothing, after dropping default-ignorable
|
||||||
|
/// characters and combining marks and trimming whitespace (two-dot
|
||||||
|
/// leaders, ellipses, fullwidth dots, look-alike spaces); look-alike dots and spaces inside a
|
||||||
|
/// name with other characters (`Wait….pdf`, an ideographic space) are fine;
|
||||||
|
/// - a segment of only dots, also with `;params` (`..;x`, `..%3b`), and any segment that is
|
||||||
|
/// one or more dots followed by a percent-encoded byte (`..%20`, `..%3f`, `..%23`), since
|
||||||
|
/// some servers trim or decode that into a dot segment.
|
||||||
|
///
|
||||||
|
/// Other paths match on whole segments, case-sensitively: prefix `/a` covers `/a` and `/a/x`,
|
||||||
|
/// not `/ab` or `/A`.
|
||||||
|
pub fn path_within(prefix: &str, raw_path: &str) -> bool {
|
||||||
|
use unicode_normalization::UnicodeNormalization;
|
||||||
|
if !raw_path.starts_with('/')
|
||||||
|
|| !raw_path.bytes().all(|c| c.is_ascii_graphic())
|
||||||
|
|| raw_path.contains('\\')
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let lower = raw_path.to_ascii_lowercase();
|
||||||
|
if REFUSED_ENCODINGS.iter().any(|bad| lower.contains(bad)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// An empty segment anywhere but at the end (a trailing slash) is `//`.
|
||||||
|
if raw_path.contains("//") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(decoded) = percent_decode(raw_path) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Ok(decoded) = String::from_utf8(decoded) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let looks_structural = decoded.chars().filter(|c| !c.is_ascii()).any(|c| {
|
||||||
|
SLASH_LOOKALIKES.contains(&c)
|
||||||
|
|| std::iter::once(c)
|
||||||
|
.nfkc()
|
||||||
|
.any(|n| STRUCTURAL.contains(&n) || n.is_control())
|
||||||
|
});
|
||||||
|
if looks_structural {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Dot segments as an upstream that normalises (NFKC) and trims whitespace would see them.
|
||||||
|
let segments: Vec<&str> = decoded[1..].split('/').collect();
|
||||||
|
for (i, seg) in segments.iter().enumerate() {
|
||||||
|
if seg.is_empty() && i + 1 == segments.len() {
|
||||||
|
continue; // trailing slash
|
||||||
|
}
|
||||||
|
if seg.is_ascii() {
|
||||||
|
continue; // the raw checks below cover ASCII segments
|
||||||
|
}
|
||||||
|
// Invisible characters (default-ignorable code points, combining marks) do not count:
|
||||||
|
// `\u{200B}..` is `..` to a server that drops them.
|
||||||
|
let n: String = seg.nfkc().collect();
|
||||||
|
let visible: String = n
|
||||||
|
.split(';')
|
||||||
|
.next()
|
||||||
|
.unwrap_or("")
|
||||||
|
.chars()
|
||||||
|
.filter(|c| {
|
||||||
|
!default_ignorable(*c) && !unicode_normalization::char::is_combining_mark(*c)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if visible.trim().chars().all(|c| c == '.') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for seg in lower[1..].split('/') {
|
||||||
|
// `..;x` is `..` to Tomcat and friends; `..%3b` is `..;` to servers that decode
|
||||||
|
// before splitting.
|
||||||
|
let seg = seg.replace("%3b", ";");
|
||||||
|
let name = seg.split(';').next().unwrap_or("");
|
||||||
|
let after_dots = name.trim_start_matches('.');
|
||||||
|
if name.starts_with('.') && (after_dots.is_empty() || after_dots.starts_with('%')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if prefix == "/" {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
match raw_path.strip_prefix(prefix) {
|
||||||
|
Some(rest) => rest.is_empty() || rest.starts_with('/'),
|
||||||
|
None => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Unix seconds to calendar dates (UTC), for API timestamps and visitor pages. Pure: the
|
||||||
|
//! caller passes the time in.
|
||||||
|
|
||||||
|
/// Days since 1970-01-01 → (year, month 1–12, day 1–31). Howard Hinnant's `civil_from_days`.
|
||||||
|
fn civil_from_days(days: i64) -> (i64, u32, u32) {
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z.rem_euclid(146_097);
|
||||||
|
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let y = yoe + era * 400;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||||
|
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||||
|
(if m <= 2 { y + 1 } else { y }, m, d)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `2026-11-14T14:20:00Z`.
|
||||||
|
pub fn rfc3339(unix: u64) -> String {
|
||||||
|
let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2);
|
||||||
|
let (y, m, d) = civil_from_days(secs.div_euclid(86_400));
|
||||||
|
let s = secs.rem_euclid(86_400);
|
||||||
|
format!(
|
||||||
|
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
|
||||||
|
s / 3600,
|
||||||
|
(s / 60) % 60,
|
||||||
|
s % 60
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const MONTHS: [&str; 12] = [
|
||||||
|
"January",
|
||||||
|
"February",
|
||||||
|
"March",
|
||||||
|
"April",
|
||||||
|
"May",
|
||||||
|
"June",
|
||||||
|
"July",
|
||||||
|
"August",
|
||||||
|
"September",
|
||||||
|
"October",
|
||||||
|
"November",
|
||||||
|
"December",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// `14 November 2026` (UTC).
|
||||||
|
pub fn long_date(unix: u64) -> String {
|
||||||
|
let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2);
|
||||||
|
let (y, m, d) = civil_from_days(secs.div_euclid(86_400));
|
||||||
|
let month = MONTHS
|
||||||
|
.get(m.saturating_sub(1) as usize)
|
||||||
|
.copied()
|
||||||
|
.unwrap_or("?");
|
||||||
|
format!("{d} {month} {y}")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn known_dates() {
|
||||||
|
assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z");
|
||||||
|
assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z");
|
||||||
|
assert_eq!(rfc3339(1_794_666_000), "2026-11-14T14:20:00Z");
|
||||||
|
assert_eq!(long_date(1_794_666_000), "14 November 2026");
|
||||||
|
assert_eq!(long_date(4_133_980_799), "31 December 2100");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,817 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Parsing and validation of the routes tree. Route files are hostile input: everything is
|
||||||
|
//! checked, every problem becomes a typed [`ValidationError`], nothing panics.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::net::IpAddr;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
|
||||||
|
use crate::error::{ValidationError as E, ValidationErrors, reason as r};
|
||||||
|
use crate::model::{
|
||||||
|
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
|
||||||
|
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model,
|
||||||
|
Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// One route file handed in by the caller (core does no I/O).
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct SourceFile<'a> {
|
||||||
|
pub name: &'a str,
|
||||||
|
pub contents: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ raw file shapes
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct RawSite {
|
||||||
|
#[serde(default)]
|
||||||
|
secrets: Vec<String>,
|
||||||
|
forward_auth: Option<RawForwardAuth>,
|
||||||
|
acme: Option<RawAcme>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct RawForwardAuth {
|
||||||
|
url: String,
|
||||||
|
copy_headers: Option<Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct RawAcme {
|
||||||
|
email: Option<String>,
|
||||||
|
directory: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
enum RawTls {
|
||||||
|
#[default]
|
||||||
|
Letsencrypt,
|
||||||
|
Domi,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
enum RawAuth {
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
ForwardAuth,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
enum RawAccessLog {
|
||||||
|
#[default]
|
||||||
|
Off,
|
||||||
|
Truncated,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
enum RawAction {
|
||||||
|
Set,
|
||||||
|
Remove,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct RawRule {
|
||||||
|
action: RawAction,
|
||||||
|
name: String,
|
||||||
|
value: Option<String>,
|
||||||
|
secret: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct RawHealthCheck {
|
||||||
|
path: String,
|
||||||
|
/// Signed so that 0 and negative numbers get a typed error instead of a serde one.
|
||||||
|
#[serde(default = "default_interval")]
|
||||||
|
interval_secs: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_interval() -> i64 {
|
||||||
|
10
|
||||||
|
}
|
||||||
|
|
||||||
|
fn yes() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct RawHost {
|
||||||
|
hostname: String,
|
||||||
|
upstreams: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
tls: RawTls,
|
||||||
|
#[serde(default)]
|
||||||
|
auth: RawAuth,
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
websockets: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
share_links: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
access_log: RawAccessLog,
|
||||||
|
health_check: Option<RawHealthCheck>,
|
||||||
|
#[serde(default)]
|
||||||
|
request_headers: Vec<RawRule>,
|
||||||
|
#[serde(default)]
|
||||||
|
response_headers: Vec<RawRule>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ entry point
|
||||||
|
|
||||||
|
/// Parse and validate the site file and every host file. Returns every problem found, or the
|
||||||
|
/// model with hosts sorted by hostname. File order does not matter.
|
||||||
|
pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, ValidationErrors> {
|
||||||
|
let mut errors = Vec::new();
|
||||||
|
|
||||||
|
let site_model = match parse::<RawSite>(site) {
|
||||||
|
Ok(raw) => check_site(site.name, raw, &mut errors),
|
||||||
|
Err(e) => {
|
||||||
|
errors.push(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Stable order: by file name. Duplicate file names are an error of their own.
|
||||||
|
let mut files: Vec<&SourceFile<'_>> = hosts.iter().collect();
|
||||||
|
files.sort_by(|a, b| a.name.cmp(b.name));
|
||||||
|
let mut seen_files = BTreeSet::new();
|
||||||
|
let mut checked = Vec::new();
|
||||||
|
for f in files {
|
||||||
|
if !seen_files.insert(f.name) {
|
||||||
|
errors.push(E::DuplicateFile {
|
||||||
|
file: f.name.to_owned(),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match parse::<RawHost>(f) {
|
||||||
|
Ok(raw) => {
|
||||||
|
if let Some(h) = check_host(f.name, raw, site_model.as_ref(), &mut errors) {
|
||||||
|
checked.push(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => errors.push(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut by_name: BTreeMap<Hostname, Host> = BTreeMap::new();
|
||||||
|
for h in checked {
|
||||||
|
if let Some(first) = by_name.get(&h.hostname) {
|
||||||
|
errors.push(E::DuplicateHostname {
|
||||||
|
hostname: h.hostname.to_string(),
|
||||||
|
first: first.source.clone(),
|
||||||
|
second: h.source.clone(),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
by_name.insert(h.hostname.clone(), h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match site_model {
|
||||||
|
Some(site) if errors.is_empty() => Ok(Model {
|
||||||
|
site,
|
||||||
|
hosts: by_name.into_values().collect(),
|
||||||
|
}),
|
||||||
|
_ => Err(ValidationErrors(errors)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ TOML → raw
|
||||||
|
|
||||||
|
fn parse<T: DeserializeOwned>(f: &SourceFile<'_>) -> Result<T, E> {
|
||||||
|
let file = f.name.to_owned();
|
||||||
|
if f.contents.len() > MAX_FILE_BYTES {
|
||||||
|
return Err(E::FileTooLarge {
|
||||||
|
file,
|
||||||
|
max: MAX_FILE_BYTES,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// A plain table parse first tells syntax errors apart from schema errors.
|
||||||
|
if let Err(e) = toml::from_str::<toml::Table>(f.contents) {
|
||||||
|
return Err(E::Syntax {
|
||||||
|
file,
|
||||||
|
line: e.span().map(|s| line_of(f.contents, s.start)),
|
||||||
|
message: e.message().trim().to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
toml::from_str::<T>(f.contents).map_err(|e| classify(file, e.message()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn line_of(text: &str, offset: usize) -> usize {
|
||||||
|
text.get(..offset).map_or(0, |t| t.matches('\n').count()) + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turn serde's standard messages into typed errors.
|
||||||
|
fn classify(file: String, message: &str) -> E {
|
||||||
|
let message = message.trim();
|
||||||
|
let quoted = |prefix: &str| -> Option<String> {
|
||||||
|
let rest = message.strip_prefix(prefix)?;
|
||||||
|
let end = rest.find('`')?;
|
||||||
|
Some(rest[..end].to_owned())
|
||||||
|
};
|
||||||
|
if let Some(field) = quoted("unknown field `") {
|
||||||
|
E::UnknownField { file, field }
|
||||||
|
} else if let Some(field) = quoted("missing field `") {
|
||||||
|
E::MissingField { file, field }
|
||||||
|
} else {
|
||||||
|
E::InvalidValue {
|
||||||
|
file,
|
||||||
|
message: message.to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ site file
|
||||||
|
|
||||||
|
fn check_site(file: &str, raw: RawSite, errors: &mut Vec<E>) -> Option<Site> {
|
||||||
|
let before = errors.len();
|
||||||
|
let mut secrets = BTreeSet::new();
|
||||||
|
for name in raw.secrets {
|
||||||
|
if valid_secret_name(&name) {
|
||||||
|
secrets.insert(SecretName(name));
|
||||||
|
} else {
|
||||||
|
errors.push(E::InvalidSecretName {
|
||||||
|
file: file.to_owned(),
|
||||||
|
name,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let forward_auth = raw.forward_auth.and_then(|fa| {
|
||||||
|
let bad = |reason| E::BadForwardAuth {
|
||||||
|
file: file.to_owned(),
|
||||||
|
reason,
|
||||||
|
};
|
||||||
|
let (upstream, path_and_query) = match parse_url(&fa.url, true) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(reason) => {
|
||||||
|
errors.push(bad(reason));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let copy_headers: Vec<String> = match fa.copy_headers {
|
||||||
|
Some(h) => h,
|
||||||
|
None => AUTHELIA_COPY_HEADERS
|
||||||
|
.iter()
|
||||||
|
.map(|s| (*s).to_owned())
|
||||||
|
.collect(),
|
||||||
|
};
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
for h in ©_headers {
|
||||||
|
if !valid_header_name(h) {
|
||||||
|
errors.push(E::InvalidHeaderName {
|
||||||
|
file: file.to_owned(),
|
||||||
|
name: h.clone(),
|
||||||
|
field: "forward_auth.copy_headers".into(),
|
||||||
|
});
|
||||||
|
} else if is_protected(h) {
|
||||||
|
errors.push(E::ProtectedHeader {
|
||||||
|
file: file.to_owned(),
|
||||||
|
header: h.clone(),
|
||||||
|
field: "forward_auth.copy_headers".into(),
|
||||||
|
});
|
||||||
|
} else if !seen.insert(h.to_ascii_lowercase()) {
|
||||||
|
errors.push(bad("copy_headers lists a header twice"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(ForwardAuth {
|
||||||
|
upstream,
|
||||||
|
path_and_query,
|
||||||
|
copy_headers,
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
let acme = match raw.acme {
|
||||||
|
None => Acme {
|
||||||
|
email: None,
|
||||||
|
directory: LETSENCRYPT_PRODUCTION.to_owned(),
|
||||||
|
},
|
||||||
|
Some(a) => {
|
||||||
|
let bad = |reason| E::BadAcme {
|
||||||
|
file: file.to_owned(),
|
||||||
|
reason,
|
||||||
|
};
|
||||||
|
if a.email.as_deref().is_some_and(|e| !valid_email(e)) {
|
||||||
|
errors.push(bad("email is not a plain address like admin@example.org"));
|
||||||
|
}
|
||||||
|
let directory = a
|
||||||
|
.directory
|
||||||
|
.unwrap_or_else(|| LETSENCRYPT_PRODUCTION.to_owned());
|
||||||
|
if !valid_acme_directory(&directory) {
|
||||||
|
errors.push(bad(
|
||||||
|
"directory must be an https:// URL without credentials or fragment",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Acme {
|
||||||
|
email: a.email,
|
||||||
|
directory,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
(errors.len() == before).then_some(Site {
|
||||||
|
secrets,
|
||||||
|
forward_auth,
|
||||||
|
acme,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_secret_name(n: &str) -> bool {
|
||||||
|
let b = n.as_bytes();
|
||||||
|
!b.is_empty()
|
||||||
|
&& b.len() <= 64
|
||||||
|
&& (b[0].is_ascii_lowercase() || b[0].is_ascii_digit())
|
||||||
|
&& b.iter()
|
||||||
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'_' || *c == b'-')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_email(e: &str) -> bool {
|
||||||
|
let Some((local, domain)) = e.split_once('@') else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
!local.is_empty()
|
||||||
|
&& e.len() <= 254
|
||||||
|
&& check_hostname(domain).is_ok()
|
||||||
|
&& local
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_graphic() && !b"{}@<>\"\\,;:[]()".contains(&c))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_acme_directory(d: &str) -> bool {
|
||||||
|
match url::Url::parse(d) {
|
||||||
|
Ok(u) => {
|
||||||
|
u.scheme() == "https"
|
||||||
|
&& u.username().is_empty()
|
||||||
|
&& u.password().is_none()
|
||||||
|
&& u.fragment().is_none()
|
||||||
|
&& u.host().is_some()
|
||||||
|
&& d.bytes()
|
||||||
|
.all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}')
|
||||||
|
}
|
||||||
|
Err(_) => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ host files
|
||||||
|
|
||||||
|
fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>) -> Option<Host> {
|
||||||
|
let before = errors.len();
|
||||||
|
let f = || file.to_owned();
|
||||||
|
|
||||||
|
match check_hostname(&raw.hostname) {
|
||||||
|
Err(reason) => errors.push(E::InvalidHostname {
|
||||||
|
file: f(),
|
||||||
|
hostname: raw.hostname.clone(),
|
||||||
|
reason,
|
||||||
|
}),
|
||||||
|
Ok(()) => {
|
||||||
|
// One TOML per host, named after it: exactly `hosts/<hostname>.toml`.
|
||||||
|
if file != format!("hosts/{}.toml", raw.hostname) {
|
||||||
|
errors.push(E::FileNameMismatch {
|
||||||
|
file: f(),
|
||||||
|
hostname: raw.hostname.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if raw.upstreams.is_empty() {
|
||||||
|
errors.push(E::NoUpstreams { file: f() });
|
||||||
|
}
|
||||||
|
if raw.upstreams.len() > MAX_UPSTREAMS {
|
||||||
|
errors.push(E::TooManyUpstreams {
|
||||||
|
file: f(),
|
||||||
|
max: MAX_UPSTREAMS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut upstreams: Vec<Upstream> = Vec::new();
|
||||||
|
let mut seen_upstreams = BTreeSet::new();
|
||||||
|
for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() {
|
||||||
|
match parse_url(u, false) {
|
||||||
|
Ok((up, _)) => {
|
||||||
|
if seen_upstreams.insert(up.clone()) {
|
||||||
|
upstreams.push(up);
|
||||||
|
} else {
|
||||||
|
errors.push(E::DuplicateUpstream {
|
||||||
|
file: f(),
|
||||||
|
url: shown_url(u),
|
||||||
|
index,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(reason) => errors.push(E::BadUpstreamUrl {
|
||||||
|
file: f(),
|
||||||
|
url: shown_url(u),
|
||||||
|
reason,
|
||||||
|
index: Some(index),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if upstreams.windows(2).any(|w| w[0].scheme != w[1].scheme) {
|
||||||
|
errors.push(E::BadUpstreamUrl {
|
||||||
|
file: f(),
|
||||||
|
url: raw
|
||||||
|
.upstreams
|
||||||
|
.iter()
|
||||||
|
.map(|u| shown_url(u))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", "),
|
||||||
|
reason: r::URL_MIXED,
|
||||||
|
index: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let auth = match raw.auth {
|
||||||
|
RawAuth::None => AuthMode::None,
|
||||||
|
RawAuth::ForwardAuth => AuthMode::ForwardAuth,
|
||||||
|
};
|
||||||
|
if auth == AuthMode::ForwardAuth && site.is_some_and(|s| s.forward_auth.is_none()) {
|
||||||
|
errors.push(E::ForwardAuthNotConfigured { file: f() });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identity headers (Authelia's four, plus any configured copy header) must not be
|
||||||
|
// overridable by a rule on a forward-auth host.
|
||||||
|
let identity: Vec<String> = match auth {
|
||||||
|
AuthMode::ForwardAuth => {
|
||||||
|
let extra = site
|
||||||
|
.and_then(|s| s.forward_auth.as_ref())
|
||||||
|
.map(|fa| fa.copy_headers.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
AUTHELIA_COPY_HEADERS
|
||||||
|
.iter()
|
||||||
|
.map(|h| (*h).to_owned())
|
||||||
|
.chain(extra)
|
||||||
|
.map(|h| h.to_ascii_lowercase())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
AuthMode::None => Vec::new(),
|
||||||
|
};
|
||||||
|
let request_headers = check_rules(
|
||||||
|
file,
|
||||||
|
"request_headers",
|
||||||
|
raw.request_headers,
|
||||||
|
&identity,
|
||||||
|
site,
|
||||||
|
errors,
|
||||||
|
);
|
||||||
|
let response_headers = check_rules(
|
||||||
|
file,
|
||||||
|
"response_headers",
|
||||||
|
raw.response_headers,
|
||||||
|
&[],
|
||||||
|
site,
|
||||||
|
errors,
|
||||||
|
);
|
||||||
|
|
||||||
|
let health_check = raw.health_check.and_then(|hc| {
|
||||||
|
let bad = |reason| E::BadHealthCheck { file: f(), reason };
|
||||||
|
let ok_path = hc.path.starts_with('/')
|
||||||
|
&& hc.path.len() <= 1024
|
||||||
|
&& hc
|
||||||
|
.path
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c));
|
||||||
|
if !ok_path {
|
||||||
|
errors.push(bad(r::HEALTH_PATH));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match u32::try_from(hc.interval_secs) {
|
||||||
|
Ok(i) if (1..=3600).contains(&i) => Some(HealthCheck {
|
||||||
|
path: hc.path,
|
||||||
|
interval_secs: i,
|
||||||
|
}),
|
||||||
|
_ => {
|
||||||
|
errors.push(bad(r::HEALTH_INTERVAL));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if errors.len() != before {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(Host {
|
||||||
|
hostname: Hostname(raw.hostname),
|
||||||
|
source: f(),
|
||||||
|
upstreams,
|
||||||
|
tls: match raw.tls {
|
||||||
|
RawTls::Letsencrypt => TlsMode::LetsEncrypt,
|
||||||
|
RawTls::Domi => TlsMode::Domi,
|
||||||
|
},
|
||||||
|
auth,
|
||||||
|
request_headers,
|
||||||
|
response_headers,
|
||||||
|
websockets: raw.websockets,
|
||||||
|
health_check,
|
||||||
|
share_links: raw.share_links,
|
||||||
|
access_log: match raw.access_log {
|
||||||
|
RawAccessLog::Off => AccessLog::Off,
|
||||||
|
RawAccessLog::Truncated => AccessLog::Truncated,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Headers the proxy manages itself (framing, hop-by-hop, forwarding metadata).
|
||||||
|
const PROTECTED: [&str; 14] = [
|
||||||
|
"host",
|
||||||
|
"content-length",
|
||||||
|
"transfer-encoding",
|
||||||
|
"connection",
|
||||||
|
"upgrade",
|
||||||
|
"keep-alive",
|
||||||
|
"te",
|
||||||
|
"trailer",
|
||||||
|
"proxy-connection",
|
||||||
|
"x-forwarded-for",
|
||||||
|
"x-forwarded-proto",
|
||||||
|
"x-forwarded-host",
|
||||||
|
"x-forwarded-method",
|
||||||
|
"x-forwarded-uri",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn is_protected(name: &str) -> bool {
|
||||||
|
PROTECTED.iter().any(|p| p.eq_ignore_ascii_case(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_rules(
|
||||||
|
file: &str,
|
||||||
|
list: &str,
|
||||||
|
raw: Vec<RawRule>,
|
||||||
|
identity: &[String],
|
||||||
|
site: Option<&Site>,
|
||||||
|
errors: &mut Vec<E>,
|
||||||
|
) -> Vec<HeaderRule> {
|
||||||
|
let request = list == "request_headers";
|
||||||
|
let f = || file.to_owned();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
for (i, r) in raw.into_iter().enumerate() {
|
||||||
|
let at = |part: &str| {
|
||||||
|
if part.is_empty() {
|
||||||
|
format!("{list}[{i}]")
|
||||||
|
} else {
|
||||||
|
format!("{list}[{i}].{part}")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let header = r.name.clone();
|
||||||
|
if !valid_header_name(&r.name) {
|
||||||
|
errors.push(E::InvalidHeaderName {
|
||||||
|
file: f(),
|
||||||
|
name: r.name,
|
||||||
|
field: at("name"),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let lower = r.name.to_ascii_lowercase();
|
||||||
|
if is_protected(&r.name) || identity.contains(&lower) {
|
||||||
|
errors.push(E::ProtectedHeader {
|
||||||
|
file: f(),
|
||||||
|
header,
|
||||||
|
field: at("name"),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !seen.insert(lower) {
|
||||||
|
errors.push(E::DuplicateHeaderRule {
|
||||||
|
file: f(),
|
||||||
|
header,
|
||||||
|
field: at("name"),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let bad = |reason| E::BadHeaderRule {
|
||||||
|
file: f(),
|
||||||
|
header: header.clone(),
|
||||||
|
reason,
|
||||||
|
field: at(if reason == r::RULE_NEITHER {
|
||||||
|
"value"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
match (r.action, r.value, r.secret) {
|
||||||
|
(RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }),
|
||||||
|
(RawAction::Remove, _, _) => errors.push(bad(r::RULE_REMOVE_VALUE)),
|
||||||
|
(RawAction::Set, Some(_), Some(_)) => errors.push(bad(r::RULE_BOTH)),
|
||||||
|
(RawAction::Set, None, None) => errors.push(bad(r::RULE_NEITHER)),
|
||||||
|
(RawAction::Set, Some(v), None) => match check_header_value(&v) {
|
||||||
|
Ok(()) => out.push(HeaderRule::Set {
|
||||||
|
name: r.name,
|
||||||
|
value: HeaderValue::Literal(v),
|
||||||
|
}),
|
||||||
|
Err(reason) => errors.push(E::InvalidHeaderValue {
|
||||||
|
file: f(),
|
||||||
|
header,
|
||||||
|
reason,
|
||||||
|
field: at("value"),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
(RawAction::Set, None, Some(s)) => {
|
||||||
|
if !request {
|
||||||
|
errors.push(E::SecretInResponseHeader {
|
||||||
|
file: f(),
|
||||||
|
header,
|
||||||
|
field: at(""),
|
||||||
|
});
|
||||||
|
} else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) {
|
||||||
|
errors.push(E::UndefinedSecret {
|
||||||
|
file: f(),
|
||||||
|
secret: s,
|
||||||
|
field: at("secret"),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
out.push(HeaderRule::Set {
|
||||||
|
name: r.name,
|
||||||
|
value: HeaderValue::Secret(SecretName(s)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RFC 9110 token minus `*`, which is a wildcard in Caddy's header operations but a literal
|
||||||
|
/// character in edge; allowing it would let the engines disagree.
|
||||||
|
fn valid_header_name(n: &str) -> bool {
|
||||||
|
!n.is_empty()
|
||||||
|
&& n.len() <= 256
|
||||||
|
&& n.bytes()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || b"!#$%&'+-.^_`|~".contains(&c))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_header_value(v: &str) -> Result<(), &'static str> {
|
||||||
|
if v.is_empty() {
|
||||||
|
return Err(r::VALUE_EMPTY);
|
||||||
|
}
|
||||||
|
if v.len() > 4096 {
|
||||||
|
return Err(r::VALUE_LONG);
|
||||||
|
}
|
||||||
|
if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) {
|
||||||
|
return Err(r::VALUE_ASCII);
|
||||||
|
}
|
||||||
|
if v.contains(['{', '}']) {
|
||||||
|
return Err(r::VALUE_BRACES);
|
||||||
|
}
|
||||||
|
if v.starts_with(' ') || v.ends_with(' ') {
|
||||||
|
return Err(r::VALUE_EDGE_SPACE);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ names and URLs
|
||||||
|
|
||||||
|
pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> {
|
||||||
|
if h.is_empty() {
|
||||||
|
return Err(r::HOST_EMPTY);
|
||||||
|
}
|
||||||
|
if h.len() > 253 {
|
||||||
|
return Err(r::HOST_TOO_LONG);
|
||||||
|
}
|
||||||
|
if h.parse::<IpAddr>().is_ok() || h.starts_with('[') {
|
||||||
|
return Err(r::HOST_IP);
|
||||||
|
}
|
||||||
|
if h.contains('*') {
|
||||||
|
return Err(r::HOST_WILDCARD);
|
||||||
|
}
|
||||||
|
if h.contains(char::is_whitespace) {
|
||||||
|
return Err(r::HOST_SPACES);
|
||||||
|
}
|
||||||
|
if h.ends_with('.') {
|
||||||
|
return Err(r::HOST_TRAILING_DOT);
|
||||||
|
}
|
||||||
|
if h.bytes().any(|c| c.is_ascii_uppercase()) {
|
||||||
|
return Err(r::HOST_UPPERCASE);
|
||||||
|
}
|
||||||
|
let mut last = "";
|
||||||
|
for label in h.split('.') {
|
||||||
|
if label.is_empty() {
|
||||||
|
return Err(r::HOST_EMPTY_LABEL);
|
||||||
|
}
|
||||||
|
if label.len() > 63 {
|
||||||
|
return Err(r::HOST_LABEL_LONG);
|
||||||
|
}
|
||||||
|
if !label
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
|
||||||
|
{
|
||||||
|
return Err(r::HOST_CHARACTERS);
|
||||||
|
}
|
||||||
|
if label.starts_with('-') || label.ends_with('-') {
|
||||||
|
return Err(r::HOST_LABEL_DASH);
|
||||||
|
}
|
||||||
|
last = label;
|
||||||
|
}
|
||||||
|
if last.bytes().all(|c| c.is_ascii_digit()) {
|
||||||
|
return Err(r::HOST_NUMERIC);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse an http(s) URL into an upstream. With `allow_path`, also returns path and query
|
||||||
|
/// (for the forward-auth endpoint); otherwise any path other than `/` is rejected.
|
||||||
|
fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static str> {
|
||||||
|
if !raw.bytes().all(|c| c.is_ascii_graphic()) {
|
||||||
|
return Err(r::URL_ASCII);
|
||||||
|
}
|
||||||
|
let u = url::Url::parse(raw).map_err(|_| r::URL_NOT_URL)?;
|
||||||
|
let scheme = match u.scheme() {
|
||||||
|
"http" => Scheme::Http,
|
||||||
|
"https" => Scheme::Https,
|
||||||
|
_ => return Err(r::URL_SCHEME),
|
||||||
|
};
|
||||||
|
if !u.username().is_empty() || u.password().is_some() {
|
||||||
|
return Err(r::URL_CREDENTIALS);
|
||||||
|
}
|
||||||
|
if u.fragment().is_some() {
|
||||||
|
return Err(r::URL_FRAGMENT);
|
||||||
|
}
|
||||||
|
let host = match u.host() {
|
||||||
|
None => return Err(r::URL_NO_HOST),
|
||||||
|
Some(url::Host::Ipv4(ip)) => UpstreamHost::Ip(IpAddr::V4(ip)),
|
||||||
|
Some(url::Host::Ipv6(ip)) => UpstreamHost::Ip(IpAddr::V6(ip)),
|
||||||
|
Some(url::Host::Domain(d)) => {
|
||||||
|
if check_hostname(d).is_err() {
|
||||||
|
return Err(r::URL_HOST_NAME);
|
||||||
|
}
|
||||||
|
UpstreamHost::Name(d.to_owned())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let port = u.port_or_known_default().ok_or(r::URL_NO_PORT)?;
|
||||||
|
if port == 0 {
|
||||||
|
return Err(r::URL_PORT_ZERO);
|
||||||
|
}
|
||||||
|
let mut path = u.path().to_owned();
|
||||||
|
if !allow_path {
|
||||||
|
if path != "/" && !path.is_empty() {
|
||||||
|
return Err(r::URL_PATH);
|
||||||
|
}
|
||||||
|
if u.query().is_some() {
|
||||||
|
return Err(r::URL_QUERY);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if let Some(q) = u.query() {
|
||||||
|
path.push('?');
|
||||||
|
path.push_str(q);
|
||||||
|
}
|
||||||
|
if path.contains(['{', '}']) {
|
||||||
|
return Err(r::URL_BRACES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((Upstream { scheme, host, port }, path))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A URL as an error may show it: everything before the last `@` (after the scheme) is
|
||||||
|
/// replaced by `…`, so a user name or password, even one containing `/`, `?` or `#`, never
|
||||||
|
/// reaches a message, a log or the API. A URL with no `@` is shown as it is.
|
||||||
|
pub(crate) fn shown_url(raw: &str) -> String {
|
||||||
|
let (scheme, rest) = match raw.find("://") {
|
||||||
|
Some(i) => (&raw[..i + 3], &raw[i + 3..]),
|
||||||
|
None => ("", raw),
|
||||||
|
};
|
||||||
|
match rest.rfind('@') {
|
||||||
|
Some(at) => format!("{scheme}\u{2026}@{}", &rest[at + 1..]),
|
||||||
|
None => raw.to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod shown_tests {
|
||||||
|
use super::shown_url;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn userinfo_is_hidden() {
|
||||||
|
assert_eq!(
|
||||||
|
shown_url("http://user:hunter2@10.0.0.1:80/x"),
|
||||||
|
"http://\u{2026}@10.0.0.1:80/x"
|
||||||
|
);
|
||||||
|
assert_eq!(shown_url("user:hunter2@host:80"), "\u{2026}@host:80");
|
||||||
|
assert_eq!(shown_url("http://10.0.0.1:80"), "http://10.0.0.1:80");
|
||||||
|
assert_eq!(shown_url("http://h/a@b"), "http://\u{2026}@b");
|
||||||
|
assert_eq!(
|
||||||
|
shown_url("http://admin:hunter/2@10.0.0.1:80"),
|
||||||
|
"http://\u{2026}@10.0.0.1:80"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
shown_url("http://admin:hunter?2@10.0.0.1:80"),
|
||||||
|
"http://\u{2026}@10.0.0.1:80"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
shown_url("http://admin:hunter#2@10.0.0.1:80"),
|
||||||
|
"http://\u{2026}@10.0.0.1:80"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Compiler tests: both compilers are deterministic (byte-identical output for the same model,
|
||||||
|
//! whatever the file order), never embed secret values, and match the reviewed golden files.
|
||||||
|
//! Regenerate the golden files after an intended change with `IANITOR_UPDATE_GOLDEN=1`.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use ianitor_core::compile::{self, CompileError, CompileOptions};
|
||||||
|
use ianitor_core::edge_config::EdgeConfig;
|
||||||
|
use ianitor_core::{Model, SourceFile, load};
|
||||||
|
|
||||||
|
fn fixtures() -> PathBuf {
|
||||||
|
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/routes")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read(p: &Path) -> String {
|
||||||
|
std::fs::read_to_string(p).unwrap().replace("\r\n", "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (file name, contents) for every host file, in directory order or reversed.
|
||||||
|
fn host_files(reverse: bool) -> Vec<(String, String)> {
|
||||||
|
let mut files: Vec<_> = std::fs::read_dir(fixtures().join("hosts"))
|
||||||
|
.unwrap()
|
||||||
|
.map(|e| e.unwrap().path())
|
||||||
|
.collect();
|
||||||
|
files.sort();
|
||||||
|
if reverse {
|
||||||
|
files.reverse();
|
||||||
|
}
|
||||||
|
files
|
||||||
|
.into_iter()
|
||||||
|
.map(|p| {
|
||||||
|
(
|
||||||
|
format!("hosts/{}", p.file_name().unwrap().to_string_lossy()),
|
||||||
|
read(&p),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn model(reverse: bool) -> Model {
|
||||||
|
let site = read(&fixtures().join("ianitor.toml"));
|
||||||
|
let files = host_files(reverse);
|
||||||
|
let sources: Vec<SourceFile> = files
|
||||||
|
.iter()
|
||||||
|
.map(|(n, c)| SourceFile {
|
||||||
|
name: n,
|
||||||
|
contents: c,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: &site,
|
||||||
|
},
|
||||||
|
&sources,
|
||||||
|
)
|
||||||
|
.expect("fixtures are valid")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn options() -> CompileOptions {
|
||||||
|
CompileOptions {
|
||||||
|
http_listen: "0.0.0.0:80".parse().unwrap(),
|
||||||
|
https_listen: "0.0.0.0:443".parse().unwrap(),
|
||||||
|
cert_dir: "/var/lib/ianitor/certs".into(),
|
||||||
|
state_dir: "/var/lib/ianitor".into(),
|
||||||
|
access_log: "/var/log/ianitor/access.log".into(),
|
||||||
|
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
|
||||||
|
caddy_admin: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn edge_compiler_is_deterministic() {
|
||||||
|
let m = model(false);
|
||||||
|
let first = compile::edge(&m, &options()).unwrap();
|
||||||
|
for _ in 0..50 {
|
||||||
|
assert_eq!(first, compile::edge(&m, &options()).unwrap());
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
first,
|
||||||
|
compile::edge(&model(true), &options()).unwrap(),
|
||||||
|
"file order must not matter"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn caddy_compiler_is_deterministic() {
|
||||||
|
let m = model(false);
|
||||||
|
let first = compile::caddy(&m, &options()).unwrap();
|
||||||
|
for _ in 0..50 {
|
||||||
|
assert_eq!(first, compile::caddy(&m, &options()).unwrap());
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
first,
|
||||||
|
compile::caddy(&model(true), &options()).unwrap(),
|
||||||
|
"file order must not matter"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn determinism_holds_across_threads() {
|
||||||
|
let outputs: Vec<(String, String)> = std::thread::scope(|s| {
|
||||||
|
let handles: Vec<_> = (0..8)
|
||||||
|
.map(|i| {
|
||||||
|
s.spawn(move || {
|
||||||
|
let m = model(i % 2 == 0);
|
||||||
|
(
|
||||||
|
compile::edge(&m, &options()).unwrap(),
|
||||||
|
compile::caddy(&m, &options()).unwrap(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||||
|
});
|
||||||
|
for o in &outputs {
|
||||||
|
assert_eq!(o, &outputs[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn edge_output_round_trips_through_the_edge_schema() {
|
||||||
|
let text = compile::edge(&model(false), &options()).unwrap();
|
||||||
|
let cfg: EdgeConfig = serde_json::from_str(&text).unwrap();
|
||||||
|
assert_eq!(cfg.hosts.len(), 3);
|
||||||
|
let again = serde_json::to_string_pretty(&cfg).unwrap() + "\n";
|
||||||
|
assert_eq!(text, again);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn edge_config_rejects_unknown_fields() {
|
||||||
|
let text = compile::edge(&model(false), &options()).unwrap();
|
||||||
|
let mut v: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||||
|
v["surprise"] = serde_json::json!(true);
|
||||||
|
assert!(serde_json::from_value::<EdgeConfig>(v).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn caddy_output_is_valid_json_with_servers() {
|
||||||
|
let text = compile::caddy(&model(false), &options()).unwrap();
|
||||||
|
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||||
|
assert!(v["apps"]["http"]["servers"].is_object());
|
||||||
|
assert_eq!(v["admin"]["disabled"], serde_json::json!(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outputs_reference_secrets_by_name_only() {
|
||||||
|
let edge = compile::edge(&model(false), &options()).unwrap();
|
||||||
|
let caddy = compile::caddy(&model(false), &options()).unwrap();
|
||||||
|
assert!(
|
||||||
|
edge.contains("\"photos_api_key\""),
|
||||||
|
"edge config names the secret"
|
||||||
|
);
|
||||||
|
assert!(caddy.contains("{file./run/credentials/caddy-fallback.service/photos_api_key}"));
|
||||||
|
// The compilers never see secret values, so nothing secret-shaped can be in the output.
|
||||||
|
for out in [&edge, &caddy] {
|
||||||
|
assert!(!out.contains("BEGIN"), "no key material");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_relative_paths_in_options() {
|
||||||
|
let mut o = options();
|
||||||
|
o.cert_dir = "certs".into();
|
||||||
|
assert!(matches!(
|
||||||
|
compile::edge(&model(false), &o),
|
||||||
|
Err(CompileError::BadOption { .. })
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
compile::caddy(&model(false), &o),
|
||||||
|
Err(CompileError::BadOption { .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_path_options_that_would_break_out_of_json_or_placeholders() {
|
||||||
|
for bad in ["/run/x}y", "/run/{x", "/run/a\nb"] {
|
||||||
|
let mut o = options();
|
||||||
|
o.caddy_credentials_dir = bad.into();
|
||||||
|
assert!(compile::caddy(&model(false), &o).is_err(), "{bad:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn golden(name: &str, actual: &str) {
|
||||||
|
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.join("tests/golden")
|
||||||
|
.join(name);
|
||||||
|
if std::env::var_os("IANITOR_UPDATE_GOLDEN").is_some() {
|
||||||
|
std::fs::write(&path, actual).unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let expected = read(&path);
|
||||||
|
assert!(
|
||||||
|
expected == actual,
|
||||||
|
"{name} differs from the golden file; review and rerun with IANITOR_UPDATE_GOLDEN=1.\n--- actual ---\n{actual}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn edge_output_matches_golden_file() {
|
||||||
|
golden(
|
||||||
|
"edge.json",
|
||||||
|
&compile::edge(&model(false), &options()).unwrap(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn caddy_output_matches_golden_file() {
|
||||||
|
golden(
|
||||||
|
"caddy.json",
|
||||||
|
&compile::caddy(&model(false), &options()).unwrap(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn forward_auth_hosts_strip_client_identity_headers_in_both_engines() {
|
||||||
|
let m = model(false);
|
||||||
|
let edge: EdgeConfig = serde_json::from_str(&compile::edge(&m, &options()).unwrap()).unwrap();
|
||||||
|
let strip = edge.forward_auth.unwrap().strip_headers;
|
||||||
|
for h in [
|
||||||
|
"Remote-User",
|
||||||
|
"Remote-Groups",
|
||||||
|
"Remote-Email",
|
||||||
|
"Remote-Name",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
strip.iter().any(|s| s.eq_ignore_ascii_case(h)),
|
||||||
|
"edge strips {h}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let caddy = compile::caddy(&m, &options()).unwrap();
|
||||||
|
let v: serde_json::Value = serde_json::from_str(&caddy).unwrap();
|
||||||
|
let routes = v["apps"]["http"]["servers"]["ianitor_https"]["routes"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap();
|
||||||
|
let wiki = routes
|
||||||
|
.iter()
|
||||||
|
.find(|r| r["match"][0]["host"][0] == "wiki.home.test")
|
||||||
|
.unwrap();
|
||||||
|
let steps = wiki["handle"][0]["routes"].as_array().unwrap();
|
||||||
|
let first = &steps[0]["handle"][0];
|
||||||
|
assert_eq!(
|
||||||
|
first["handler"], "headers",
|
||||||
|
"identity headers are deleted before forward_auth"
|
||||||
|
);
|
||||||
|
let deleted: Vec<&str> = first["request"]["delete"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|d| d.as_str().unwrap())
|
||||||
|
.collect();
|
||||||
|
for h in [
|
||||||
|
"Remote-User",
|
||||||
|
"Remote-Groups",
|
||||||
|
"Remote-Email",
|
||||||
|
"Remote-Name",
|
||||||
|
] {
|
||||||
|
assert!(deleted.contains(&h), "caddy deletes {h}: {deleted:?}");
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
steps[1]["handle"][0]["handler"], "reverse_proxy",
|
||||||
|
"then forward_auth"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn websocket_refusal_in_caddy_matches_any_upgrade_token() {
|
||||||
|
let caddy = compile::caddy(&model(false), &options()).unwrap();
|
||||||
|
assert!(
|
||||||
|
caddy.contains(r#"(?i)(^|,)\\s*websocket\\s*(,|$)"#),
|
||||||
|
"token-aware Upgrade matcher"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
hostname = "photos.example.org"
|
||||||
|
upstreams = ["http://127.0.0.1:2342", "http://127.0.0.1:2343"]
|
||||||
|
tls = "letsencrypt"
|
||||||
|
websockets = true
|
||||||
|
access_log = "truncated"
|
||||||
|
|
||||||
|
[health_check]
|
||||||
|
path = "/api/v1/status"
|
||||||
|
interval_secs = 15
|
||||||
|
|
||||||
|
[[request_headers]]
|
||||||
|
action = "set"
|
||||||
|
name = "X-Api-Key"
|
||||||
|
secret = "photos_api_key"
|
||||||
|
|
||||||
|
[[request_headers]]
|
||||||
|
action = "remove"
|
||||||
|
name = "X-Debug"
|
||||||
|
|
||||||
|
[[response_headers]]
|
||||||
|
action = "set"
|
||||||
|
name = "Strict-Transport-Security"
|
||||||
|
value = "max-age=31536000"
|
||||||
|
|
||||||
|
[[response_headers]]
|
||||||
|
action = "remove"
|
||||||
|
name = "X-Powered-By"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
hostname = "status.example.org"
|
||||||
|
upstreams = ["http://[::1]:3001"]
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
hostname = "wiki.home.test"
|
||||||
|
upstreams = ["https://wiki.lan:8443"]
|
||||||
|
tls = "domi"
|
||||||
|
auth = "forward-auth"
|
||||||
|
websockets = false
|
||||||
|
|
||||||
|
[[request_headers]]
|
||||||
|
action = "set"
|
||||||
|
name = "Authorization"
|
||||||
|
secret = "wiki_token"
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Site-wide settings for the routes repo (sample used by the compiler tests).
|
||||||
|
secrets = ["photos_api_key", "wiki_token"]
|
||||||
|
|
||||||
|
[forward_auth]
|
||||||
|
url = "http://127.0.0.1:9091/api/authz/forward-auth"
|
||||||
|
|
||||||
|
[acme]
|
||||||
|
email = "admin@example.org"
|
||||||
|
directory = "https://acme-staging-v02.api.letsencrypt.org/directory"
|
||||||
@@ -0,0 +1,573 @@
|
|||||||
|
{
|
||||||
|
"admin": {
|
||||||
|
"disabled": true
|
||||||
|
},
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"http_port": 80,
|
||||||
|
"https_port": 443,
|
||||||
|
"servers": {
|
||||||
|
"ianitor_http": {
|
||||||
|
"automatic_https": {
|
||||||
|
"disable_redirects": true
|
||||||
|
},
|
||||||
|
"listen": [
|
||||||
|
"0.0.0.0:80"
|
||||||
|
],
|
||||||
|
"protocols": [
|
||||||
|
"h1"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "static_response",
|
||||||
|
"headers": {
|
||||||
|
"Location": [
|
||||||
|
"https://{http.request.host}{http.request.uri}"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"status_code": 308
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"photos.example.org",
|
||||||
|
"status.example.org",
|
||||||
|
"wiki.home.test"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "static_response",
|
||||||
|
"status_code": 404
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"ianitor_https": {
|
||||||
|
"automatic_https": {
|
||||||
|
"disable_redirects": true,
|
||||||
|
"skip_certificates": [
|
||||||
|
"wiki.home.test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"listen": [
|
||||||
|
"0.0.0.0:443"
|
||||||
|
],
|
||||||
|
"logs": {
|
||||||
|
"logger_names": {
|
||||||
|
"photos.example.org": [
|
||||||
|
"ianitor_access"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"skip_unmapped_hosts": true
|
||||||
|
},
|
||||||
|
"protocols": [
|
||||||
|
"h1",
|
||||||
|
"h2"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "reverse_proxy",
|
||||||
|
"headers": {
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"X-Debug"
|
||||||
|
],
|
||||||
|
"set": {
|
||||||
|
"X-Api-Key": [
|
||||||
|
"{file./run/credentials/caddy-fallback.service/photos_api_key}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"response": {
|
||||||
|
"delete": [
|
||||||
|
"X-Powered-By"
|
||||||
|
],
|
||||||
|
"set": {
|
||||||
|
"Strict-Transport-Security": [
|
||||||
|
"max-age=31536000"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"health_checks": {
|
||||||
|
"active": {
|
||||||
|
"interval": "15s",
|
||||||
|
"timeout": "5s",
|
||||||
|
"uri": "/api/v1/status"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"load_balancing": {
|
||||||
|
"selection_policy": {
|
||||||
|
"policy": "round_robin"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"dial": "127.0.0.1:2342"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"dial": "127.0.0.1:2343"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"photos.example.org"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "reverse_proxy",
|
||||||
|
"load_balancing": {
|
||||||
|
"selection_policy": {
|
||||||
|
"policy": "round_robin"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"dial": "[::1]:3001"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"status.example.org"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"Remote-User",
|
||||||
|
"Remote-Groups",
|
||||||
|
"Remote-Email",
|
||||||
|
"Remote-Name"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handle_response": [
|
||||||
|
{
|
||||||
|
"match": {
|
||||||
|
"status_code": [
|
||||||
|
2
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "vars"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"Remote-User"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Remote-User": [
|
||||||
|
"{http.reverse_proxy.header.Remote-User}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"not": [
|
||||||
|
{
|
||||||
|
"vars": {
|
||||||
|
"{http.reverse_proxy.header.Remote-User}": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"Remote-Groups"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Remote-Groups": [
|
||||||
|
"{http.reverse_proxy.header.Remote-Groups}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"not": [
|
||||||
|
{
|
||||||
|
"vars": {
|
||||||
|
"{http.reverse_proxy.header.Remote-Groups}": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"Remote-Email"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Remote-Email": [
|
||||||
|
"{http.reverse_proxy.header.Remote-Email}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"not": [
|
||||||
|
{
|
||||||
|
"vars": {
|
||||||
|
"{http.reverse_proxy.header.Remote-Email}": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"Remote-Name"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Remote-Name": [
|
||||||
|
"{http.reverse_proxy.header.Remote-Name}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"not": [
|
||||||
|
{
|
||||||
|
"vars": {
|
||||||
|
"{http.reverse_proxy.header.Remote-Name}": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handler": "reverse_proxy",
|
||||||
|
"headers": {
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"X-Forwarded-Method": [
|
||||||
|
"{http.request.method}"
|
||||||
|
],
|
||||||
|
"X-Forwarded-Uri": [
|
||||||
|
"{http.request.uri}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"rewrite": {
|
||||||
|
"method": "GET",
|
||||||
|
"uri": "/api/authz/forward-auth"
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"dial": "127.0.0.1:9091"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "static_response",
|
||||||
|
"status_code": 403
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"header_regexp": {
|
||||||
|
"Upgrade": {
|
||||||
|
"pattern": "(?i)(^|,)\\s*websocket\\s*(,|$)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "reverse_proxy",
|
||||||
|
"headers": {
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Authorization": [
|
||||||
|
"{file./run/credentials/caddy-fallback.service/wiki_token}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"load_balancing": {
|
||||||
|
"selection_policy": {
|
||||||
|
"policy": "round_robin"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"transport": {
|
||||||
|
"protocol": "http",
|
||||||
|
"tls": {}
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"dial": "wiki.lan:8443"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"wiki.home.test"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "static_response",
|
||||||
|
"status_code": 404
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"tls_connection_policies": [
|
||||||
|
{
|
||||||
|
"certificate_selection": {
|
||||||
|
"any_tag": [
|
||||||
|
"ianitor:wiki.home.test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"match": {
|
||||||
|
"sni": [
|
||||||
|
"wiki.home.test"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"tls": {
|
||||||
|
"automation": {
|
||||||
|
"policies": [
|
||||||
|
{
|
||||||
|
"issuers": [
|
||||||
|
{
|
||||||
|
"ca": "https://acme-staging-v02.api.letsencrypt.org/directory",
|
||||||
|
"email": "admin@example.org",
|
||||||
|
"module": "acme"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjects": [
|
||||||
|
"photos.example.org",
|
||||||
|
"status.example.org"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"certificates": {
|
||||||
|
"load_files": [
|
||||||
|
{
|
||||||
|
"certificate": "/var/lib/ianitor/certs/wiki.home.test.crt",
|
||||||
|
"key": "/var/lib/ianitor/certs/wiki.home.test.key",
|
||||||
|
"tags": [
|
||||||
|
"ianitor:wiki.home.test"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"logging": {
|
||||||
|
"logs": {
|
||||||
|
"default": {
|
||||||
|
"exclude": [
|
||||||
|
"http.log.access.ianitor_access"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"ianitor_access": {
|
||||||
|
"encoder": {
|
||||||
|
"fields": {
|
||||||
|
"request>client_ip": {
|
||||||
|
"filter": "ip_mask",
|
||||||
|
"ipv4_cidr": 24,
|
||||||
|
"ipv6_cidr": 48
|
||||||
|
},
|
||||||
|
"request>headers": {
|
||||||
|
"filter": "delete"
|
||||||
|
},
|
||||||
|
"request>remote_ip": {
|
||||||
|
"filter": "ip_mask",
|
||||||
|
"ipv4_cidr": 24,
|
||||||
|
"ipv6_cidr": 48
|
||||||
|
},
|
||||||
|
"request>remote_port": {
|
||||||
|
"filter": "delete"
|
||||||
|
},
|
||||||
|
"request>tls": {
|
||||||
|
"filter": "delete"
|
||||||
|
},
|
||||||
|
"request>uri": {
|
||||||
|
"filter": "regexp",
|
||||||
|
"regexp": "\\?.*$",
|
||||||
|
"value": ""
|
||||||
|
},
|
||||||
|
"resp_headers": {
|
||||||
|
"filter": "delete"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"format": "filter",
|
||||||
|
"wrap": {
|
||||||
|
"format": "json"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"http.log.access.ianitor_access"
|
||||||
|
],
|
||||||
|
"writer": {
|
||||||
|
"filename": "/var/log/ianitor/access.log",
|
||||||
|
"output": "file"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"storage": {
|
||||||
|
"module": "file_system",
|
||||||
|
"root": "/var/lib/ianitor/caddy"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
{
|
||||||
|
"version": 2,
|
||||||
|
"http_listen": "0.0.0.0:80",
|
||||||
|
"https_listen": "0.0.0.0:443",
|
||||||
|
"https_port": 443,
|
||||||
|
"cert_dir": "/var/lib/ianitor/certs",
|
||||||
|
"state_dir": "/var/lib/ianitor",
|
||||||
|
"access_log": "/var/log/ianitor/access.log",
|
||||||
|
"acme": {
|
||||||
|
"directory": "https://acme-staging-v02.api.letsencrypt.org/directory",
|
||||||
|
"email": "admin@example.org"
|
||||||
|
},
|
||||||
|
"forward_auth": {
|
||||||
|
"upstream": {
|
||||||
|
"address": "127.0.0.1:9091",
|
||||||
|
"tls": false,
|
||||||
|
"sni": "127.0.0.1"
|
||||||
|
},
|
||||||
|
"path_and_query": "/api/authz/forward-auth",
|
||||||
|
"copy_headers": [
|
||||||
|
"Remote-User",
|
||||||
|
"Remote-Groups",
|
||||||
|
"Remote-Email",
|
||||||
|
"Remote-Name"
|
||||||
|
],
|
||||||
|
"strip_headers": [
|
||||||
|
"Remote-User",
|
||||||
|
"Remote-Groups",
|
||||||
|
"Remote-Email",
|
||||||
|
"Remote-Name"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hosts": [
|
||||||
|
{
|
||||||
|
"hostname": "photos.example.org",
|
||||||
|
"tls": {
|
||||||
|
"source": "acme"
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"address": "127.0.0.1:2342",
|
||||||
|
"tls": false,
|
||||||
|
"sni": "127.0.0.1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"address": "127.0.0.1:2343",
|
||||||
|
"tls": false,
|
||||||
|
"sni": "127.0.0.1"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"forward_auth": false,
|
||||||
|
"websockets": true,
|
||||||
|
"request_headers": [
|
||||||
|
{
|
||||||
|
"op": "set",
|
||||||
|
"name": "X-Api-Key",
|
||||||
|
"value": {
|
||||||
|
"kind": "secret",
|
||||||
|
"name": "photos_api_key"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"op": "remove",
|
||||||
|
"name": "X-Debug"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"response_headers": [
|
||||||
|
{
|
||||||
|
"op": "set",
|
||||||
|
"name": "Strict-Transport-Security",
|
||||||
|
"value": {
|
||||||
|
"kind": "literal",
|
||||||
|
"value": "max-age=31536000"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"op": "remove",
|
||||||
|
"name": "X-Powered-By"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"health_check": {
|
||||||
|
"path": "/api/v1/status",
|
||||||
|
"interval_secs": 15
|
||||||
|
},
|
||||||
|
"access_log": true,
|
||||||
|
"share_links": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"hostname": "status.example.org",
|
||||||
|
"tls": {
|
||||||
|
"source": "acme"
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"address": "[::1]:3001",
|
||||||
|
"tls": false,
|
||||||
|
"sni": "::1"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"forward_auth": false,
|
||||||
|
"websockets": true,
|
||||||
|
"request_headers": [],
|
||||||
|
"response_headers": [],
|
||||||
|
"health_check": null,
|
||||||
|
"access_log": false,
|
||||||
|
"share_links": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"hostname": "wiki.home.test",
|
||||||
|
"tls": {
|
||||||
|
"source": "files",
|
||||||
|
"cert": "/var/lib/ianitor/certs/wiki.home.test.crt",
|
||||||
|
"key": "/var/lib/ianitor/certs/wiki.home.test.key"
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"address": "wiki.lan:8443",
|
||||||
|
"tls": true,
|
||||||
|
"sni": "wiki.lan"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"forward_auth": true,
|
||||||
|
"websockets": false,
|
||||||
|
"request_headers": [
|
||||||
|
{
|
||||||
|
"op": "set",
|
||||||
|
"name": "Authorization",
|
||||||
|
"value": {
|
||||||
|
"kind": "secret",
|
||||||
|
"name": "wiki_token"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"response_headers": [],
|
||||||
|
"health_check": null,
|
||||||
|
"access_log": false,
|
||||||
|
"share_links": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -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 routes repository holds exactly `ianitor.toml` and `hosts/<hostname>.toml`, and the
|
||||||
|
//! loader requires the exact path (ROADMAP §10: the check used to look at the base name only).
|
||||||
|
//! Validation errors carry a stable code, a field path and params for the UI (docs/ui-api.md §3.1).
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use ianitor_core::routes::{EntryKind, RoutePath, check_path, check_tree};
|
||||||
|
use ianitor_core::{SourceFile, ValidationError, load};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_site_file_and_host_files_are_allowed() {
|
||||||
|
assert_eq!(
|
||||||
|
check_path("ianitor.toml", EntryKind::File).unwrap(),
|
||||||
|
RoutePath::Site
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
check_path("hosts/wiki.home.test.toml", EntryKind::File).unwrap(),
|
||||||
|
RoutePath::Host {
|
||||||
|
hostname: "wiki.home.test".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
for bad in [
|
||||||
|
"README.md",
|
||||||
|
".gitattributes",
|
||||||
|
"hosts.toml",
|
||||||
|
"other/wiki.home.test.toml",
|
||||||
|
"hosts/sub/wiki.home.test.toml",
|
||||||
|
"hosts/wiki.home.test.toml/x",
|
||||||
|
"hosts/Wiki.home.test.toml",
|
||||||
|
"hosts/wiki.home.test.TOML",
|
||||||
|
"hosts/wiki.home.test",
|
||||||
|
"hosts/.toml",
|
||||||
|
"hosts/*.home.test.toml",
|
||||||
|
"hosts/wiki..test.toml",
|
||||||
|
"hosts/10.0.0.1.toml",
|
||||||
|
"hosts/wiki home.toml",
|
||||||
|
"hosts\\wiki.home.test.toml",
|
||||||
|
"hosts/wiki\\x.toml",
|
||||||
|
"IANITOR.toml",
|
||||||
|
"./ianitor.toml",
|
||||||
|
] {
|
||||||
|
let e = check_path(bad, EntryKind::File).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::UnexpectedFile { ref file, .. } if file == bad),
|
||||||
|
"{bad}: {e:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(e.code(), "repo.unexpected_file");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn links_executables_and_submodules_are_refused() {
|
||||||
|
for kind in [
|
||||||
|
EntryKind::Symlink,
|
||||||
|
EntryKind::Submodule,
|
||||||
|
EntryKind::Executable,
|
||||||
|
] {
|
||||||
|
assert!(check_path("hosts/a.test.toml", kind).is_err(), "{kind:?}");
|
||||||
|
assert!(check_path("ianitor.toml", kind).is_err(), "{kind:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tree_needs_the_site_file_and_reports_every_stray_file() {
|
||||||
|
let ok = [
|
||||||
|
("ianitor.toml", EntryKind::File),
|
||||||
|
("hosts/a.test.toml", EntryKind::File),
|
||||||
|
];
|
||||||
|
assert!(check_tree(ok).is_ok());
|
||||||
|
let errs = check_tree([
|
||||||
|
("hosts/a.test.toml", EntryKind::File),
|
||||||
|
("notes.txt", EntryKind::File),
|
||||||
|
("hosts/b/c.toml", EntryKind::File),
|
||||||
|
])
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(errs.len(), 3, "{errs:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_loader_requires_the_exact_path() {
|
||||||
|
let site = SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
};
|
||||||
|
let body = "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n";
|
||||||
|
for name in [
|
||||||
|
"app.test.toml",
|
||||||
|
"other/app.test.toml",
|
||||||
|
"hosts/x/app.test.toml",
|
||||||
|
"hosts\\app.test.toml",
|
||||||
|
"./hosts/app.test.toml",
|
||||||
|
] {
|
||||||
|
let errs = load(
|
||||||
|
&site,
|
||||||
|
&[SourceFile {
|
||||||
|
name,
|
||||||
|
contents: body,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
errs.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::FileNameMismatch { .. })),
|
||||||
|
"{name}: {errs:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
load(
|
||||||
|
&site,
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: body
|
||||||
|
}]
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn errors_for(body: &str) -> Vec<ValidationError> {
|
||||||
|
let site = SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "secrets = [\"api_key\"]\n",
|
||||||
|
};
|
||||||
|
load(
|
||||||
|
&site,
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: body,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.unwrap_err()
|
||||||
|
.into_errors()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn errors_have_codes_fields_and_params_for_the_ui() {
|
||||||
|
let cases: &[(&str, &str, Option<&str>)] = &[
|
||||||
|
(
|
||||||
|
"upstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
"host.hostname.missing",
|
||||||
|
Some("hostname"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\n",
|
||||||
|
"host.upstreams.missing",
|
||||||
|
Some("upstreams"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
"host.hostname.uppercase",
|
||||||
|
Some("hostname"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
"host.hostname.spaces",
|
||||||
|
Some("hostname"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"ftp://x\"]\n",
|
||||||
|
"host.upstream.scheme",
|
||||||
|
Some("upstreams[1]"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1/x\"]\n",
|
||||||
|
"host.upstream.path",
|
||||||
|
Some("upstreams[0]"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"http://127.0.0.1:1\"]\n",
|
||||||
|
"host.upstream.duplicate",
|
||||||
|
Some("upstreams[1]"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"https://127.0.0.1:2\"]\n",
|
||||||
|
"host.upstream.mixed_schemes",
|
||||||
|
Some("upstreams"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ncolour = 1\n",
|
||||||
|
"host.field.unknown",
|
||||||
|
Some("colour"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"set\"\nname = \"Host\"\nvalue = \"x\"\n",
|
||||||
|
"host.header.protected",
|
||||||
|
Some("request_headers[1].name"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n",
|
||||||
|
"host.header.secret_response",
|
||||||
|
Some("response_headers[0]"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"nope\"\n",
|
||||||
|
"host.header.secret_unknown",
|
||||||
|
Some("request_headers[0].secret"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[health_check]\npath = \"/x\"\ninterval_secs = 0\n",
|
||||||
|
"host.health.interval",
|
||||||
|
Some("health_check.interval_secs"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\nauth = \"forward-auth\"\n",
|
||||||
|
"host.auth.not_configured",
|
||||||
|
Some("auth"),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (body, code, field) in cases {
|
||||||
|
let errs = errors_for(body);
|
||||||
|
let e = errs
|
||||||
|
.iter()
|
||||||
|
.find(|e| e.code() == *code)
|
||||||
|
.unwrap_or_else(|| panic!("no {code} for {body:?}: {errs:?}"));
|
||||||
|
assert_eq!(e.field().as_deref(), *field, "{code}");
|
||||||
|
assert_eq!(e.params()["file"], "hosts/app.test.toml");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn params_carry_suggestions() {
|
||||||
|
let errs = errors_for("hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n");
|
||||||
|
let e = errs
|
||||||
|
.iter()
|
||||||
|
.find(|e| e.code() == "host.hostname.uppercase")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(e.params()["suggestion"], "app.test");
|
||||||
|
let errs = errors_for("hostname = \"app.test\"\nupstreams = [\"http://10.0.0.2:3000/app\"]\n");
|
||||||
|
let e = errs
|
||||||
|
.iter()
|
||||||
|
.find(|e| e.code() == "host.upstream.path")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(e.params()["suggestion"], "http://10.0.0.2:3000");
|
||||||
|
assert_eq!(e.params()["url"], "http://10.0.0.2:3000/app");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_password_in_an_upstream_url_is_never_repeated() {
|
||||||
|
let errs = errors_for(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://admin:hunter2@10.0.0.2:3000\", \"ftp://u:hunter2@x\", \"http://admin:hunter2@10.0.0.2:3000\"]\n",
|
||||||
|
);
|
||||||
|
assert!(!errs.is_empty());
|
||||||
|
for e in &errs {
|
||||||
|
let all = format!("{e} {:?} {:?}", e.params(), e.field());
|
||||||
|
assert!(!all.contains("hunter2"), "{all}");
|
||||||
|
}
|
||||||
|
let e = errs
|
||||||
|
.iter()
|
||||||
|
.find(|e| e.code() == "host.upstream.credentials")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(e.params()["url"], "http://\u{2026}@10.0.0.2:3000");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn credentials_with_slash_query_or_hash_are_never_repeated() {
|
||||||
|
for url in [
|
||||||
|
"http://admin:hunter/2@10.0.0.1:80",
|
||||||
|
"http://admin:hunter?2@10.0.0.1:80",
|
||||||
|
"http://admin:hunter#2@10.0.0.1:80",
|
||||||
|
"ftp://admin:hunter2@10.0.0.1",
|
||||||
|
] {
|
||||||
|
let errs = errors_for(&format!(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"{url}\"]\n"
|
||||||
|
));
|
||||||
|
assert!(!errs.is_empty(), "{url} accepted");
|
||||||
|
for e in &errs {
|
||||||
|
let all = format!("{e} {:?}", e.params());
|
||||||
|
assert!(!all.contains("hunter"), "{url}: {all}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,908 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Schema and validation tests. Route files are hostile input: every rejection must be a
|
||||||
|
//! typed error that names the file, never a panic.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use ianitor_core::{
|
||||||
|
AccessLog, AuthMode, HeaderRule, HeaderValue, SourceFile, TlsMode, ValidationError,
|
||||||
|
ValidationErrors, load,
|
||||||
|
};
|
||||||
|
|
||||||
|
const SITE: &str = r#"
|
||||||
|
secrets = ["api_key", "other-token"]
|
||||||
|
|
||||||
|
[forward_auth]
|
||||||
|
url = "http://127.0.0.1:9091/api/authz/forward-auth"
|
||||||
|
"#;
|
||||||
|
|
||||||
|
fn site() -> SourceFile<'static> {
|
||||||
|
SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: SITE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn one(contents: &str) -> Result<ianitor_core::Model, ValidationErrors> {
|
||||||
|
load(
|
||||||
|
&site(),
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents,
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn errors(contents: &str) -> Vec<ValidationError> {
|
||||||
|
match one(contents) {
|
||||||
|
Ok(_) => panic!("expected validation to fail for:\n{contents}"),
|
||||||
|
Err(e) => e.errors().to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn single_error(contents: &str) -> ValidationError {
|
||||||
|
let errs = errors(contents);
|
||||||
|
assert_eq!(errs.len(), 1, "expected exactly one error, got {errs:#?}");
|
||||||
|
errs.into_iter().next().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
const MINIMAL: &str = r#"
|
||||||
|
hostname = "app.test"
|
||||||
|
upstreams = ["http://127.0.0.1:8080"]
|
||||||
|
"#;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- accepted input
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn minimal_host_gets_documented_defaults() {
|
||||||
|
let model = one(MINIMAL).expect("minimal host is valid");
|
||||||
|
let hosts = model.hosts();
|
||||||
|
assert_eq!(hosts.len(), 1);
|
||||||
|
let h = &hosts[0];
|
||||||
|
assert_eq!(h.hostname.as_str(), "app.test");
|
||||||
|
assert_eq!(h.source, "hosts/app.test.toml");
|
||||||
|
assert_eq!(h.tls, TlsMode::LetsEncrypt);
|
||||||
|
assert_eq!(h.auth, AuthMode::None);
|
||||||
|
assert!(h.websockets, "websockets default on, like Caddy");
|
||||||
|
assert!(!h.share_links);
|
||||||
|
assert_eq!(h.access_log, AccessLog::Off);
|
||||||
|
assert!(h.health_check.is_none());
|
||||||
|
assert!(h.request_headers.is_empty() && h.response_headers.is_empty());
|
||||||
|
assert_eq!(h.upstreams.len(), 1);
|
||||||
|
assert_eq!(h.upstreams[0].to_string(), "http://127.0.0.1:8080");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn full_host_is_accepted() {
|
||||||
|
let model = one(r#"
|
||||||
|
hostname = "app.test"
|
||||||
|
upstreams = ["https://127.0.0.1:8443", "https://backend.lan", "https://[::1]:9000/"]
|
||||||
|
tls = "domi"
|
||||||
|
auth = "forward-auth"
|
||||||
|
websockets = false
|
||||||
|
share_links = true
|
||||||
|
access_log = "truncated"
|
||||||
|
|
||||||
|
[health_check]
|
||||||
|
path = "/healthz"
|
||||||
|
interval_secs = 10
|
||||||
|
|
||||||
|
[[request_headers]]
|
||||||
|
action = "set"
|
||||||
|
name = "X-Api-Key"
|
||||||
|
secret = "api_key"
|
||||||
|
|
||||||
|
[[request_headers]]
|
||||||
|
action = "remove"
|
||||||
|
name = "X-Debug"
|
||||||
|
|
||||||
|
[[response_headers]]
|
||||||
|
action = "set"
|
||||||
|
name = "Strict-Transport-Security"
|
||||||
|
value = "max-age=31536000"
|
||||||
|
"#)
|
||||||
|
.expect("full host is valid");
|
||||||
|
let h = &model.hosts()[0];
|
||||||
|
assert_eq!(h.tls, TlsMode::Domi);
|
||||||
|
assert_eq!(h.auth, AuthMode::ForwardAuth);
|
||||||
|
assert!(!h.websockets);
|
||||||
|
assert!(h.share_links);
|
||||||
|
assert_eq!(h.access_log, AccessLog::Truncated);
|
||||||
|
let hc = h.health_check.as_ref().unwrap();
|
||||||
|
assert_eq!(hc.path, "/healthz");
|
||||||
|
assert_eq!(hc.interval_secs, 10);
|
||||||
|
let ups: Vec<String> = h.upstreams.iter().map(|u| u.to_string()).collect();
|
||||||
|
assert_eq!(
|
||||||
|
ups,
|
||||||
|
[
|
||||||
|
"https://127.0.0.1:8443",
|
||||||
|
"https://backend.lan:443",
|
||||||
|
"https://[::1]:9000"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
h.request_headers[0],
|
||||||
|
HeaderRule::Set {
|
||||||
|
name: "X-Api-Key".into(),
|
||||||
|
value: HeaderValue::Secret("api_key".into())
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
h.request_headers[1],
|
||||||
|
HeaderRule::Remove {
|
||||||
|
name: "X-Debug".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
h.response_headers[0],
|
||||||
|
HeaderRule::Set {
|
||||||
|
name: "Strict-Transport-Security".into(),
|
||||||
|
value: HeaderValue::Literal("max-age=31536000".into())
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hosts_are_sorted_by_hostname_whatever_the_file_order() {
|
||||||
|
let a = SourceFile {
|
||||||
|
name: "hosts/b.test.toml",
|
||||||
|
contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
};
|
||||||
|
let b = SourceFile {
|
||||||
|
name: "hosts/a.test.toml",
|
||||||
|
contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
};
|
||||||
|
let m1 = load(&site(), &[a, b]).unwrap();
|
||||||
|
let m2 = load(&site(), &[b, a]).unwrap();
|
||||||
|
let names = |m: &ianitor_core::Model| {
|
||||||
|
m.hosts()
|
||||||
|
.iter()
|
||||||
|
.map(|h| h.hostname.to_string())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
};
|
||||||
|
assert_eq!(names(&m1), ["a.test", "b.test"]);
|
||||||
|
assert_eq!(m1, m2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_site_file_is_allowed() {
|
||||||
|
let m = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(m.is_ok(), "{m:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- unknown fields
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_unknown_top_level_field() {
|
||||||
|
let e = single_error(&format!("{MINIMAL}colour = \"red\"\n"));
|
||||||
|
assert_eq!(
|
||||||
|
e,
|
||||||
|
ValidationError::UnknownField {
|
||||||
|
file: "hosts/app.test.toml".into(),
|
||||||
|
field: "colour".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_misspelled_field() {
|
||||||
|
let e = single_error("hostname = \"app.test\"\nupstream = [\"http://127.0.0.1:1\"]\n");
|
||||||
|
// `upstream` is unknown; it is reported before the missing `upstreams`.
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::UnknownField { ref field, .. } if field == "upstream"),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_unknown_field_in_health_check() {
|
||||||
|
let e = single_error(&format!(
|
||||||
|
"{MINIMAL}[health_check]\npath = \"/h\"\ninterval_secs = 5\ntimeout = 3\n"
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::UnknownField { ref field, .. } if field == "timeout"),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_unknown_field_in_header_rule() {
|
||||||
|
let e = single_error(&format!(
|
||||||
|
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\nappend = true\n"
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::UnknownField { ref field, .. } if field == "append"),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_unknown_field_in_site_file() {
|
||||||
|
let r = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "secrets = []\nsecret_values = { a = \"b\" }\n",
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
let errs = r.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
errs.errors().iter().any(|e| matches!(e, ValidationError::UnknownField { file, field } if file == "ianitor.toml" && field == "secret_values")),
|
||||||
|
"{errs:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_unknown_enum_value() {
|
||||||
|
let e = single_error(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ntls = \"selfsigned\"\n",
|
||||||
|
);
|
||||||
|
assert!(matches!(e, ValidationError::InvalidValue { .. }), "{e:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_wrong_type() {
|
||||||
|
let e = single_error("hostname = \"app.test\"\nupstreams = \"http://127.0.0.1:1\"\n");
|
||||||
|
assert!(matches!(e, ValidationError::InvalidValue { .. }), "{e:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_toml_syntax_error() {
|
||||||
|
let e = single_error("hostname = \"app.test\nupstreams = [\n");
|
||||||
|
assert!(matches!(e, ValidationError::Syntax { .. }), "{e:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- hostnames
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_missing_hostname() {
|
||||||
|
let e = single_error("upstreams = [\"http://127.0.0.1:8080\"]\n");
|
||||||
|
assert_eq!(
|
||||||
|
e,
|
||||||
|
ValidationError::MissingField {
|
||||||
|
file: "hosts/app.test.toml".into(),
|
||||||
|
field: "hostname".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_missing_upstreams() {
|
||||||
|
let e = single_error("hostname = \"app.test\"\n");
|
||||||
|
assert_eq!(
|
||||||
|
e,
|
||||||
|
ValidationError::MissingField {
|
||||||
|
file: "hosts/app.test.toml".into(),
|
||||||
|
field: "upstreams".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_bad_hostnames() {
|
||||||
|
let long_label = format!("{}.test", "a".repeat(64));
|
||||||
|
let long_name = format!("{}test", "abcdefghi.".repeat(26));
|
||||||
|
for bad in [
|
||||||
|
"",
|
||||||
|
"UPPER.test",
|
||||||
|
"-bad.test",
|
||||||
|
"bad-.test",
|
||||||
|
"a..b",
|
||||||
|
"*.wild.test",
|
||||||
|
"1.2.3.4",
|
||||||
|
"[::1]",
|
||||||
|
"has space.test",
|
||||||
|
"under_score.test",
|
||||||
|
"app.test.",
|
||||||
|
".app.test",
|
||||||
|
"app.test:443",
|
||||||
|
long_label.as_str(),
|
||||||
|
long_name.as_str(),
|
||||||
|
"ünicode.test",
|
||||||
|
] {
|
||||||
|
let e = single_error(&format!(
|
||||||
|
"hostname = {bad:?}\nupstreams = [\"http://127.0.0.1:1\"]\n"
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::InvalidHostname { ref hostname, .. } if hostname == bad),
|
||||||
|
"hostname {bad:?} gave {e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn accepts_good_hostnames() {
|
||||||
|
for good in [
|
||||||
|
"localhost",
|
||||||
|
"a.b",
|
||||||
|
"app.test",
|
||||||
|
"x-1.example.org",
|
||||||
|
"0day.example.org",
|
||||||
|
] {
|
||||||
|
let contents = format!("hostname = {good:?}\nupstreams = [\"http://127.0.0.1:1\"]\n");
|
||||||
|
let name = format!("hosts/{good}.toml");
|
||||||
|
let r = load(
|
||||||
|
&site(),
|
||||||
|
&[SourceFile {
|
||||||
|
name: &name,
|
||||||
|
contents: &contents,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(r.is_ok(), "{good}: {r:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_second_file_for_the_same_host_is_refused_by_its_path() {
|
||||||
|
// With the exact `hosts/<hostname>.toml` rule, two files can never hold one hostname:
|
||||||
|
// the second one is in the wrong place, whatever the file order.
|
||||||
|
for order in [false, true] {
|
||||||
|
let mut files = vec![
|
||||||
|
SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
|
SourceFile {
|
||||||
|
name: "other/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
if order {
|
||||||
|
files.reverse();
|
||||||
|
}
|
||||||
|
let errs = load(&site(), &files).unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
errs.errors(),
|
||||||
|
[ValidationError::FileNameMismatch {
|
||||||
|
file: "other/app.test.toml".into(),
|
||||||
|
hostname: "app.test".into()
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_duplicate_source_file_names() {
|
||||||
|
let r = load(
|
||||||
|
&site(),
|
||||||
|
&[
|
||||||
|
SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
|
SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::DuplicateFile { .. }))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- upstreams
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_bad_upstream_urls() {
|
||||||
|
for bad in [
|
||||||
|
"ftp://127.0.0.1:21",
|
||||||
|
"127.0.0.1:8080",
|
||||||
|
"http://",
|
||||||
|
"http://user:pw@127.0.0.1:8080",
|
||||||
|
"http://user@127.0.0.1:8080",
|
||||||
|
"http://127.0.0.1:8080/path",
|
||||||
|
"http://127.0.0.1:8080?q=1",
|
||||||
|
"http://127.0.0.1:8080#frag",
|
||||||
|
"http://127.0.0.1:0",
|
||||||
|
"http://127.0.0.1:99999",
|
||||||
|
"not a url",
|
||||||
|
"",
|
||||||
|
"http://bad_host:80",
|
||||||
|
"unix:///run/app.sock",
|
||||||
|
"http://127.0.0.1:80{x}",
|
||||||
|
] {
|
||||||
|
let e = single_error(&format!("hostname = \"app.test\"\nupstreams = [{bad:?}]\n"));
|
||||||
|
assert!(
|
||||||
|
// Credentials are never repeated in an error.
|
||||||
|
matches!(e, ValidationError::BadUpstreamUrl { ref url, .. }
|
||||||
|
if url == bad || (bad.contains('@') && url == "http://\u{2026}@127.0.0.1:8080")),
|
||||||
|
"upstream {bad:?} gave {e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_mixed_upstream_schemes() {
|
||||||
|
// Caddy has one transport per reverse_proxy handler, so a host cannot mix http and https.
|
||||||
|
let e = single_error(
|
||||||
|
"hostname = \"app.test\"
|
||||||
|
upstreams = [\"http://127.0.0.1:1\", \"https://127.0.0.1:2\"]
|
||||||
|
",
|
||||||
|
);
|
||||||
|
assert!(matches!(e, ValidationError::BadUpstreamUrl { .. }), "{e:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_empty_upstream_list() {
|
||||||
|
let e = single_error("hostname = \"app.test\"\nupstreams = []\n");
|
||||||
|
assert!(matches!(e, ValidationError::NoUpstreams { .. }), "{e:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_duplicate_upstreams() {
|
||||||
|
let e = single_error(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:80\", \"http://127.0.0.1\"]\n",
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::DuplicateUpstream { .. }),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- secrets
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_undefined_secret_reference() {
|
||||||
|
let e = single_error(&format!(
|
||||||
|
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"nope\"\n"
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
e,
|
||||||
|
ValidationError::UndefinedSecret {
|
||||||
|
file: "hosts/app.test.toml".into(),
|
||||||
|
secret: "nope".into(),
|
||||||
|
field: "request_headers[0].secret".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn undefined_secret_is_reported_when_site_declares_none() {
|
||||||
|
let r = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: &format!(
|
||||||
|
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n"
|
||||||
|
),
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::UndefinedSecret { .. }))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_secret_in_response_header() {
|
||||||
|
let e = single_error(&format!(
|
||||||
|
"{MINIMAL}[[response_headers]]\naction = \"set\"\nname = \"X-Leak\"\nsecret = \"api_key\"\n"
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::SecretInResponseHeader { .. }),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_bad_secret_names_in_site_file() {
|
||||||
|
for bad in ["../etc/passwd", "a/b", "", "UPPER", "with space", ".hidden"] {
|
||||||
|
let r = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: &format!("secrets = [{bad:?}]\n"),
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
let errs = r.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
errs.errors().iter().any(
|
||||||
|
|e| matches!(e, ValidationError::InvalidSecretName { name, .. } if name == bad)
|
||||||
|
),
|
||||||
|
"{bad:?}: {errs:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- header rules
|
||||||
|
|
||||||
|
fn rule(list: &str, body: &str) -> String {
|
||||||
|
format!("{MINIMAL}[[{list}]]\n{body}\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_malformed_header_rules() {
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
"set without value",
|
||||||
|
rule("request_headers", "action = \"set\"\nname = \"X-A\""),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"remove with value",
|
||||||
|
rule(
|
||||||
|
"request_headers",
|
||||||
|
"action = \"remove\"\nname = \"X-A\"\nvalue = \"1\"",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"value and secret",
|
||||||
|
rule(
|
||||||
|
"request_headers",
|
||||||
|
"action = \"set\"\nname = \"X-A\"\nvalue = \"1\"\nsecret = \"api_key\"",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (what, input) in cases {
|
||||||
|
let e = single_error(&input);
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::BadHeaderRule { .. }),
|
||||||
|
"{what}: {e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_header_names() {
|
||||||
|
for bad in ["Bad Header", "", "X:Y", "X\nY", "Ä"] {
|
||||||
|
let e = single_error(&rule(
|
||||||
|
"request_headers",
|
||||||
|
&format!("action = \"remove\"\nname = {bad:?}"),
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::InvalidHeaderName { ref name, .. } if name == bad),
|
||||||
|
"{bad:?}: {e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_header_values() {
|
||||||
|
for bad in [
|
||||||
|
"a\nb",
|
||||||
|
"a\rb",
|
||||||
|
"a\u{0}b",
|
||||||
|
"{http.request.host}",
|
||||||
|
"x}",
|
||||||
|
"\u{7f}",
|
||||||
|
" leading",
|
||||||
|
"ü",
|
||||||
|
] {
|
||||||
|
let value = toml::Value::String(bad.to_owned()).to_string();
|
||||||
|
let e = single_error(&rule(
|
||||||
|
"response_headers",
|
||||||
|
&format!("action = \"set\"\nname = \"X-A\"\nvalue = {value}"),
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::InvalidHeaderValue { .. }),
|
||||||
|
"{bad:?}: {e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_protected_headers() {
|
||||||
|
for name in [
|
||||||
|
"Host",
|
||||||
|
"content-length",
|
||||||
|
"Transfer-Encoding",
|
||||||
|
"Connection",
|
||||||
|
"Upgrade",
|
||||||
|
"X-Forwarded-For",
|
||||||
|
"x-forwarded-proto",
|
||||||
|
"X-Forwarded-Host",
|
||||||
|
] {
|
||||||
|
let e = single_error(&rule(
|
||||||
|
"request_headers",
|
||||||
|
&format!("action = \"remove\"\nname = {name:?}"),
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::ProtectedHeader { .. }),
|
||||||
|
"{name}: {e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn identity_headers_are_protected_on_forward_auth_hosts() {
|
||||||
|
let input = format!(
|
||||||
|
"{MINIMAL}auth = \"forward-auth\"\n[[request_headers]]\naction = \"set\"\nname = \"remote-user\"\nvalue = \"admin\"\n"
|
||||||
|
);
|
||||||
|
let e = single_error(&input);
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::ProtectedHeader { .. }),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_duplicate_header_rules_case_insensitively() {
|
||||||
|
let input = format!(
|
||||||
|
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"remove\"\nname = \"x-a\"\n"
|
||||||
|
);
|
||||||
|
let e = single_error(&input);
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::DuplicateHeaderRule { .. }),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- auth and health checks
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn forward_auth_requires_site_configuration() {
|
||||||
|
let r = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"),
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::ForwardAuthNotConfigured { .. }))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_bad_forward_auth_site_config() {
|
||||||
|
for bad in [
|
||||||
|
"ftp://127.0.0.1/x",
|
||||||
|
"http://u:p@127.0.0.1:9091/api",
|
||||||
|
"http://127.0.0.1:9091/api#x",
|
||||||
|
"nope",
|
||||||
|
] {
|
||||||
|
let r = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: &format!("[forward_auth]\nurl = {bad:?}\n"),
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::BadForwardAuth { .. })),
|
||||||
|
"{bad}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_bad_health_checks() {
|
||||||
|
for body in [
|
||||||
|
"path = \"healthz\"\ninterval_secs = 5",
|
||||||
|
"path = \"/h z\"\ninterval_secs = 5",
|
||||||
|
"path = \"/h\"\ninterval_secs = 0",
|
||||||
|
"path = \"/h\"\ninterval_secs = 86401",
|
||||||
|
"path = \"/{x}\"\ninterval_secs = 5",
|
||||||
|
] {
|
||||||
|
let e = single_error(&format!("{MINIMAL}[health_check]\n{body}\n"));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::BadHealthCheck { .. }),
|
||||||
|
"{body}: {e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- reporting
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn collects_errors_from_every_file() {
|
||||||
|
let r = load(
|
||||||
|
&site(),
|
||||||
|
&[
|
||||||
|
SourceFile {
|
||||||
|
name: "hosts/a.test.toml",
|
||||||
|
contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n",
|
||||||
|
},
|
||||||
|
SourceFile {
|
||||||
|
name: "hosts/B.test.toml",
|
||||||
|
contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
},
|
||||||
|
SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let errs = r.unwrap_err();
|
||||||
|
assert_eq!(errs.errors().len(), 2, "{errs:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn error_messages_name_the_file_in_plain_english() {
|
||||||
|
let errs = one("hostname = \"app.test\"\nupstreams = [\"ftp://x\"]\n").unwrap_err();
|
||||||
|
let text = errs.to_string();
|
||||||
|
assert!(text.contains("hosts/app.test.toml"), "{text}");
|
||||||
|
assert!(text.contains("ftp://x"), "{text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn never_panics_on_garbage() {
|
||||||
|
let samples = [
|
||||||
|
"\u{0}\u{1}\u{2}",
|
||||||
|
"[[[[",
|
||||||
|
"hostname = 1",
|
||||||
|
"hostname = [\"a\"]",
|
||||||
|
"= =",
|
||||||
|
"[health_check]\npath = 1",
|
||||||
|
"hostname = \"a.test\"\nupstreams = [1, 2]",
|
||||||
|
"hostname = \"a.test\"\nupstreams = [[]]",
|
||||||
|
"hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\n",
|
||||||
|
"hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\nrequest_headers = 5",
|
||||||
|
];
|
||||||
|
for s in samples {
|
||||||
|
assert!(one(s).is_err(), "{s:?} unexpectedly valid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- QC findings
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn file_name_must_match_the_hostname() {
|
||||||
|
let r = load(
|
||||||
|
&site(),
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/other.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
let errs = r.unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
errs.errors(),
|
||||||
|
[ValidationError::FileNameMismatch {
|
||||||
|
file: "hosts/other.test.toml".into(),
|
||||||
|
hostname: "app.test".into()
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_wildcards_in_header_names() {
|
||||||
|
// Caddy treats `*` in header names as a wildcard; edge does not. Never allowed.
|
||||||
|
for list in ["request_headers", "response_headers"] {
|
||||||
|
for bad in ["*", "X-*", "*-Id", "X-*-Y"] {
|
||||||
|
let e = single_error(&rule(list, &format!("action = \"remove\"\nname = {bad:?}")));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::InvalidHeaderName { ref name, .. } if name == bad),
|
||||||
|
"{list} {bad}: {e:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_wildcards_in_copy_headers() {
|
||||||
|
let r = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "[forward_auth]\nurl = \"http://127.0.0.1:9091/x\"\ncopy_headers = [\"Remote-*\"]\n",
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::InvalidHeaderName { .. }))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_fragment_in_health_check_path() {
|
||||||
|
let e = single_error(&format!(
|
||||||
|
"{MINIMAL}[health_check]\npath = \"/h#x\"\ninterval_secs = 5\n"
|
||||||
|
));
|
||||||
|
assert!(matches!(e, ValidationError::BadHealthCheck { .. }), "{e:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_oversized_route_files() {
|
||||||
|
let big = format!("{MINIMAL}# {}\n", "x".repeat(1 << 20));
|
||||||
|
let e = single_error(&big);
|
||||||
|
assert!(matches!(e, ValidationError::FileTooLarge { .. }), "{e:?}");
|
||||||
|
let r = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: &big,
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(r.unwrap_err().errors().iter().any(
|
||||||
|
|e| matches!(e, ValidationError::FileTooLarge { file, .. } if file == "ianitor.toml")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_too_many_upstreams() {
|
||||||
|
let ups: Vec<String> = (1..=65)
|
||||||
|
.map(|p| format!("\"http://127.0.0.1:{p}\""))
|
||||||
|
.collect();
|
||||||
|
let e = single_error(&format!(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [{}]\n",
|
||||||
|
ups.join(", ")
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::TooManyUpstreams { .. }),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
|
let ups: Vec<String> = (1..=64)
|
||||||
|
.map(|p| format!("\"http://127.0.0.1:{p}\""))
|
||||||
|
.collect();
|
||||||
|
assert!(
|
||||||
|
one(&format!(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [{}]\n",
|
||||||
|
ups.join(", ")
|
||||||
|
))
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn identity_headers_stay_protected_with_a_custom_copy_list() {
|
||||||
|
let site = "[forward_auth]\nurl = \"http://127.0.0.1:9091/x\"\ncopy_headers = [\"X-User\"]\n";
|
||||||
|
for header in ["Remote-User", "remote-email", "X-User"] {
|
||||||
|
let host = format!(
|
||||||
|
"{MINIMAL}auth = \"forward-auth\"\n[[request_headers]]\naction = \"set\"\nname = \"{header}\"\nvalue = \"x\"\n"
|
||||||
|
);
|
||||||
|
let r = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: site,
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents: &host,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::ProtectedHeader { .. })),
|
||||||
|
"{header}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,487 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Share-link tokens (ROADMAP §6 phase 2, tests first): a token is refused when expired, for
|
||||||
|
//! the wrong path, for the wrong host, tampered, without its password or with a wrong one,
|
||||||
|
//! and no path trick lets it escape its prefix.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
use base64::Engine as _;
|
||||||
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||||
|
use ianitor_core::share::{
|
||||||
|
Claims, LinkSpec, Rejection, Revocations, ShareId, ShareKey, check_prefix, mint, path_within,
|
||||||
|
peek, session_value, verify_link, verify_session,
|
||||||
|
};
|
||||||
|
|
||||||
|
const NOW: u64 = 1_800_000_000;
|
||||||
|
const HOST: &str = "photos.home.test";
|
||||||
|
|
||||||
|
fn key() -> ShareKey {
|
||||||
|
ShareKey::new(b"0123456789abcdef0123456789abcdef-test-key").unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn other_key() -> ShareKey {
|
||||||
|
ShareKey::new(b"fedcba9876543210fedcba9876543210-test-key").unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn id(n: u8) -> ShareId {
|
||||||
|
ShareId([n; 16])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spec<'a>(prefix: &'a str, password: Option<&'a str>) -> LinkSpec<'a> {
|
||||||
|
LinkSpec {
|
||||||
|
id: id(7),
|
||||||
|
epoch: 3,
|
||||||
|
expires_at: NOW + 3600,
|
||||||
|
prefix,
|
||||||
|
password,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn none() -> Revocations {
|
||||||
|
Revocations {
|
||||||
|
epoch: 3,
|
||||||
|
deny: BTreeSet::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn token(prefix: &str, password: Option<&str>) -> String {
|
||||||
|
mint(&key(), HOST, &spec(prefix, password)).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_fresh_token_is_accepted_and_says_what_it_covers() {
|
||||||
|
let t = token("/albums/summer", None);
|
||||||
|
assert!(t.starts_with("ish1."), "{t}");
|
||||||
|
let c = verify_link(&key(), HOST, &t, None, NOW, &none()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
c,
|
||||||
|
Claims {
|
||||||
|
id: id(7),
|
||||||
|
epoch: 3,
|
||||||
|
expires_at: NOW + 3600,
|
||||||
|
password: false,
|
||||||
|
prefix: "/albums/summer".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_expired_token_is_refused_as_expired() {
|
||||||
|
let t = token("/", None);
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &t, None, NOW + 3600, &none()),
|
||||||
|
Err(Rejection::Expired {
|
||||||
|
expires_at: NOW + 3600
|
||||||
|
})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &t, None, NOW + 99_999, &none()),
|
||||||
|
Err(Rejection::Expired {
|
||||||
|
expires_at: NOW + 3600
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_token_for_another_host_is_refused() {
|
||||||
|
let t = token("/", None);
|
||||||
|
for host in [
|
||||||
|
"other.home.test",
|
||||||
|
"PHOTOS.home.test",
|
||||||
|
"photos.home.test.",
|
||||||
|
"photos.home",
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), host, &t, None, NOW, &none()),
|
||||||
|
Err(Rejection::Invalid),
|
||||||
|
"{host}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_token_made_with_another_key_is_refused() {
|
||||||
|
let t = mint(&other_key(), HOST, &spec("/", None)).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &t, None, NOW, &none()),
|
||||||
|
Err(Rejection::Invalid)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_single_bit_flip_is_refused() {
|
||||||
|
let t = token("/albums", None);
|
||||||
|
let raw = URL_SAFE_NO_PAD
|
||||||
|
.decode(t.strip_prefix("ish1.").unwrap())
|
||||||
|
.unwrap();
|
||||||
|
for i in 0..raw.len() {
|
||||||
|
for bit in 0..8 {
|
||||||
|
let mut r = raw.clone();
|
||||||
|
r[i] ^= 1 << bit;
|
||||||
|
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&r));
|
||||||
|
let got = verify_link(&key(), HOST, &forged, None, NOW, &none());
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
got,
|
||||||
|
Err(Rejection::Invalid | Rejection::Malformed | Rejection::PasswordRequired)
|
||||||
|
),
|
||||||
|
"byte {i} bit {bit}: {got:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_longer_expiry_or_wider_prefix_cannot_be_spliced_in() {
|
||||||
|
let t = token("/albums/summer", None);
|
||||||
|
let raw = URL_SAFE_NO_PAD
|
||||||
|
.decode(t.strip_prefix("ish1.").unwrap())
|
||||||
|
.unwrap();
|
||||||
|
let (payload, mac) = raw.split_at(raw.len() - 32);
|
||||||
|
// Same MAC, prefix cut down to "/albums".
|
||||||
|
let mut p = payload[..30].to_vec();
|
||||||
|
p.extend_from_slice(b"/albums");
|
||||||
|
p.extend_from_slice(mac);
|
||||||
|
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p));
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &forged, None, NOW, &none()),
|
||||||
|
Err(Rejection::Invalid)
|
||||||
|
);
|
||||||
|
// Same MAC, expiry pushed out.
|
||||||
|
let mut p = payload.to_vec();
|
||||||
|
p[21..29].copy_from_slice(&(NOW + 10 * 3600).to_be_bytes());
|
||||||
|
p.extend_from_slice(mac);
|
||||||
|
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p));
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &forged, None, NOW, &none()),
|
||||||
|
Err(Rejection::Invalid)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn garbage_is_malformed_never_a_panic() {
|
||||||
|
for bad in [
|
||||||
|
"",
|
||||||
|
"ish1.",
|
||||||
|
"ish1.!!!!",
|
||||||
|
"ish2.AAAA",
|
||||||
|
"iss1.AAAA",
|
||||||
|
"ish1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||||
|
&"ish1.".repeat(400),
|
||||||
|
"ish1.\u{0}",
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, bad, None, NOW, &none()),
|
||||||
|
Err(Rejection::Malformed),
|
||||||
|
"{bad:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_password_link_needs_its_password() {
|
||||||
|
let t = token("/", Some("correct horse"));
|
||||||
|
assert!(peek(&t).unwrap().password);
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &t, None, NOW, &none()),
|
||||||
|
Err(Rejection::PasswordRequired)
|
||||||
|
);
|
||||||
|
for wrong in ["", "correct hors", "correct horse ", "Correct horse", "x"] {
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &t, Some(wrong), NOW, &none()),
|
||||||
|
Err(Rejection::Invalid),
|
||||||
|
"{wrong:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap();
|
||||||
|
assert!(c.password);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_token_carries_no_password_hash() {
|
||||||
|
// Two links that differ only in the password have the same payload; only the MAC differs.
|
||||||
|
let a = token("/", Some("password-one"));
|
||||||
|
let b = token("/", Some("password-two"));
|
||||||
|
let ra = URL_SAFE_NO_PAD
|
||||||
|
.decode(a.strip_prefix("ish1.").unwrap())
|
||||||
|
.unwrap();
|
||||||
|
let rb = URL_SAFE_NO_PAD
|
||||||
|
.decode(b.strip_prefix("ish1.").unwrap())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(ra.len(), rb.len());
|
||||||
|
assert_eq!(ra[..ra.len() - 32], rb[..rb.len() - 32]);
|
||||||
|
assert_ne!(ra[ra.len() - 32..], rb[rb.len() - 32..]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_dropped_password_flag_does_not_open_the_link() {
|
||||||
|
let t = token("/", Some("correct horse"));
|
||||||
|
let mut raw = URL_SAFE_NO_PAD
|
||||||
|
.decode(t.strip_prefix("ish1.").unwrap())
|
||||||
|
.unwrap();
|
||||||
|
raw[29] = 0;
|
||||||
|
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&raw));
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &forged, None, NOW, &none()),
|
||||||
|
Err(Rejection::Invalid)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn passwords_are_8_to_128_characters() {
|
||||||
|
assert!(mint(&key(), HOST, &spec("/", Some("short"))).is_err());
|
||||||
|
assert!(mint(&key(), HOST, &spec("/", Some(&"x".repeat(129)))).is_err());
|
||||||
|
assert!(mint(&key(), HOST, &spec("/", Some("12345678"))).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stopped_links_and_older_epochs_are_revoked() {
|
||||||
|
let t = token("/", None);
|
||||||
|
let mut r = none();
|
||||||
|
r.deny.insert(id(7));
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &t, None, NOW, &r),
|
||||||
|
Err(Rejection::Revoked)
|
||||||
|
);
|
||||||
|
let r = Revocations {
|
||||||
|
epoch: 4,
|
||||||
|
deny: BTreeSet::new(),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
verify_link(&key(), HOST, &t, None, NOW, &r),
|
||||||
|
Err(Rejection::Revoked)
|
||||||
|
);
|
||||||
|
// Another link on the deny list does not matter.
|
||||||
|
let mut r = none();
|
||||||
|
r.deny.insert(id(8));
|
||||||
|
assert!(verify_link(&key(), HOST, &t, None, NOW, &r).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn session_cookies_and_link_tokens_are_not_interchangeable() {
|
||||||
|
let t = token("/albums", Some("correct horse"));
|
||||||
|
let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap();
|
||||||
|
let s = session_value(&key(), HOST, &c);
|
||||||
|
assert!(s.starts_with("iss1."));
|
||||||
|
assert_eq!(verify_session(&key(), HOST, &s, NOW, &none()).unwrap(), c);
|
||||||
|
// A cookie is not a link, a link is not a cookie, even with the prefix swapped.
|
||||||
|
assert!(verify_link(&key(), HOST, &s, None, NOW, &none()).is_err());
|
||||||
|
assert!(verify_session(&key(), HOST, &t, NOW, &none()).is_err());
|
||||||
|
let swapped = s.replacen("iss1.", "ish1.", 1);
|
||||||
|
assert!(verify_link(&key(), HOST, &swapped, Some("correct horse"), NOW, &none()).is_err());
|
||||||
|
let swapped = t.replacen("ish1.", "iss1.", 1);
|
||||||
|
assert!(verify_session(&key(), HOST, &swapped, NOW, &none()).is_err());
|
||||||
|
// Cookies are host-bound, expire and are revoked like links.
|
||||||
|
assert_eq!(
|
||||||
|
verify_session(&key(), "other.home.test", &s, NOW, &none()),
|
||||||
|
Err(Rejection::Invalid)
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
verify_session(&key(), HOST, &s, NOW + 3600, &none()),
|
||||||
|
Err(Rejection::Expired { .. })
|
||||||
|
));
|
||||||
|
let mut r = none();
|
||||||
|
r.deny.insert(id(7));
|
||||||
|
assert_eq!(
|
||||||
|
verify_session(&key(), HOST, &s, NOW, &r),
|
||||||
|
Err(Rejection::Revoked)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn short_keys_are_refused() {
|
||||||
|
assert!(ShareKey::new(b"short").is_err());
|
||||||
|
assert!(ShareKey::new(&[0u8; 31]).is_err());
|
||||||
|
assert!(ShareKey::new(&[0u8; 32]).is_ok());
|
||||||
|
assert!(!format!("{:?}", key()).contains("0123"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prefixes_are_normalised_or_refused() {
|
||||||
|
assert_eq!(check_prefix("/").unwrap(), "/");
|
||||||
|
assert_eq!(check_prefix("/a/").unwrap(), "/a");
|
||||||
|
assert_eq!(
|
||||||
|
check_prefix("/albums/summer-2026").unwrap(),
|
||||||
|
"/albums/summer-2026"
|
||||||
|
);
|
||||||
|
for bad in [
|
||||||
|
"", "a", "//", "/a//b", "/a/../b", "/..", "/.", "/a/./b", "/a%2fb", "/a\\b", "/a b",
|
||||||
|
"/a;b", "/ä", "/a?b", "/a#b",
|
||||||
|
] {
|
||||||
|
assert!(check_prefix(bad).is_err(), "{bad:?} accepted");
|
||||||
|
}
|
||||||
|
assert!(check_prefix(&format!("/{}", "a".repeat(256))).is_err());
|
||||||
|
// A prefix that is not in normal form is not minted.
|
||||||
|
assert!(mint(&key(), HOST, &spec("/a/", None)).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ids_round_trip_as_hex() {
|
||||||
|
let i = ShareId([0xab; 16]);
|
||||||
|
assert_eq!(i.to_hex(), "ab".repeat(16));
|
||||||
|
assert_eq!(ShareId::from_hex(&i.to_hex()), Some(i));
|
||||||
|
for bad in [
|
||||||
|
"",
|
||||||
|
"ab",
|
||||||
|
&"AB".repeat(16),
|
||||||
|
&"zz".repeat(16),
|
||||||
|
&"a".repeat(33),
|
||||||
|
] {
|
||||||
|
assert_eq!(ShareId::from_hex(bad), None, "{bad:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ prefix escapes
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paths_under_the_prefix_are_within() {
|
||||||
|
for (prefix, path) in [
|
||||||
|
("/a", "/a"),
|
||||||
|
("/a", "/a/"),
|
||||||
|
("/a", "/a/b"),
|
||||||
|
("/a", "/a/b/c.jpg"),
|
||||||
|
("/a", "/a/b%20c"),
|
||||||
|
("/a", "/a/%E2%9C%93"),
|
||||||
|
("/", "/"),
|
||||||
|
("/", "/anything/at/all"),
|
||||||
|
("/a/b", "/a/b/c"),
|
||||||
|
("/a", "/a/b;v=1"),
|
||||||
|
("/a", "/a/.well"),
|
||||||
|
("/a", "/a/%C3%A9t%C3%A9.jpg"),
|
||||||
|
("/a", "/a/%e2%9c%93"),
|
||||||
|
("/a", "/a/a%20b"),
|
||||||
|
// QC fix round 3: ordinary names with look-alike dots or spaces inside.
|
||||||
|
("/a", "/a/Wait%E2%80%A6.pdf"),
|
||||||
|
("/a", "/a/%E3%80%80photo"),
|
||||||
|
("/a", "/a/my%C2%A0file.pdf"),
|
||||||
|
("/a", "/a/dokumenty/p%C5%99ehled"),
|
||||||
|
("/a", "/a/my%20file.pdf"),
|
||||||
|
("/a", "/a/a+b"),
|
||||||
|
("/a", "/a/caf%C3%A9"),
|
||||||
|
("/a", "/a/cafe%CC%81"),
|
||||||
|
("/a", "/a/%E3%80%80photo%E3%80%80album"),
|
||||||
|
("/a", "/a/e%CC%81"),
|
||||||
|
("/a", "/a/%E2%80%93"),
|
||||||
|
("/a", "/a/%E6%97%85%E8%A1%8C"),
|
||||||
|
("/a", "/a/.well-known/x"),
|
||||||
|
("/a", "/a/%C2%BD.txt"),
|
||||||
|
("/a", "/a/x%3Fy"),
|
||||||
|
] {
|
||||||
|
assert!(path_within(prefix, path), "{prefix} should cover {path}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_path_trick_escapes_the_prefix() {
|
||||||
|
let cases = [
|
||||||
|
("/a", "/ab"),
|
||||||
|
("/a", "/abc/d"),
|
||||||
|
("/a", "/A"),
|
||||||
|
("/a", "/A/b"),
|
||||||
|
("/a/b", "/a"),
|
||||||
|
("/a/b", "/a/bc"),
|
||||||
|
("/a", "/b"),
|
||||||
|
("/a", "/a/../b"),
|
||||||
|
("/a", "/a/.."),
|
||||||
|
("/a", "/a/./../b"),
|
||||||
|
("/a", "/a/%2e%2e/b"),
|
||||||
|
("/a", "/a/%2E%2E/b"),
|
||||||
|
("/a", "/a/.%2e/b"),
|
||||||
|
("/a", "/a/%2e./b"),
|
||||||
|
("/a", "/a/%252e%252e/b"),
|
||||||
|
("/a", "/a/%25252e/b"),
|
||||||
|
("/a", "/a%2f..%2fb"),
|
||||||
|
("/a", "/a%2F..%2Fb"),
|
||||||
|
("/a", "/a/..%2fb"),
|
||||||
|
("/a", "/a//b"),
|
||||||
|
("/a", "//a/b"),
|
||||||
|
("/a", "/a\\..\\b"),
|
||||||
|
("/a", "/a/..\\b"),
|
||||||
|
("/a", "/a%5c..%5cb"),
|
||||||
|
("/a", "/a/..;/b"),
|
||||||
|
("/a", "/a/.;/b"),
|
||||||
|
("/a", "/a/%00/b"),
|
||||||
|
("/a", "/a/b c"),
|
||||||
|
("/a", "/a/\tb"),
|
||||||
|
("/a", "a/b"),
|
||||||
|
("/a", ""),
|
||||||
|
("/a", "/a/ä"),
|
||||||
|
("/", "/../etc/passwd"),
|
||||||
|
("/", "//evil"),
|
||||||
|
("/", "/%2e%2e/x"),
|
||||||
|
// QC fix round 1: overlong UTF-8, IIS %u, fullwidth dots, Windows-trimmed and
|
||||||
|
// encoded-semicolon dot segments.
|
||||||
|
("/a", "/a/%c0%ae%c0%ae/b"),
|
||||||
|
("/a", "/a/%C0%AE%C0%AE/secret"),
|
||||||
|
("/a", "/a/..%c0%afb"),
|
||||||
|
("/a", "/a/%e0%80%ae%e0%80%ae/b"),
|
||||||
|
("/a", "/a/%f0%80%80%ae/b"),
|
||||||
|
("/a", "/a/%u002e%u002e/b"),
|
||||||
|
("/a", "/a/%u002E%u002E/b"),
|
||||||
|
("/a", "/a/..%u2215b"),
|
||||||
|
("/a", "/a/%ef%bc%8e%ef%bc%8e/b"),
|
||||||
|
("/a", "/a/..%ef%bc%8fb"),
|
||||||
|
("/a", "/a/..%e2%88%95b"),
|
||||||
|
("/a", "/a/..%20/b"),
|
||||||
|
("/a", "/a/.%20/b"),
|
||||||
|
("/a", "/a/..%09/b"),
|
||||||
|
("/a", "/a/..%3b/b"),
|
||||||
|
("/a", "/a/..%3B/b"),
|
||||||
|
("/a", "/a/..%3bx/b"),
|
||||||
|
("/a", "/a/.;x/b"),
|
||||||
|
("/a", "/a;/../b"),
|
||||||
|
("/a", "/a/%2E./b"),
|
||||||
|
// QC fix round 2: NFKC look-alikes and dots before an encoded byte.
|
||||||
|
("/a", "/a/%e2%80%a5/b"),
|
||||||
|
("/a", "/a/%E2%80%A5/b"),
|
||||||
|
("/a", "/a/%ef%b8%b0/b"),
|
||||||
|
("/a", "/a/..%ef%b9%a8secret"),
|
||||||
|
("/a", "/a/..%3f/b"),
|
||||||
|
("/a", "/a/..%3F"),
|
||||||
|
("/a", "/a/..%23/b"),
|
||||||
|
("/a", "/a/%e3%80%80/b"),
|
||||||
|
("/a", "/a/%zz/b"),
|
||||||
|
("/a", "/a/%e2%9c"),
|
||||||
|
// QC fix round 3: a segment that is only an ellipsis or a look-alike space, slash
|
||||||
|
// look-alikes, and a broken escape that from_str_radix would take.
|
||||||
|
("/a", "/a/%E2%80%A6/b"),
|
||||||
|
("/a", "/a/%E2%80%A6"),
|
||||||
|
("/a", "/a/%E3%80%80/b"),
|
||||||
|
("/a", "/a/%C2%A0%C2%A0/b"),
|
||||||
|
("/a", "/a/..%e2%88%95b"),
|
||||||
|
("/a", "/a/..%e2%81%84b"),
|
||||||
|
("/a", "/a/..%e2%a7%b8b"),
|
||||||
|
("/a", "/a/x%e2%88%95y"),
|
||||||
|
("/a", "/a/x%e2%81%84y"),
|
||||||
|
("/a", "/a/%+f/b"),
|
||||||
|
("/a", "/a/%-1/b"),
|
||||||
|
// QC fix round 4: dot-only segments hidden by invisible characters.
|
||||||
|
("/a", "/a/%e2%80%8b../b"),
|
||||||
|
("/a", "/a/%ef%bb%bf../b"),
|
||||||
|
("/a", "/a/%c2%ad../b"),
|
||||||
|
("/a", "/a/%cc%81../b"),
|
||||||
|
("/a", "/a/%e2%80%a4.%e2%80%8b/b"),
|
||||||
|
("/a", "/a/%e2%81%a0%e2%80%a5/b"),
|
||||||
|
("/a", "/a/..%cc%81/b"),
|
||||||
|
("/a", "/a/%e3%80%80../b"),
|
||||||
|
("/a", "/a/%ef%bc%8e%ef%bc%8e/b"),
|
||||||
|
("/a", "/a/%e2%80%a5%3bx/b"),
|
||||||
|
("/a", "/a/%ef%bc%85/b"),
|
||||||
|
("/a", "/a/x%ef%bc%8fy"),
|
||||||
|
("/a", "/a/%e2%80%a4%09/b"),
|
||||||
|
("/a", "/a/%ef%b9%a8"),
|
||||||
|
("/a", "/a/%e2%88%96"),
|
||||||
|
("/a", "/a/%e2%80%8b/b"),
|
||||||
|
];
|
||||||
|
for (prefix, path) in cases {
|
||||||
|
assert!(
|
||||||
|
!path_within(prefix, path),
|
||||||
|
"{prefix} must not cover {path:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
[package]
|
||||||
|
name = "ianitor-edge"
|
||||||
|
description = "Ianitor Domi data plane on Pingora. Serves compiled config; never decides policy."
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "ianitor-edge"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
ianitor-core.workspace = true
|
||||||
|
pingora = { version = "0.9.1", default-features = false, features = ["proxy", "rustls"] }
|
||||||
|
async-trait.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
bytes.workspace = true
|
||||||
|
http.workspace = true
|
||||||
|
log.workspace = true
|
||||||
|
rustls.workspace = true
|
||||||
|
rustls-pki-types.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
arc-swap = "1.7"
|
||||||
|
instant-acme = { version = "0.8.5", default-features = false, features = ["ring", "hyper-rustls", "rcgen"] }
|
||||||
|
x509-parser = "0.18"
|
||||||
|
thiserror.workspace = true
|
||||||
|
ring.workspace = true
|
||||||
|
hyper.workspace = true
|
||||||
|
hyper-util.workspace = true
|
||||||
|
http-body-util.workspace = true
|
||||||
|
form_urlencoded = "1.2"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
ianitor-testkit.workspace = true
|
||||||
|
ring.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -0,0 +1,347 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Let's Encrypt (any RFC 8555 directory) through `instant-acme`, HTTP-01 challenges answered
|
||||||
|
//! on the plain-HTTP listener. Certificates and the account live in `<state_dir>/acme`
|
||||||
|
//! (key files mode 0600) and are swapped into the SNI store without a restart. A certificate
|
||||||
|
//! is renewed when it has less than 30 days left; failures are retried with backoff.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, RwLock};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use instant_acme::{
|
||||||
|
Account, AccountCredentials, AuthorizationStatus, ChallengeType, Identifier, NewAccount,
|
||||||
|
NewOrder, OrderStatus, RetryPolicy,
|
||||||
|
};
|
||||||
|
use pingora::server::ShutdownWatch;
|
||||||
|
use pingora::services::background::BackgroundService;
|
||||||
|
|
||||||
|
use crate::logging::now_secs;
|
||||||
|
use crate::shared::{CertState, Shared};
|
||||||
|
use crate::tls::{certified_key, not_after};
|
||||||
|
|
||||||
|
const RENEW_BEFORE_SECS: f64 = 30.0 * 86_400.0;
|
||||||
|
const CHECK_EVERY: Duration = Duration::from_secs(12 * 3600);
|
||||||
|
const FIRST_RETRY: Duration = Duration::from_secs(30);
|
||||||
|
const MAX_RETRY: Duration = Duration::from_secs(3600);
|
||||||
|
const MIN_GAP: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
|
/// HTTP-01 tokens → key authorizations, shared with the HTTP listener.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Challenges(RwLock<HashMap<String, String>>);
|
||||||
|
|
||||||
|
impl Challenges {
|
||||||
|
pub fn get(&self, token: &str) -> Option<String> {
|
||||||
|
self.0.read().ok()?.get(token).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert(&self, token: String, key_auth: String) {
|
||||||
|
if let Ok(mut m) = self.0.write() {
|
||||||
|
m.insert(token, key_auth);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove(&self, token: &str) {
|
||||||
|
if let Ok(mut m) = self.0.write() {
|
||||||
|
m.remove(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AcmeService {
|
||||||
|
pub shared: Arc<Shared>,
|
||||||
|
pub challenges: Arc<Challenges>,
|
||||||
|
/// Extra trust root for the ACME directory (tests against Pebble only).
|
||||||
|
pub ca_root: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_private(path: &Path, data: &[u8]) -> Result<(), String> {
|
||||||
|
let tmp = path.with_extension("tmp");
|
||||||
|
let mut opts = std::fs::OpenOptions::new();
|
||||||
|
opts.write(true).create(true).truncate(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o600);
|
||||||
|
let mut f = opts
|
||||||
|
.open(&tmp)
|
||||||
|
.map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;
|
||||||
|
std::io::Write::write_all(&mut f, data)
|
||||||
|
.map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;
|
||||||
|
std::fs::rename(&tmp, path).map_err(|e| format!("cannot replace {}: {e}", path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fnv(data: &[u8]) -> String {
|
||||||
|
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||||
|
for b in data {
|
||||||
|
h ^= u64::from(*b);
|
||||||
|
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||||
|
}
|
||||||
|
format!("{h:016x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AcmeService {
|
||||||
|
fn dir(&self) -> PathBuf {
|
||||||
|
self.shared.current().acme_dir()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn paths(&self, host: &str) -> (PathBuf, PathBuf) {
|
||||||
|
(
|
||||||
|
self.dir().join(format!("{host}.crt")),
|
||||||
|
self.dir().join(format!("{host}.key")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load a stored certificate into the SNI store; returns its expiry.
|
||||||
|
fn load_stored(&self, host: &str) -> Option<i64> {
|
||||||
|
let (crt, key) = self.paths(host);
|
||||||
|
let cert_pem = std::fs::read(&crt).ok()?;
|
||||||
|
let key_pem = std::fs::read(&key).ok()?;
|
||||||
|
let expiry = not_after(&cert_pem)?;
|
||||||
|
match certified_key(&cert_pem, &key_pem) {
|
||||||
|
Ok(ck) => {
|
||||||
|
self.shared.certs.insert(host, ck);
|
||||||
|
self.ok(host, expiry);
|
||||||
|
Some(expiry)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::warn!(target: "ianitor::acme", "{host}: stored certificate is not usable ({e}); ordering a new one");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn builder(&self) -> Result<instant_acme::AccountBuilder, String> {
|
||||||
|
match &self.ca_root {
|
||||||
|
Some(p) => Account::builder_with_root(p),
|
||||||
|
None => Account::builder(),
|
||||||
|
}
|
||||||
|
.map_err(|e| format!("cannot set up the ACME client: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn account(&self, directory: &str, email: Option<&str>) -> Result<Account, String> {
|
||||||
|
let file = self
|
||||||
|
.dir()
|
||||||
|
.join(format!("account-{}.json", fnv(directory.as_bytes())));
|
||||||
|
if let Ok(text) = std::fs::read_to_string(&file) {
|
||||||
|
let creds: AccountCredentials = serde_json::from_str(&text)
|
||||||
|
.map_err(|e| format!("{} is damaged: {e}", file.display()))?;
|
||||||
|
return self
|
||||||
|
.builder()?
|
||||||
|
.from_credentials(creds)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("cannot restore the ACME account: {e}"));
|
||||||
|
}
|
||||||
|
let contact = email.map(|e| format!("mailto:{e}"));
|
||||||
|
let contacts: Vec<&str> = contact.iter().map(String::as_str).collect();
|
||||||
|
let (account, creds) = self
|
||||||
|
.builder()?
|
||||||
|
.create(
|
||||||
|
&NewAccount {
|
||||||
|
contact: &contacts,
|
||||||
|
terms_of_service_agreed: true,
|
||||||
|
only_return_existing: false,
|
||||||
|
},
|
||||||
|
directory.to_owned(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("cannot create the ACME account: {e}"))?;
|
||||||
|
let text = serde_json::to_vec(&creds)
|
||||||
|
.map_err(|e| format!("cannot store the ACME account: {e}"))?;
|
||||||
|
write_private(&file, &text)?;
|
||||||
|
log::info!(target: "ianitor::acme", "created ACME account at {directory}");
|
||||||
|
Ok(account)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn issue(&self, account: &Account, host: &str) -> Result<i64, String> {
|
||||||
|
let ids = [Identifier::Dns(host.to_owned())];
|
||||||
|
let mut order = account
|
||||||
|
.new_order(&NewOrder::new(&ids))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("new order: {e}"))?;
|
||||||
|
let mut tokens = Vec::new();
|
||||||
|
let mut auths = order.authorizations();
|
||||||
|
while let Some(result) = auths.next().await {
|
||||||
|
let mut authz = result.map_err(|e| format!("authorization: {e}"))?;
|
||||||
|
if authz.status == AuthorizationStatus::Valid {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if authz.status != AuthorizationStatus::Pending {
|
||||||
|
return Err(format!("authorization is {:?}", authz.status));
|
||||||
|
}
|
||||||
|
let mut ch = authz
|
||||||
|
.challenge(ChallengeType::Http01)
|
||||||
|
.ok_or("the server offers no HTTP-01 challenge")?;
|
||||||
|
self.challenges
|
||||||
|
.insert(ch.token.clone(), ch.key_authorization().as_str().to_owned());
|
||||||
|
tokens.push(ch.token.clone());
|
||||||
|
ch.set_ready()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("challenge ready: {e}"))?;
|
||||||
|
}
|
||||||
|
let policy = RetryPolicy::new().timeout(Duration::from_secs(90));
|
||||||
|
let status = order
|
||||||
|
.poll_ready(&policy)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("order: {e}"));
|
||||||
|
for t in &tokens {
|
||||||
|
self.challenges.remove(t);
|
||||||
|
}
|
||||||
|
match status? {
|
||||||
|
OrderStatus::Ready => {}
|
||||||
|
other => return Err(format!("order ended as {other:?}")),
|
||||||
|
}
|
||||||
|
let key_pem = order
|
||||||
|
.finalize()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("finalize: {e}"))?;
|
||||||
|
let chain_pem = order
|
||||||
|
.poll_certificate(&policy)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("certificate: {e}"))?;
|
||||||
|
let ck = certified_key(chain_pem.as_bytes(), key_pem.as_bytes())?;
|
||||||
|
let expiry =
|
||||||
|
not_after(chain_pem.as_bytes()).ok_or("cannot read the new certificate's expiry")?;
|
||||||
|
let (crt, key) = self.paths(host);
|
||||||
|
write_private(&key, key_pem.as_bytes())?;
|
||||||
|
write_private(&crt, chain_pem.as_bytes())?;
|
||||||
|
self.shared.certs.insert(host, ck);
|
||||||
|
self.ok(host, expiry);
|
||||||
|
log::info!(target: "ianitor::acme", "{host}: certificate issued, valid until {expiry}");
|
||||||
|
Ok(expiry)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pass over every ACME host. Returns false if any host failed.
|
||||||
|
fn ok(&self, host: &str, expiry: i64) {
|
||||||
|
self.shared.set_cert_state(
|
||||||
|
host,
|
||||||
|
CertState {
|
||||||
|
state: "ok",
|
||||||
|
not_after: Some(expiry),
|
||||||
|
error: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn round(&self, expiries: &mut HashMap<String, i64>) -> bool {
|
||||||
|
let rt = self.shared.current();
|
||||||
|
let Some(acme) = &rt.cfg.acme else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
let due: Vec<String> = rt
|
||||||
|
.acme_hosts()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|h| {
|
||||||
|
expiries
|
||||||
|
.get(h)
|
||||||
|
.is_none_or(|e| (*e as f64) - now_secs() < RENEW_BEFORE_SECS)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if due.is_empty() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
for h in &due {
|
||||||
|
if !expiries.contains_key(h) {
|
||||||
|
self.shared.set_cert_state(
|
||||||
|
h,
|
||||||
|
CertState {
|
||||||
|
state: "pending",
|
||||||
|
not_after: None,
|
||||||
|
error: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let account = match self.account(&acme.directory, acme.email.as_deref()).await {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::acme", "{e}");
|
||||||
|
for h in &due {
|
||||||
|
self.failed(h, expiries.get(h).copied(), &e);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut ok = true;
|
||||||
|
for host in due {
|
||||||
|
match self.issue(&account, &host).await {
|
||||||
|
Ok(exp) => {
|
||||||
|
expiries.insert(host, exp);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}");
|
||||||
|
self.failed(&host, expiries.get(&host).copied(), &e);
|
||||||
|
ok = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A host that still has a valid certificate stays `ok` while renewal retries.
|
||||||
|
fn failed(&self, host: &str, expiry: Option<i64>, error: &str) {
|
||||||
|
let still_valid = expiry.is_some_and(|e| (e as f64) > now_secs());
|
||||||
|
self.shared.set_cert_state(
|
||||||
|
host,
|
||||||
|
CertState {
|
||||||
|
state: if still_valid { "ok" } else { "failed" },
|
||||||
|
not_after: expiry,
|
||||||
|
error: Some(error.chars().take(300).collect()),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl BackgroundService for AcmeService {
|
||||||
|
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||||
|
let mut expiries = HashMap::new();
|
||||||
|
let mut retry = FIRST_RETRY;
|
||||||
|
let mut last: Option<std::time::Instant> = None;
|
||||||
|
loop {
|
||||||
|
// Reloads can come many times a second; ACME rounds at most every 5 s.
|
||||||
|
if let Some(l) = last
|
||||||
|
&& l.elapsed() < MIN_GAP
|
||||||
|
{
|
||||||
|
tokio::select! {
|
||||||
|
_ = tokio::time::sleep(MIN_GAP - l.elapsed()) => {}
|
||||||
|
_ = shutdown.changed() => return,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
last = Some(std::time::Instant::now());
|
||||||
|
let hosts = self.shared.current().acme_hosts();
|
||||||
|
let mut wait = CHECK_EVERY;
|
||||||
|
if !hosts.is_empty() {
|
||||||
|
let dir = self.dir();
|
||||||
|
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||||
|
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
|
||||||
|
} else {
|
||||||
|
for h in hosts {
|
||||||
|
if !expiries.contains_key(&h)
|
||||||
|
&& let Some(e) = self.load_stored(&h)
|
||||||
|
{
|
||||||
|
expiries.insert(h, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wait = if self.round(&mut expiries).await {
|
||||||
|
retry = FIRST_RETRY;
|
||||||
|
CHECK_EVERY
|
||||||
|
} else {
|
||||||
|
let w = retry;
|
||||||
|
retry = (retry * 2).min(MAX_RETRY);
|
||||||
|
w
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Woken early by a reload (new hosts) or a "try again" from control.
|
||||||
|
tokio::select! {
|
||||||
|
_ = tokio::time::sleep(wait) => {}
|
||||||
|
_ = self.shared.acme_wake.notified() => {}
|
||||||
|
_ = shutdown.changed() => return,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,338 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! The admin socket: a Unix socket (mode 0660, so only edge's user and group, i.e. control,
|
||||||
|
//! can connect; never a TCP port) speaking small JSON over HTTP/1.1.
|
||||||
|
//!
|
||||||
|
//! | Request | Does |
|
||||||
|
//! |:--|:--|
|
||||||
|
//! | `GET /v1/status` | config hash, trial, revocations, health per host and upstream, certificates |
|
||||||
|
//! | `POST /v1/reload` | reload the config file (refused while a trial runs) |
|
||||||
|
//! | `POST /v1/trial {confirm_within_secs, watch_hosts?, watch_every_secs?}` | serve the trial file until confirmed |
|
||||||
|
//! | `POST /v1/confirm {config_sha256}` | keep the running trial |
|
||||||
|
//! | `POST /v1/abort` | back to the config before the trial (idempotent) |
|
||||||
|
//! | `POST /v1/share-revocations/reload` | re-read the share-link revocation file |
|
||||||
|
//! | `POST /v1/acme/retry` | try Let's Encrypt again now |
|
||||||
|
//!
|
||||||
|
//! Bodies are at most 4 KiB with no unknown fields. Answers never carry a secret.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use bytes::Bytes;
|
||||||
|
use http_body_util::{BodyExt, Full, Limited};
|
||||||
|
use hyper::body::Incoming;
|
||||||
|
use hyper::server::conn::http1;
|
||||||
|
use hyper::service::service_fn;
|
||||||
|
use hyper::{Request, Response, StatusCode};
|
||||||
|
use hyper_util::rt::TokioIo;
|
||||||
|
use pingora::server::ShutdownWatch;
|
||||||
|
use pingora::services::background::BackgroundService;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use crate::shared::{AdminError, Shared, WatchSpec};
|
||||||
|
|
||||||
|
const MAX_BODY: usize = 4096;
|
||||||
|
/// Longest trial the admin socket accepts.
|
||||||
|
const MAX_TRIAL_SECS: u64 = 3600;
|
||||||
|
|
||||||
|
pub struct AdminSocket {
|
||||||
|
pub shared: Arc<Shared>,
|
||||||
|
pub path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct TrialBody {
|
||||||
|
confirm_within_secs: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
watch_hosts: Vec<String>,
|
||||||
|
watch_every_secs: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct ConfirmBody {
|
||||||
|
config_sha256: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Resp = Response<Full<Bytes>>;
|
||||||
|
|
||||||
|
fn reply(status: StatusCode, v: Value) -> Resp {
|
||||||
|
let mut r = Response::new(Full::new(Bytes::from(v.to_string())));
|
||||||
|
*r.status_mut() = status;
|
||||||
|
r.headers_mut().insert(
|
||||||
|
http::header::CONTENT_TYPE,
|
||||||
|
http::HeaderValue::from_static("application/json"),
|
||||||
|
);
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error(status: StatusCode, message: impl std::fmt::Display) -> Resp {
|
||||||
|
reply(status, json!({ "error": message.to_string() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn admin_error(e: AdminError) -> Resp {
|
||||||
|
match e {
|
||||||
|
AdminError::Refused(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
|
||||||
|
AdminError::Conflict(m) => error(StatusCode::CONFLICT, m),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The status document.
|
||||||
|
pub fn status(shared: &Shared) -> Value {
|
||||||
|
let rt = shared.current();
|
||||||
|
let mut hosts: Vec<&String> = rt.hosts.keys().collect();
|
||||||
|
hosts.sort();
|
||||||
|
let hosts: Vec<Value> = hosts
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|name| rt.hosts.get(name))
|
||||||
|
.map(|h| {
|
||||||
|
let name = &h.cfg.hostname;
|
||||||
|
let cert = match &h.cfg.tls {
|
||||||
|
ianitor_core::edge_config::EdgeTls::Files { .. } => json!({
|
||||||
|
"state": "ok",
|
||||||
|
"not_after": rt.file_cert_expiry.get(name),
|
||||||
|
"error": null,
|
||||||
|
}),
|
||||||
|
ianitor_core::edge_config::EdgeTls::Acme => match shared.cert_state(name) {
|
||||||
|
Some(c) => {
|
||||||
|
json!({ "state": c.state, "not_after": c.not_after, "error": c.error })
|
||||||
|
}
|
||||||
|
None => json!({ "state": "pending", "not_after": null, "error": null }),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
json!({
|
||||||
|
"hostname": name,
|
||||||
|
"health_check": h.cfg.health_check.is_some(),
|
||||||
|
"upstreams": h.upstreams.iter().map(|u| json!({
|
||||||
|
"address": u.authority,
|
||||||
|
"healthy": u.healthy.load(std::sync::atomic::Ordering::Relaxed),
|
||||||
|
"checks": u.health.checks(),
|
||||||
|
})).collect::<Vec<_>>(),
|
||||||
|
"certificate": cert,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let rev = shared.revocations();
|
||||||
|
json!({
|
||||||
|
"generation": shared.generation(),
|
||||||
|
"config_sha256": rt.sha256,
|
||||||
|
"started_at": shared.started_at,
|
||||||
|
"trial": shared.trial_info().map(|(sha, left, prev)| json!({
|
||||||
|
"config_sha256": sha,
|
||||||
|
"seconds_left": left,
|
||||||
|
"previous_sha256": prev,
|
||||||
|
})),
|
||||||
|
"share_revocations": {
|
||||||
|
"loaded": rev.loaded,
|
||||||
|
"epoch": rev.revocations.epoch,
|
||||||
|
"stopped": rev.revocations.deny.len(),
|
||||||
|
"error": rev.error,
|
||||||
|
},
|
||||||
|
"hosts": hosts,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn body<T: for<'de> Deserialize<'de>>(
|
||||||
|
req: Request<Incoming>,
|
||||||
|
) -> Result<Option<T>, Box<Resp>> {
|
||||||
|
let bytes = Limited::new(req.into_body(), MAX_BODY)
|
||||||
|
.collect()
|
||||||
|
.await
|
||||||
|
.map_err(|_| {
|
||||||
|
error(
|
||||||
|
StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
"the body is larger than 4 KiB",
|
||||||
|
)
|
||||||
|
})?
|
||||||
|
.to_bytes();
|
||||||
|
if bytes.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
serde_json::from_slice(&bytes)
|
||||||
|
.map(Some)
|
||||||
|
.map_err(|e| Box::new(error(StatusCode::BAD_REQUEST, format!("bad body: {e}"))))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle(shared: Arc<Shared>, req: Request<Incoming>) -> Resp {
|
||||||
|
let method = req.method().clone();
|
||||||
|
let path = req.uri().path().to_owned();
|
||||||
|
match (method.as_str(), path.as_str()) {
|
||||||
|
("GET", "/v1/status") => reply(StatusCode::OK, status(&shared)),
|
||||||
|
("POST", "/v1/reload") => {
|
||||||
|
let r = tokio::task::spawn_blocking({
|
||||||
|
let s = shared.clone();
|
||||||
|
move || s.reload()
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match r {
|
||||||
|
Ok(Ok(rt)) => reply(
|
||||||
|
StatusCode::OK,
|
||||||
|
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
|
||||||
|
),
|
||||||
|
Ok(Err(e)) => admin_error(e),
|
||||||
|
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("POST", "/v1/trial") => {
|
||||||
|
let b: TrialBody = match body(req).await {
|
||||||
|
Ok(Some(b)) => b,
|
||||||
|
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
|
||||||
|
Err(r) => return *r,
|
||||||
|
};
|
||||||
|
if !(1..=MAX_TRIAL_SECS).contains(&b.confirm_within_secs) {
|
||||||
|
return error(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"confirm_within_secs must be between 1 and 3600",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let every = b.watch_every_secs.unwrap_or(5);
|
||||||
|
if !(1..=60).contains(&every) || b.watch_hosts.len() > 1000 {
|
||||||
|
return error(StatusCode::BAD_REQUEST, "watch_every_secs must be 1 to 60");
|
||||||
|
}
|
||||||
|
let watch = (!b.watch_hosts.is_empty()).then(|| WatchSpec {
|
||||||
|
hosts: b.watch_hosts,
|
||||||
|
every: Duration::from_secs(every),
|
||||||
|
});
|
||||||
|
let within = Duration::from_secs(b.confirm_within_secs);
|
||||||
|
let r = tokio::task::spawn_blocking({
|
||||||
|
let s = shared.clone();
|
||||||
|
move || s.start_trial(within, watch)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match r {
|
||||||
|
Ok(Ok((id, rt))) => {
|
||||||
|
let s = shared.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Some(deadline) = s.trial_deadline(id) {
|
||||||
|
tokio::time::sleep_until(deadline.into()).await;
|
||||||
|
s.expire_trial(id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
reply(
|
||||||
|
StatusCode::OK,
|
||||||
|
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Ok(Err(e)) => admin_error(e),
|
||||||
|
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("POST", "/v1/confirm") => {
|
||||||
|
let b: ConfirmBody = match body(req).await {
|
||||||
|
Ok(Some(b)) => b,
|
||||||
|
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
|
||||||
|
Err(r) => return *r,
|
||||||
|
};
|
||||||
|
match shared.confirm(&b.config_sha256) {
|
||||||
|
Ok(()) => reply(StatusCode::OK, json!({ "confirmed": true })),
|
||||||
|
Err(e) => admin_error(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })),
|
||||||
|
("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() {
|
||||||
|
Ok(()) => {
|
||||||
|
let r = shared.revocations();
|
||||||
|
reply(
|
||||||
|
StatusCode::OK,
|
||||||
|
json!({ "epoch": r.revocations.epoch, "stopped": r.revocations.deny.len() }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
|
||||||
|
},
|
||||||
|
("POST", "/v1/acme/retry") => {
|
||||||
|
shared.acme_wake.notify_one();
|
||||||
|
reply(StatusCode::OK, json!({ "retrying": true }))
|
||||||
|
}
|
||||||
|
(_, "/v1/status" | "/v1/reload" | "/v1/trial" | "/v1/confirm" | "/v1/abort") => {
|
||||||
|
error(StatusCode::METHOD_NOT_ALLOWED, "method not allowed")
|
||||||
|
}
|
||||||
|
_ => error(StatusCode::NOT_FOUND, "no such admin request"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bind(path: &Path) -> std::io::Result<tokio::net::UnixListener> {
|
||||||
|
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
|
||||||
|
// A socket left over from a previous run is removed; anything else at the path is not.
|
||||||
|
if let Ok(meta) = std::fs::symlink_metadata(path) {
|
||||||
|
if meta.file_type().is_socket() {
|
||||||
|
std::fs::remove_file(path)?;
|
||||||
|
} else {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::AlreadyExists,
|
||||||
|
format!("{} exists and is not a socket", path.display()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Bind inside a fresh 0700 directory, set the mode, then move the socket into place, so
|
||||||
|
// there is no moment in which the socket exists with the process umask's permissions.
|
||||||
|
use std::os::unix::fs::DirBuilderExt;
|
||||||
|
let parent = path.parent().unwrap_or(Path::new("."));
|
||||||
|
let private = parent.join(format!(".ianitor-admin-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&private);
|
||||||
|
std::fs::DirBuilder::new().mode(0o700).create(&private)?;
|
||||||
|
let staged = private.join("admin.sock");
|
||||||
|
let bound = tokio::net::UnixListener::bind(&staged).and_then(|l| {
|
||||||
|
std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o660))?;
|
||||||
|
std::fs::rename(&staged, path)?;
|
||||||
|
Ok(l)
|
||||||
|
});
|
||||||
|
let _ = std::fs::remove_dir_all(&private);
|
||||||
|
bound
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl BackgroundService for AdminSocket {
|
||||||
|
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||||
|
let listener = match bind(&self.path) {
|
||||||
|
Ok(l) => l,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::admin", "cannot listen on {}: {e}; control cannot reach edge", self.path.display());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
log::info!(target: "ianitor::admin", "admin socket at {}", self.path.display());
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
_ = shutdown.changed() => break,
|
||||||
|
a = listener.accept() => {
|
||||||
|
let Ok((stream, _)) = a else { continue };
|
||||||
|
let shared = self.shared.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let svc = service_fn(move |req| {
|
||||||
|
let shared = shared.clone();
|
||||||
|
async move { Ok::<_, std::convert::Infallible>(handle(shared, req).await) }
|
||||||
|
});
|
||||||
|
let _ = http1::Builder::new()
|
||||||
|
.serve_connection(TokioIo::new(stream), svc)
|
||||||
|
.await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_file(&self.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-reads the share-link revocation file when it changes (every 5 s), so a stopped link
|
||||||
|
/// stops even if control's reload request was lost.
|
||||||
|
pub struct RevocationPoller {
|
||||||
|
pub shared: Arc<Shared>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl BackgroundService for RevocationPoller {
|
||||||
|
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
_ = shutdown.changed() => return,
|
||||||
|
_ = tokio::time::sleep(Duration::from_secs(5)) => self.shared.poll_revocations(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Startup errors. None of them ever carries a secret value.
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum EdgeError {
|
||||||
|
#[error("cannot read {path}: {source}")]
|
||||||
|
Read {
|
||||||
|
path: PathBuf,
|
||||||
|
source: std::io::Error,
|
||||||
|
},
|
||||||
|
#[error("cannot write {path}: {source}")]
|
||||||
|
Write {
|
||||||
|
path: PathBuf,
|
||||||
|
source: std::io::Error,
|
||||||
|
},
|
||||||
|
#[error("{path} is not a valid edge config: {message}")]
|
||||||
|
Config { path: PathBuf, message: String },
|
||||||
|
#[error("edge config version {found} is not supported (this build reads version {expected})")]
|
||||||
|
Version { found: u32, expected: u32 },
|
||||||
|
#[error("secret `{name}`: {reason}")]
|
||||||
|
Secret { name: String, reason: &'static str },
|
||||||
|
#[error("certificate for {host}: {reason}")]
|
||||||
|
Cert { host: String, reason: String },
|
||||||
|
#[error("upstream {address}: {reason}")]
|
||||||
|
Upstream { address: String, reason: String },
|
||||||
|
#[error("header `{name}`: {reason}")]
|
||||||
|
Header { name: String, reason: &'static str },
|
||||||
|
#[error("listener {address}: {reason}")]
|
||||||
|
Listen { address: String, reason: String },
|
||||||
|
#[error("command line: {0}")]
|
||||||
|
Usage(String),
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
// 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 HTTP client on Pingora's connector, for forward-auth subrequests and health checks.
|
||||||
|
//!
|
||||||
|
//! - The whole exchange is bounded by one deadline (Pingora's connector ignores the peer's
|
||||||
|
//! read timeout, so the deadline is enforced here with `tokio::time::timeout`).
|
||||||
|
//! - Informational answers (100, 102, 103) are skipped; `101` is returned as the final head
|
||||||
|
//! without a body, for the caller to reject.
|
||||||
|
//! - Every resolved address is tried in order until one accepts the connection.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use pingora::connectors::http::Connector;
|
||||||
|
use pingora::http::{RequestHeader, ResponseHeader};
|
||||||
|
use pingora::upstreams::peer::HttpPeer;
|
||||||
|
use pingora::{Error, ErrorType, Result};
|
||||||
|
|
||||||
|
use crate::runtime::UpstreamRt;
|
||||||
|
|
||||||
|
pub struct Fetched {
|
||||||
|
pub header: ResponseHeader,
|
||||||
|
pub body: Bytes,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dial timeout, matching Caddy's reverse_proxy default.
|
||||||
|
pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3);
|
||||||
|
/// More 1xx heads than this before a final answer is treated as a broken server. Go (and so
|
||||||
|
/// Caddy) has no count limit, only one on total header bytes; 1000 heads accepts anything a
|
||||||
|
/// real server sends, and the overall deadline bounds the rest.
|
||||||
|
const MAX_INFORMATIONAL: usize = 1000;
|
||||||
|
|
||||||
|
pub fn peer(addr: SocketAddr, u: &UpstreamRt) -> HttpPeer {
|
||||||
|
let mut p = HttpPeer::new(addr, u.tls, u.sni.clone());
|
||||||
|
p.options.connection_timeout = Some(DIAL_TIMEOUT);
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send `req` without a body; read the whole response, at most `max_body` bytes of body,
|
||||||
|
/// all within `timeout`.
|
||||||
|
pub async fn fetch(
|
||||||
|
connector: &Connector,
|
||||||
|
u: &UpstreamRt,
|
||||||
|
req: RequestHeader,
|
||||||
|
max_body: usize,
|
||||||
|
timeout: Duration,
|
||||||
|
) -> Result<Fetched> {
|
||||||
|
match tokio::time::timeout(timeout, exchange(connector, u, req, max_body, timeout)).await {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(_) => Error::e_explain(
|
||||||
|
ErrorType::ReadTimedout,
|
||||||
|
format!("no complete answer within {timeout:?}"),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn exchange(
|
||||||
|
connector: &Connector,
|
||||||
|
u: &UpstreamRt,
|
||||||
|
req: RequestHeader,
|
||||||
|
max_body: usize,
|
||||||
|
timeout: Duration,
|
||||||
|
) -> Result<Fetched> {
|
||||||
|
let addrs = u.resolve().await.map_err(|e| {
|
||||||
|
Error::explain(
|
||||||
|
ErrorType::ConnectNoRoute,
|
||||||
|
format!("cannot resolve {}: {e}", u.authority),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let mut last = None;
|
||||||
|
let mut session = None;
|
||||||
|
for addr in addrs {
|
||||||
|
let mut p = peer(addr, u);
|
||||||
|
p.options.total_connection_timeout = Some(timeout);
|
||||||
|
match connector.get_http_session(&p).await {
|
||||||
|
Ok((s, _reused)) => {
|
||||||
|
session = Some(s);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(e) => last = Some(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some(mut http) = session else {
|
||||||
|
return Err(last.unwrap_or_else(|| {
|
||||||
|
Error::explain(ErrorType::ConnectError, "no address to connect to")
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
http.set_read_timeout(Some(timeout));
|
||||||
|
http.set_write_timeout(Some(timeout));
|
||||||
|
http.write_request_header(Box::new(req)).await?;
|
||||||
|
http.finish_request_body().await?;
|
||||||
|
|
||||||
|
let mut header = None;
|
||||||
|
for _ in 0..=MAX_INFORMATIONAL {
|
||||||
|
http.read_response_header().await?;
|
||||||
|
let h = http
|
||||||
|
.response_header()
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?;
|
||||||
|
let s = h.status.as_u16();
|
||||||
|
if (100..200).contains(&s) && s != 101 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
header = Some(h);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let header = header.ok_or_else(|| {
|
||||||
|
Error::explain(ErrorType::InvalidHTTPHeader, "only informational answers")
|
||||||
|
})?;
|
||||||
|
if header.status.as_u16() == 101 {
|
||||||
|
// Switching protocols: there is no HTTP body to read.
|
||||||
|
return Ok(Fetched {
|
||||||
|
header,
|
||||||
|
body: Bytes::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut body = BytesMut::new();
|
||||||
|
while let Some(chunk) = http.read_response_body().await? {
|
||||||
|
if body.len() + chunk.len() > max_body {
|
||||||
|
return Error::e_explain(ErrorType::InvalidHTTPHeader, "response body too large");
|
||||||
|
}
|
||||||
|
body.extend_from_slice(&chunk);
|
||||||
|
}
|
||||||
|
// Not returned to the pool: these calls are rare and a fresh connection is simplest.
|
||||||
|
Ok(Fetched {
|
||||||
|
header,
|
||||||
|
body: body.freeze(),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Forward-auth compatible with Authelia's ForwardAuth implementation
|
||||||
|
//! (`GET /api/authz/forward-auth`) and with Caddy's `forward_auth` directive:
|
||||||
|
//!
|
||||||
|
//! - The subrequest is a `GET` to the configured path, carrying the client's request headers
|
||||||
|
//! (minus hop-by-hop and framing headers, never a body) plus `X-Forwarded-Method`,
|
||||||
|
//! `X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Uri` and `X-Forwarded-For`, which
|
||||||
|
//! edge always sets itself (client-supplied values are replaced).
|
||||||
|
//! - A 2xx answer allows the request: each configured identity header is removed from the
|
||||||
|
//! client request and, when the auth answer has a non-empty value, set from it.
|
||||||
|
//! - Any other answer is returned to the client as it is (status, headers, body), and the
|
||||||
|
//! request never reaches the upstream.
|
||||||
|
//! - If the auth server cannot be reached, does not answer completely within 10 s, answers
|
||||||
|
//! with more than 1 MiB of body, a broken body or `101`, the request fails closed with 502.
|
||||||
|
//! Informational answers (100, 102, 103) before the real answer are skipped.
|
||||||
|
//! - Client-sent identity headers (Authelia's four plus the copy headers) are removed first,
|
||||||
|
//! so neither the auth server nor the upstream ever sees them.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use bytes::Bytes;
|
||||||
|
use http::header::{self, HeaderName, HeaderValue};
|
||||||
|
use pingora::connectors::http::Connector;
|
||||||
|
use pingora::http::{RequestHeader, ResponseHeader};
|
||||||
|
use pingora::proxy::Session;
|
||||||
|
use pingora::{Error, ErrorType, Result};
|
||||||
|
|
||||||
|
use crate::fetch::fetch;
|
||||||
|
use crate::runtime::ForwardAuthRt;
|
||||||
|
|
||||||
|
const MAX_AUTH_BODY: usize = 1 << 20;
|
||||||
|
const AUTH_TIMEOUT: Duration = Duration::from_secs(10);
|
||||||
|
|
||||||
|
pub enum Outcome {
|
||||||
|
Allow(Vec<(HeaderName, Option<HeaderValue>)>),
|
||||||
|
Deny(Box<ResponseHeader>, Bytes),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request headers never copied to a subrequest or a passed-through response.
|
||||||
|
pub fn hop_by_hop(name: &HeaderName) -> bool {
|
||||||
|
matches!(
|
||||||
|
name.as_str(),
|
||||||
|
"connection"
|
||||||
|
| "keep-alive"
|
||||||
|
| "proxy-connection"
|
||||||
|
| "te"
|
||||||
|
| "trailer"
|
||||||
|
| "transfer-encoding"
|
||||||
|
| "upgrade"
|
||||||
|
| "content-length"
|
||||||
|
| "proxy-authenticate"
|
||||||
|
| "proxy-authorization"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn forwarded(name: &HeaderName) -> bool {
|
||||||
|
name.as_str().starts_with("x-forwarded-")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn check(
|
||||||
|
connector: &Connector,
|
||||||
|
fa: &ForwardAuthRt,
|
||||||
|
session: &Session,
|
||||||
|
host_header: &str,
|
||||||
|
client_ip: Option<String>,
|
||||||
|
) -> Result<Outcome> {
|
||||||
|
let req = session.req_header();
|
||||||
|
let mut sub = RequestHeader::build("GET", fa.path_and_query.as_bytes(), None)?;
|
||||||
|
for (name, value) in req.headers.iter() {
|
||||||
|
if !hop_by_hop(name) && !forwarded(name) && name != header::HOST {
|
||||||
|
sub.append_header(name.clone(), value.clone())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let uri = req.uri.path_and_query().map(|p| p.as_str()).unwrap_or("/");
|
||||||
|
sub.insert_header(header::HOST, host_header)?;
|
||||||
|
sub.insert_header("X-Forwarded-Method", req.method.as_str())?;
|
||||||
|
sub.insert_header("X-Forwarded-Proto", "https")?;
|
||||||
|
sub.insert_header("X-Forwarded-Host", host_header)?;
|
||||||
|
sub.insert_header("X-Forwarded-Uri", uri)?;
|
||||||
|
if let Some(ip) = client_ip {
|
||||||
|
sub.insert_header("X-Forwarded-For", ip)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let got = fetch(connector, &fa.upstream, sub, MAX_AUTH_BODY, AUTH_TIMEOUT).await?;
|
||||||
|
let status = got.header.status.as_u16();
|
||||||
|
if status < 200 {
|
||||||
|
// 101 (or any 1xx left over) is not an answer we can pass on or treat as an allow.
|
||||||
|
return Error::e_explain(
|
||||||
|
ErrorType::InvalidHTTPHeader,
|
||||||
|
format!("auth server answered {status}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (200..300).contains(&status) {
|
||||||
|
let copy = fa
|
||||||
|
.copy_headers
|
||||||
|
.iter()
|
||||||
|
.map(|n| {
|
||||||
|
let v = got.header.headers.get(n).filter(|v| !v.is_empty()).cloned();
|
||||||
|
(n.clone(), v)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
return Ok(Outcome::Allow(copy));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut resp = ResponseHeader::build(got.header.status, None)?;
|
||||||
|
for (name, value) in got.header.headers.iter() {
|
||||||
|
if !hop_by_hop(name) {
|
||||||
|
resp.append_header(name.clone(), value.clone())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resp.insert_header(header::CONTENT_LENGTH, got.body.len().to_string())?;
|
||||||
|
Ok(Outcome::Deny(Box::new(resp), got.body))
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Active health checks, like Caddy's `health_checks.active`: `GET <path>` with the upstream
|
||||||
|
//! address as Host, healthy on 2xx, 5 s timeout, one result flips the state. The first round
|
||||||
|
//! runs when a config is loaded; upstreams start healthy.
|
||||||
|
//!
|
||||||
|
//! Every result is also recorded (time, latency, why it failed) for the admin socket.
|
||||||
|
//! During a trial, the watched hosts are probed at least every `every` seconds; a watched
|
||||||
|
//! host without a health check gets `GET /` with its own hostname as Host, and any answer
|
||||||
|
//! below 500 counts as alive (docs/ui-api.md G3). Those watch probes never change routing.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use pingora::connectors::http::Connector;
|
||||||
|
use pingora::http::RequestHeader;
|
||||||
|
use pingora::server::ShutdownWatch;
|
||||||
|
use pingora::services::background::BackgroundService;
|
||||||
|
use pingora::{Error, ErrorType};
|
||||||
|
|
||||||
|
use crate::fetch::fetch;
|
||||||
|
use crate::logging::now_secs;
|
||||||
|
use crate::runtime::{Check, HostRt, UpstreamRt};
|
||||||
|
use crate::shared::Shared;
|
||||||
|
|
||||||
|
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
|
pub struct HealthChecks {
|
||||||
|
pub shared: Arc<Shared>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a probe failed, in the words of docs/ui-api.md §3.3.
|
||||||
|
pub fn failure_kind(e: &Error) -> &'static str {
|
||||||
|
match e.etype() {
|
||||||
|
ErrorType::ConnectRefused | ErrorType::ConnectError | ErrorType::ConnectionClosed => {
|
||||||
|
"refused"
|
||||||
|
}
|
||||||
|
ErrorType::ConnectTimedout
|
||||||
|
| ErrorType::ReadTimedout
|
||||||
|
| ErrorType::WriteTimedout
|
||||||
|
| ErrorType::TLSHandshakeTimedout => "timeout",
|
||||||
|
ErrorType::ConnectNoRoute => "name",
|
||||||
|
ErrorType::TLSHandshakeFailure | ErrorType::InvalidCert | ErrorType::HandshakeError => {
|
||||||
|
"tls"
|
||||||
|
}
|
||||||
|
_ => "bad_answer",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_kind(status: u16) -> &'static str {
|
||||||
|
match status {
|
||||||
|
300..=399 => "redirect",
|
||||||
|
401 | 403 => "sign_in",
|
||||||
|
404 => "not_found",
|
||||||
|
500..=599 => "server_error",
|
||||||
|
_ => "bad_answer",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One probe. `watch` probes count any answer below 500 as alive.
|
||||||
|
async fn probe(
|
||||||
|
connector: &Connector,
|
||||||
|
u: &UpstreamRt,
|
||||||
|
path: &str,
|
||||||
|
host: &str,
|
||||||
|
watch: bool,
|
||||||
|
) -> Check {
|
||||||
|
let started = Instant::now();
|
||||||
|
let at = now_secs() as u64;
|
||||||
|
let source = if watch { "watch" } else { "health_check" };
|
||||||
|
let fail = |kind: &'static str, status: Option<u16>, latency: Option<u64>| Check {
|
||||||
|
seq: 0,
|
||||||
|
at,
|
||||||
|
ok: false,
|
||||||
|
source,
|
||||||
|
kind: Some(kind),
|
||||||
|
status,
|
||||||
|
latency_ms: latency,
|
||||||
|
};
|
||||||
|
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
|
||||||
|
return fail("bad_answer", None, None);
|
||||||
|
};
|
||||||
|
if req.insert_header(http::header::HOST, host).is_err() {
|
||||||
|
return fail("bad_answer", None, None);
|
||||||
|
}
|
||||||
|
match fetch(connector, u, req, 64 * 1024, TIMEOUT).await {
|
||||||
|
Ok(f) => {
|
||||||
|
let status = f.header.status.as_u16();
|
||||||
|
let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||||
|
let ok = if watch {
|
||||||
|
(100..500).contains(&status)
|
||||||
|
} else {
|
||||||
|
f.header.status.is_success()
|
||||||
|
};
|
||||||
|
if ok {
|
||||||
|
Check {
|
||||||
|
seq: 0,
|
||||||
|
at,
|
||||||
|
ok: true,
|
||||||
|
source,
|
||||||
|
kind: None,
|
||||||
|
status: Some(status),
|
||||||
|
latency_ms: Some(latency),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fail(status_kind(status), Some(status), Some(latency))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => fail(failure_kind(&e), None, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a
|
||||||
|
/// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of
|
||||||
|
/// ending health checks.
|
||||||
|
async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>, watch: bool) {
|
||||||
|
for i in 0..host.upstreams.len() {
|
||||||
|
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
|
||||||
|
let probe_host = if watch {
|
||||||
|
host.cfg.hostname.clone()
|
||||||
|
} else {
|
||||||
|
host.upstreams[i].authority.clone()
|
||||||
|
};
|
||||||
|
let check = match tokio::spawn(async move {
|
||||||
|
probe(&c, &h.upstreams[i], &p, &probe_host, watch).await
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority);
|
||||||
|
Check {
|
||||||
|
seq: 0,
|
||||||
|
at: now_secs() as u64,
|
||||||
|
ok: false,
|
||||||
|
source: if watch { "watch" } else { "health_check" },
|
||||||
|
kind: Some("bad_answer"),
|
||||||
|
status: None,
|
||||||
|
latency_ms: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let u = &host.upstreams[i];
|
||||||
|
let ok = check.ok;
|
||||||
|
u.health.record(check);
|
||||||
|
if watch {
|
||||||
|
// Watch probes only report; routing follows the host's own health check.
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if u.healthy.swap(ok, Ordering::Relaxed) != ok {
|
||||||
|
if ok {
|
||||||
|
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
|
||||||
|
} else {
|
||||||
|
log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn watcher(host: Arc<HostRt>, path: String, every: Duration, watch: bool) {
|
||||||
|
let connector = Arc::new(Connector::new(None));
|
||||||
|
loop {
|
||||||
|
round(&host, &path, &connector, watch).await;
|
||||||
|
tokio::time::sleep(every).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Job {
|
||||||
|
host: Arc<HostRt>,
|
||||||
|
path: String,
|
||||||
|
every: Duration,
|
||||||
|
watch: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn jobs(shared: &Shared) -> Vec<Job> {
|
||||||
|
let rt = shared.current();
|
||||||
|
let spec = shared.watch_spec();
|
||||||
|
let watched = |h: &str| {
|
||||||
|
spec.as_ref()
|
||||||
|
.is_some_and(|s| s.hosts.iter().any(|w| w == h))
|
||||||
|
};
|
||||||
|
let every = spec.as_ref().map(|s| s.every);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for h in rt.hosts.values() {
|
||||||
|
let name = &h.cfg.hostname;
|
||||||
|
match &h.cfg.health_check {
|
||||||
|
Some(hc) => {
|
||||||
|
let mut interval = Duration::from_secs(u64::from(hc.interval_secs.max(1)));
|
||||||
|
if watched(name)
|
||||||
|
&& let Some(e) = every
|
||||||
|
{
|
||||||
|
interval = interval.min(e);
|
||||||
|
}
|
||||||
|
out.push(Job {
|
||||||
|
host: h.clone(),
|
||||||
|
path: hc.path.clone(),
|
||||||
|
every: interval,
|
||||||
|
watch: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
None if watched(name) => out.push(Job {
|
||||||
|
host: h.clone(),
|
||||||
|
path: "/".into(),
|
||||||
|
every: every.unwrap_or(Duration::from_secs(5)),
|
||||||
|
watch: true,
|
||||||
|
}),
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl BackgroundService for HealthChecks {
|
||||||
|
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||||
|
let mut changes = self.shared.subscribe();
|
||||||
|
loop {
|
||||||
|
let jobs = jobs(&self.shared);
|
||||||
|
let mut tasks = tokio::task::JoinSet::new();
|
||||||
|
let mut which = std::collections::HashMap::new();
|
||||||
|
for (i, j) in jobs.iter().enumerate() {
|
||||||
|
let id = tasks
|
||||||
|
.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch))
|
||||||
|
.id();
|
||||||
|
which.insert(id, i);
|
||||||
|
}
|
||||||
|
// Run until the config or the watch changes; a watcher never returns, and if one
|
||||||
|
// ends anyway, say so and start it again.
|
||||||
|
let stop = loop {
|
||||||
|
tokio::select! {
|
||||||
|
_ = shutdown.changed() => break true,
|
||||||
|
r = changes.changed() => break r.is_err(),
|
||||||
|
Some(done) = tasks.join_next_with_id() => {
|
||||||
|
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
|
||||||
|
if let Some(i) = which.remove(&id) {
|
||||||
|
let j = &jobs[i];
|
||||||
|
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", j.host.cfg.hostname);
|
||||||
|
which.insert(tasks.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch)).id(), i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tasks.abort_all();
|
||||||
|
if stop {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
// 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 plain-HTTP listener: answers ACME HTTP-01 challenges, redirects known hosts to HTTPS
|
||||||
|
//! with 308 (like Caddy), and answers 404 for anything else.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use http::{Response, StatusCode, header};
|
||||||
|
use pingora::ErrorType;
|
||||||
|
use pingora::apps::{HttpPersistentSettings, HttpServerApp, ReusedHttpStream};
|
||||||
|
use pingora::http::ResponseHeader;
|
||||||
|
use pingora::protocols::http::ServerSession;
|
||||||
|
use pingora::server::ShutdownWatch;
|
||||||
|
|
||||||
|
use crate::acme::Challenges;
|
||||||
|
use crate::logging::{AccessRecord, now_secs, truncate_ip};
|
||||||
|
use crate::proxy::{host_header, hostname};
|
||||||
|
use crate::shared::Shared;
|
||||||
|
|
||||||
|
pub struct HttpApp {
|
||||||
|
pub shared: Arc<Shared>,
|
||||||
|
pub challenges: Arc<Challenges>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn empty(status: StatusCode) -> Response<Vec<u8>> {
|
||||||
|
let mut r = Response::new(Vec::new());
|
||||||
|
*r.status_mut() = status;
|
||||||
|
r.headers_mut()
|
||||||
|
.insert(header::CONTENT_LENGTH, http::HeaderValue::from_static("0"));
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl HttpServerApp for HttpApp {
|
||||||
|
/// Like Pingora's `ServeHttp` driver, but a request Pingora refuses to parse (for example
|
||||||
|
/// an absolute-form target whose authority differs from Host) gets a 400 instead of a
|
||||||
|
/// silently closed connection, as on the HTTPS listener.
|
||||||
|
async fn process_new_http(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
mut http: ServerSession,
|
||||||
|
shutdown: &ShutdownWatch,
|
||||||
|
) -> Option<ReusedHttpStream> {
|
||||||
|
match http.read_request().await {
|
||||||
|
Ok(true) => {}
|
||||||
|
Ok(false) => return None,
|
||||||
|
Err(e) => {
|
||||||
|
if matches!(e.etype(), ErrorType::InvalidHTTPHeader) {
|
||||||
|
log::debug!(target: "ianitor::http", "bad request: {e}");
|
||||||
|
let _ = http.respond_error(400).await;
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
http.set_keepalive(if *shutdown.borrow() { None } else { Some(60) });
|
||||||
|
let (parts, body) = self.response(&mut http).await.into_parts();
|
||||||
|
let header: ResponseHeader = parts.into();
|
||||||
|
if http.write_response_header(Box::new(header)).await.is_err() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if !body.is_empty() && http.write_response_body(body.into(), true).await.is_err() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let settings = HttpPersistentSettings::for_session(&http);
|
||||||
|
match http.finish().await {
|
||||||
|
Ok(c) => c.map(|s| ReusedHttpStream::from_reusable_stream(s, settings)),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HttpApp {
|
||||||
|
async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> {
|
||||||
|
let start = Instant::now();
|
||||||
|
let rt = self.shared.current();
|
||||||
|
let req = session.req_header();
|
||||||
|
let hh = host_header(req);
|
||||||
|
let name = hostname(&hh);
|
||||||
|
let path = req.uri.path().to_owned();
|
||||||
|
|
||||||
|
if let Some(token) = path.strip_prefix("/.well-known/acme-challenge/")
|
||||||
|
&& let Some(key_auth) = self.challenges.get(token)
|
||||||
|
{
|
||||||
|
log::info!(target: "ianitor::acme", "answered HTTP-01 challenge for {name}");
|
||||||
|
let mut r = Response::new(key_auth.into_bytes());
|
||||||
|
r.headers_mut().insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
http::HeaderValue::from_static("text/plain"),
|
||||||
|
);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(host) = rt.host(&name) else {
|
||||||
|
return empty(StatusCode::NOT_FOUND);
|
||||||
|
};
|
||||||
|
let uri = req.uri.path_and_query().map_or("/", |p| p.as_str());
|
||||||
|
let port = rt.cfg.https_port;
|
||||||
|
let location = if port == 443 {
|
||||||
|
format!("https://{name}{uri}")
|
||||||
|
} else {
|
||||||
|
format!("https://{name}:{port}{uri}")
|
||||||
|
};
|
||||||
|
let mut r = empty(StatusCode::PERMANENT_REDIRECT);
|
||||||
|
match http::HeaderValue::from_str(&location) {
|
||||||
|
Ok(v) => {
|
||||||
|
r.headers_mut().insert(header::LOCATION, v);
|
||||||
|
}
|
||||||
|
Err(_) => return empty(StatusCode::BAD_REQUEST),
|
||||||
|
}
|
||||||
|
if host.cfg.access_log
|
||||||
|
&& let Some(log) = &rt.access_log
|
||||||
|
{
|
||||||
|
log.write(&AccessRecord {
|
||||||
|
ts: now_secs(),
|
||||||
|
host: &host.cfg.hostname,
|
||||||
|
method: req.method.as_str(),
|
||||||
|
path: &path,
|
||||||
|
status: 308,
|
||||||
|
remote_ip: session
|
||||||
|
.client_addr()
|
||||||
|
.and_then(|a| a.as_inet())
|
||||||
|
.map(|a| truncate_ip(a.ip()).to_string()),
|
||||||
|
duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
// 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 edge: the Pingora data plane. It reads the config compiled by `ianitor-core`
|
||||||
|
//! and serves it; it never decides policy.
|
||||||
|
//!
|
||||||
|
//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, share links, websockets,
|
||||||
|
//! header rules, round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and
|
||||||
|
//! redirects), health checks, ACME issuance and renewal, and the admin socket through which
|
||||||
|
//! control reloads the config in process (see `shared`).
|
||||||
|
|
||||||
|
pub mod acme;
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub mod admin;
|
||||||
|
pub mod error;
|
||||||
|
pub mod fetch;
|
||||||
|
pub mod forward_auth;
|
||||||
|
pub mod health;
|
||||||
|
pub mod http_app;
|
||||||
|
pub mod logging;
|
||||||
|
pub mod pages;
|
||||||
|
pub mod proxy;
|
||||||
|
pub mod runtime;
|
||||||
|
pub mod secrets;
|
||||||
|
pub mod share;
|
||||||
|
pub mod shared;
|
||||||
|
pub mod tls;
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use pingora::connectors::http::Connector;
|
||||||
|
use pingora::listeners::tls::TlsSettings;
|
||||||
|
use pingora::proxy::http_proxy_service;
|
||||||
|
use pingora::server::Server;
|
||||||
|
use pingora::server::configuration::ServerConf;
|
||||||
|
use pingora::services::background::background_service;
|
||||||
|
use pingora::services::listening::Service;
|
||||||
|
|
||||||
|
pub use error::EdgeError;
|
||||||
|
pub use runtime::Runtime;
|
||||||
|
pub use shared::Shared;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct Options {
|
||||||
|
/// The compiled edge config (`ianitor-core` edge compiler output).
|
||||||
|
pub config: PathBuf,
|
||||||
|
/// The trial config control writes before an apply; default `<config>.trial`.
|
||||||
|
pub trial_config: Option<PathBuf>,
|
||||||
|
/// Admin socket for control (Unix only); none when `None`.
|
||||||
|
pub admin_socket: Option<PathBuf>,
|
||||||
|
/// The share-link revocation file control writes; without it, share links are refused.
|
||||||
|
pub share_revocations: Option<PathBuf>,
|
||||||
|
/// Extra trust root for the ACME directory's TLS (Pebble in tests).
|
||||||
|
pub acme_root: Option<PathBuf>,
|
||||||
|
/// Overrides `$CREDENTIALS_DIRECTORY` (tests running several edges in one process).
|
||||||
|
pub credentials_dir: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Options {
|
||||||
|
pub fn trial_path(&self) -> PathBuf {
|
||||||
|
self.trial_config
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| default_trial_path(&self.config))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `<config>.trial`, next to the config.
|
||||||
|
pub fn default_trial_path(config: &Path) -> PathBuf {
|
||||||
|
let mut name = config.file_name().unwrap_or_default().to_os_string();
|
||||||
|
name.push(".trial");
|
||||||
|
config.with_file_name(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn credentials_dir(opts: &Options) -> Option<PathBuf> {
|
||||||
|
opts.credentials_dir
|
||||||
|
.clone()
|
||||||
|
.or_else(|| std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates.
|
||||||
|
pub fn prepare(opts: &Options) -> Result<Arc<Shared>, EdgeError> {
|
||||||
|
let creds = credentials_dir(opts);
|
||||||
|
let rt = runtime::build_file(&opts.config, creds.as_deref())?;
|
||||||
|
Ok(shared_for(rt, opts))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wrap an already built runtime (tests run edge in process this way).
|
||||||
|
pub fn shared_for(rt: Runtime, opts: &Options) -> Arc<Shared> {
|
||||||
|
Shared::new(
|
||||||
|
rt,
|
||||||
|
shared::Paths {
|
||||||
|
config: opts.config.clone(),
|
||||||
|
trial: opts.trial_path(),
|
||||||
|
revocations: opts.share_revocations.clone(),
|
||||||
|
},
|
||||||
|
credentials_dir(opts),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Assemble the Pingora server with all services. Listeners bind when it runs.
|
||||||
|
pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError> {
|
||||||
|
pingora::tls::install_default_crypto_provider();
|
||||||
|
let conf = ServerConf {
|
||||||
|
threads: 2,
|
||||||
|
grace_period_seconds: Some(5),
|
||||||
|
graceful_shutdown_timeout_seconds: Some(10),
|
||||||
|
..ServerConf::default()
|
||||||
|
};
|
||||||
|
let mut server = Server::new_with_opt_and_conf(None, conf);
|
||||||
|
server.bootstrap();
|
||||||
|
|
||||||
|
let challenges = Arc::new(acme::Challenges::default());
|
||||||
|
let rt = shared.current();
|
||||||
|
|
||||||
|
let mut https = http_proxy_service(
|
||||||
|
&server.configuration,
|
||||||
|
proxy::EdgeProxy {
|
||||||
|
shared: shared.clone(),
|
||||||
|
connector: Connector::new(None),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let mut tls = TlsSettings::intermediate("", "").map_err(|e| EdgeError::Listen {
|
||||||
|
address: rt.cfg.https_listen.clone(),
|
||||||
|
reason: e.to_string(),
|
||||||
|
})?;
|
||||||
|
tls.set_cert_resolver(shared.certs.clone());
|
||||||
|
tls.enable_h2();
|
||||||
|
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls);
|
||||||
|
|
||||||
|
let mut http = Service::new(
|
||||||
|
"ianitor http".to_owned(),
|
||||||
|
http_app::HttpApp {
|
||||||
|
shared: shared.clone(),
|
||||||
|
challenges: challenges.clone(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
http.add_tcp(&rt.cfg.http_listen);
|
||||||
|
|
||||||
|
server.add_service(https);
|
||||||
|
server.add_service(http);
|
||||||
|
server.add_service(background_service(
|
||||||
|
"ianitor health checks",
|
||||||
|
health::HealthChecks {
|
||||||
|
shared: shared.clone(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
server.add_service(background_service(
|
||||||
|
"ianitor acme",
|
||||||
|
acme::AcmeService {
|
||||||
|
shared: shared.clone(),
|
||||||
|
challenges,
|
||||||
|
ca_root: opts.acme_root.clone(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
server.add_service(background_service(
|
||||||
|
"ianitor share revocations",
|
||||||
|
admin::RevocationPoller {
|
||||||
|
shared: shared.clone(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
if let Some(path) = &opts.admin_socket {
|
||||||
|
server.add_service(background_service(
|
||||||
|
"ianitor admin socket",
|
||||||
|
admin::AdminSocket {
|
||||||
|
shared: shared.clone(),
|
||||||
|
path: path.clone(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(server)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run until `stop` resolves (or is dropped). For running edge inside a test process.
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub fn run_until(server: Server, stop: tokio::sync::oneshot::Receiver<()>) {
|
||||||
|
use pingora::server::{RunArgs, ShutdownSignal, ShutdownSignalWatch};
|
||||||
|
|
||||||
|
struct Stop(tokio::sync::Mutex<Option<tokio::sync::oneshot::Receiver<()>>>);
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl ShutdownSignalWatch for Stop {
|
||||||
|
async fn recv(&self) -> ShutdownSignal {
|
||||||
|
if let Some(rx) = self.0.lock().await.take() {
|
||||||
|
let _ = rx.await;
|
||||||
|
}
|
||||||
|
ShutdownSignal::FastShutdown
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server.run(RunArgs {
|
||||||
|
shutdown_signal: Box::new(Stop(tokio::sync::Mutex::new(Some(stop)))),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
// 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 (stderr, always on; journald under systemd) and the per-host access log
|
||||||
|
//! (JSON lines in a local file, client IP truncated to /24 or /48, no query strings).
|
||||||
|
//!
|
||||||
|
//! Library crates (Pingora, rustls, h2, ...) are capped at `info` whatever `IANITOR_LOG` says:
|
||||||
|
//! their debug output can include raw request and response headers.
|
||||||
|
|
||||||
|
use std::fs::{File, OpenOptions};
|
||||||
|
use std::io::Write;
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use log::{Level, LevelFilter, Log, Metadata, Record};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use crate::error::EdgeError;
|
||||||
|
|
||||||
|
struct StderrLogger {
|
||||||
|
own: LevelFilter,
|
||||||
|
}
|
||||||
|
|
||||||
|
const LIBRARY_MAX: LevelFilter = LevelFilter::Info;
|
||||||
|
|
||||||
|
impl Log for StderrLogger {
|
||||||
|
fn enabled(&self, m: &Metadata<'_>) -> bool {
|
||||||
|
let limit = if m.target().starts_with("ianitor") {
|
||||||
|
self.own
|
||||||
|
} else {
|
||||||
|
self.own.min(LIBRARY_MAX)
|
||||||
|
};
|
||||||
|
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",
|
||||||
|
};
|
||||||
|
let mut err = std::io::stderr().lock();
|
||||||
|
let _ = writeln!(err, "{lvl} {}: {}", r.target(), r.args());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&self) {
|
||||||
|
let _ = std::io::stderr().flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Install the stderr logger. `level` is `error`, `warn`, `info` (default), `debug` or `trace`.
|
||||||
|
pub fn init(level: Option<&str>) {
|
||||||
|
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(StderrLogger { own })).is_ok() {
|
||||||
|
log::set_max_level(own);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// IPv4 → /24, IPv6 → /48 (IPv4-mapped IPv6 is treated as IPv4).
|
||||||
|
pub fn truncate_ip(ip: IpAddr) -> IpAddr {
|
||||||
|
match ip {
|
||||||
|
IpAddr::V4(v4) => {
|
||||||
|
let [a, b, c, _] = v4.octets();
|
||||||
|
IpAddr::V4(Ipv4Addr::new(a, b, c, 0))
|
||||||
|
}
|
||||||
|
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
|
||||||
|
Some(v4) => truncate_ip(IpAddr::V4(v4)),
|
||||||
|
None => {
|
||||||
|
let s = v6.segments();
|
||||||
|
IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], 0, 0, 0, 0, 0))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct AccessRecord<'a> {
|
||||||
|
pub ts: f64,
|
||||||
|
pub host: &'a str,
|
||||||
|
pub method: &'a str,
|
||||||
|
/// Path only: query strings can carry tokens.
|
||||||
|
pub path: &'a str,
|
||||||
|
pub status: u16,
|
||||||
|
pub remote_ip: Option<String>,
|
||||||
|
pub duration_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn now_secs() -> f64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap_or(Duration::ZERO)
|
||||||
|
.as_secs_f64()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AccessLog {
|
||||||
|
file: Mutex<File>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AccessLog {
|
||||||
|
pub fn open(path: &Path) -> Result<AccessLog, EdgeError> {
|
||||||
|
if let Some(dir) = path.parent() {
|
||||||
|
std::fs::create_dir_all(dir).map_err(|source| EdgeError::Write {
|
||||||
|
path: dir.to_owned(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
let mut opts = OpenOptions::new();
|
||||||
|
opts.create(true).append(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o640);
|
||||||
|
let file = opts.open(path).map_err(|source| EdgeError::Write {
|
||||||
|
path: path.to_owned(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
Ok(AccessLog {
|
||||||
|
file: Mutex::new(file),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write(&self, rec: &AccessRecord<'_>) {
|
||||||
|
let Ok(mut line) = serde_json::to_vec(rec) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
line.push(b'\n');
|
||||||
|
if let Ok(mut f) = self.file.lock()
|
||||||
|
&& let Err(e) = f.write_all(&line)
|
||||||
|
{
|
||||||
|
log::error!(target: "ianitor::access", "cannot write the access log: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn t(s: &str) -> String {
|
||||||
|
truncate_ip(s.parse().unwrap()).to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ipv4_is_truncated_to_24() {
|
||||||
|
assert_eq!(t("192.168.17.42"), "192.168.17.0");
|
||||||
|
assert_eq!(t("127.0.0.1"), "127.0.0.0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ipv6_is_truncated_to_48() {
|
||||||
|
assert_eq!(t("2001:db8:abcd:12:3456::1"), "2001:db8:abcd::");
|
||||||
|
assert_eq!(t("::1"), "::");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mapped_ipv4_is_treated_as_ipv4() {
|
||||||
|
assert_eq!(t("::ffff:10.1.2.3"), "10.1.2.0");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// 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-edge --config <edge.json> [--check] [--admin-socket <path>] [--trial-config <path>]
|
||||||
|
//! [--share-revocations <path>] [--acme-root <ca.pem>]`
|
||||||
|
//!
|
||||||
|
//! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG`
|
||||||
|
//! (error, warn, info, debug, trace; libraries are capped at info).
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::ExitCode;
|
||||||
|
|
||||||
|
use ianitor_edge::{EdgeError, Options};
|
||||||
|
|
||||||
|
fn parse_args() -> Result<(Options, bool), EdgeError> {
|
||||||
|
let mut opts = Options::default();
|
||||||
|
let mut check = false;
|
||||||
|
let mut config = None;
|
||||||
|
let mut args = std::env::args_os().skip(1);
|
||||||
|
while let Some(a) = args.next() {
|
||||||
|
match a.to_str() {
|
||||||
|
Some("--config") => config = args.next().map(PathBuf::from),
|
||||||
|
Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from),
|
||||||
|
Some("--admin-socket") => opts.admin_socket = args.next().map(PathBuf::from),
|
||||||
|
Some("--trial-config") => opts.trial_config = args.next().map(PathBuf::from),
|
||||||
|
Some("--share-revocations") => opts.share_revocations = args.next().map(PathBuf::from),
|
||||||
|
Some("--check") => check = true,
|
||||||
|
Some("--help" | "-h") => {
|
||||||
|
println!(
|
||||||
|
"usage: ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] \
|
||||||
|
[--trial-config <path>] [--share-revocations <path>] [--acme-root <ca.pem>]"
|
||||||
|
);
|
||||||
|
std::process::exit(0);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
return Err(EdgeError::Usage(format!(
|
||||||
|
"unknown argument {}",
|
||||||
|
a.to_string_lossy()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
opts.config =
|
||||||
|
config.ok_or_else(|| EdgeError::Usage("--config <edge.json> is required".into()))?;
|
||||||
|
Ok((opts, check))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> ExitCode {
|
||||||
|
ianitor_edge::logging::init(std::env::var("IANITOR_LOG").ok().as_deref());
|
||||||
|
let started = parse_args().and_then(|(opts, check)| {
|
||||||
|
let shared = ianitor_edge::prepare(&opts)?;
|
||||||
|
log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), shared.current().hosts.len());
|
||||||
|
if check {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
ianitor_edge::server(shared, &opts).map(Some)
|
||||||
|
});
|
||||||
|
match started {
|
||||||
|
Ok(None) => ExitCode::SUCCESS,
|
||||||
|
Ok(Some(server)) => server.run_forever(),
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::edge", "{e}");
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! The share-link visitor pages (docs/ui-api.md §4): one self-contained HTML page each, inline
|
||||||
|
//! CSS, no JavaScript, no external requests, under 8 KB. Only the hostname and a date come
|
||||||
|
//! from the request side, both escaped; the token is echoed only into the password form's
|
||||||
|
//! hidden field (it is already in the visitor's address bar at that point), escaped too.
|
||||||
|
|
||||||
|
use ianitor_core::share::PASSWORD_PATH;
|
||||||
|
use ianitor_core::time::long_date;
|
||||||
|
|
||||||
|
pub enum Problem {
|
||||||
|
WrongPassword,
|
||||||
|
TooMany,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum Page<'a> {
|
||||||
|
Password {
|
||||||
|
host: &'a str,
|
||||||
|
token: &'a str,
|
||||||
|
until: u64,
|
||||||
|
problem: Option<Problem>,
|
||||||
|
},
|
||||||
|
Expired {
|
||||||
|
host: &'a str,
|
||||||
|
until: u64,
|
||||||
|
},
|
||||||
|
Invalid {
|
||||||
|
host: &'a str,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Page<'_> {
|
||||||
|
pub fn status(&self) -> u16 {
|
||||||
|
match self {
|
||||||
|
Page::Password {
|
||||||
|
problem: Some(Problem::TooMany),
|
||||||
|
..
|
||||||
|
} => 429,
|
||||||
|
Page::Password { .. } => 401,
|
||||||
|
Page::Expired { .. } => 410,
|
||||||
|
Page::Invalid { .. } => 403,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn escape(s: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(s.len());
|
||||||
|
for c in s.chars() {
|
||||||
|
match c {
|
||||||
|
'&' => out.push_str("&"),
|
||||||
|
'<' => out.push_str("<"),
|
||||||
|
'>' => out.push_str(">"),
|
||||||
|
'"' => out.push_str("""),
|
||||||
|
'\'' => out.push_str("'"),
|
||||||
|
c if c.is_control() => {}
|
||||||
|
c => out.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
const STYLE: &str = "\
|
||||||
|
*{box-sizing:border-box}\
|
||||||
|
body{margin:0;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;\
|
||||||
|
background:#0c0b0f;color:#f1edf3;font-family:system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;padding:16px}\
|
||||||
|
.card{width:100%;max-width:420px;padding:32px;background:#18151d;border:1px solid #3c3445;border-radius:18px}\
|
||||||
|
@media (max-width:480px){.card{padding:24px}}\
|
||||||
|
.host{color:#cfc6d4;font-size:.95rem;font-weight:600;margin:0 0 16px;overflow-wrap:anywhere}\
|
||||||
|
svg{display:block;margin:0 0 12px}\
|
||||||
|
h1{font-size:1.5rem;font-weight:700;color:#f1edf3;margin:0 0 8px}\
|
||||||
|
p{font-size:1rem;line-height:1.5;color:#cfc6d4;margin:0 0 16px}\
|
||||||
|
label{display:block;color:#cfc6d4;font-size:.9rem;margin:0 0 6px}\
|
||||||
|
input[type=password]{width:100%;height:48px;background:#0c0b0f;border:1px solid #7d7189;border-radius:10px;\
|
||||||
|
color:#f1edf3;font-size:1rem;padding:0 12px}\
|
||||||
|
input[type=password]:focus{outline:none;border-color:#e0a3dc;box-shadow:0 0 0 4px rgba(224,163,220,.16)}\
|
||||||
|
.err{color:#e2683a;font-size:.92rem;margin:8px 0 0;display:flex;gap:6px;align-items:center}\
|
||||||
|
button{margin-top:16px;width:100%;height:48px;border-radius:12px;border:1px solid #c77cc1;color:#fff;font-weight:700;\
|
||||||
|
font-size:1rem;background:linear-gradient(#8d3b89,#76306f 55%,#5c2257)}\
|
||||||
|
button:focus{outline:2px solid #f2c9ee;outline-offset:2px}\
|
||||||
|
button:disabled{opacity:.5}\
|
||||||
|
.small{font-size:.92rem;margin:16px 0 0}\
|
||||||
|
a{color:#e0a3dc;display:inline-flex;align-items:center;min-height:44px}\
|
||||||
|
footer{color:#a99eb1;font-size:.72rem;letter-spacing:.2em;text-transform:uppercase;margin-top:16px}";
|
||||||
|
|
||||||
|
fn icon(kind: &str) -> String {
|
||||||
|
let (colour, body) = match kind {
|
||||||
|
// lock
|
||||||
|
"lock" => (
|
||||||
|
"#e0a3dc",
|
||||||
|
"<rect x=\"8\" y=\"18\" width=\"24\" height=\"16\" rx=\"3\"/><path d=\"M13 18v-5a7 7 0 0 1 14 0v5\"/>",
|
||||||
|
),
|
||||||
|
// clock
|
||||||
|
"clock" => (
|
||||||
|
"#d99a35",
|
||||||
|
"<circle cx=\"20\" cy=\"20\" r=\"14\"/><path d=\"M20 12v8l5 4\"/>",
|
||||||
|
),
|
||||||
|
// broken link
|
||||||
|
_ => (
|
||||||
|
"#d99a35",
|
||||||
|
"<path d=\"M17 23l-3 3a5 5 0 0 1-7-7l3-3\"/><path d=\"M23 17l3-3a5 5 0 0 0-7-7l-3 3\"/><path d=\"M8 8l3 3M29 29l3 3M28 12h4M8 28H12\"/>",
|
||||||
|
),
|
||||||
|
};
|
||||||
|
format!(
|
||||||
|
"<svg width=\"40\" height=\"40\" viewBox=\"0 0 40 40\" fill=\"none\" stroke=\"{colour}\" stroke-width=\"2.2\" \
|
||||||
|
stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">{body}</svg>"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const RING: &str = "<svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\" fill=\"none\" stroke=\"#e2683a\" stroke-width=\"2\" aria-hidden=\"true\"><circle cx=\"7\" cy=\"7\" r=\"5\"/></svg>";
|
||||||
|
|
||||||
|
fn shell(host: &str, inner: &str, title: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
|
||||||
|
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
|
||||||
|
<meta name=\"referrer\" content=\"no-referrer\"><meta name=\"robots\" content=\"noindex\">\
|
||||||
|
<title>{title}</title><style>{STYLE}</style></head><body><main class=\"card\">\
|
||||||
|
<p class=\"host\">{}</p>{inner}</main><footer>Ianitor Domi</footer></body></html>",
|
||||||
|
escape(host)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render(p: &Page<'_>) -> String {
|
||||||
|
match p {
|
||||||
|
Page::Password {
|
||||||
|
host,
|
||||||
|
token,
|
||||||
|
until,
|
||||||
|
problem,
|
||||||
|
} => {
|
||||||
|
let h = escape(host);
|
||||||
|
let (msg, disabled) = match problem {
|
||||||
|
Some(Problem::WrongPassword) => (
|
||||||
|
format!(
|
||||||
|
"<p class=\"err\" role=\"alert\">{RING}That password is not right. Check it with the person who sent the link.</p>"
|
||||||
|
),
|
||||||
|
"",
|
||||||
|
),
|
||||||
|
Some(Problem::TooMany) => (
|
||||||
|
format!(
|
||||||
|
"<p class=\"err\" role=\"alert\">{RING}Too many tries. Wait a minute, then try again.</p>"
|
||||||
|
),
|
||||||
|
" disabled",
|
||||||
|
),
|
||||||
|
None => (String::new(), ""),
|
||||||
|
};
|
||||||
|
let inner = format!(
|
||||||
|
"{}<h1>This link is protected</h1>\
|
||||||
|
<p>Someone shared {h} with you. Enter the password they gave you.</p>\
|
||||||
|
<form method=\"post\" action=\"{PASSWORD_PATH}\">\
|
||||||
|
<input type=\"hidden\" name=\"t\" value=\"{}\">\
|
||||||
|
<label for=\"pw\">Password</label>\
|
||||||
|
<input id=\"pw\" type=\"password\" name=\"password\" autocomplete=\"current-password\" autofocus required>\
|
||||||
|
{msg}<button type=\"submit\"{disabled}>Open</button></form>\
|
||||||
|
<p class=\"small\">The link works until {}.</p>",
|
||||||
|
icon("lock"),
|
||||||
|
escape(token),
|
||||||
|
long_date(*until)
|
||||||
|
);
|
||||||
|
shell(host, &inner, "This link is protected")
|
||||||
|
}
|
||||||
|
Page::Expired { host, until } => {
|
||||||
|
let inner = format!(
|
||||||
|
"{}<h1>This link has expired</h1>\
|
||||||
|
<p>It worked until {}. Ask the person who sent it for a new one.</p>\
|
||||||
|
<a href=\"/\">Have an account? Sign in</a>",
|
||||||
|
icon("clock"),
|
||||||
|
long_date(*until)
|
||||||
|
);
|
||||||
|
shell(host, &inner, "This link has expired")
|
||||||
|
}
|
||||||
|
Page::Invalid { host } => {
|
||||||
|
let inner = format!(
|
||||||
|
"{}<h1>This link no longer works</h1>\
|
||||||
|
<p>It may have been stopped, or not copied in full. Ask the person who sent it for a new one.</p>\
|
||||||
|
<a href=\"/\">Have an account? Sign in</a>",
|
||||||
|
icon("broken")
|
||||||
|
);
|
||||||
|
shell(host, &inner, "This link no longer works")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pages_are_small_and_escaped() {
|
||||||
|
for p in [
|
||||||
|
Page::Password {
|
||||||
|
host: "<b>x</b>",
|
||||||
|
token: "\"><script>",
|
||||||
|
until: 1_794_666_000,
|
||||||
|
problem: Some(Problem::WrongPassword),
|
||||||
|
},
|
||||||
|
Page::Expired {
|
||||||
|
host: "a.test",
|
||||||
|
until: 0,
|
||||||
|
},
|
||||||
|
Page::Invalid { host: "a.test" },
|
||||||
|
] {
|
||||||
|
let html = render(&p);
|
||||||
|
assert!(html.len() < 8 * 1024, "{}", html.len());
|
||||||
|
assert!(!html.contains("<script"));
|
||||||
|
assert!(!html.contains("<b>x"));
|
||||||
|
assert!(!html.contains("http://") && !html.contains("https://"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,437 @@
|
|||||||
|
// 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 HTTPS reverse proxy. Order per request (same as the Caddy compiler emits):
|
||||||
|
//! host lookup (unknown → 404) → forward-auth → websocket refusal → upstream with header rules.
|
||||||
|
|
||||||
|
use std::net::IpAddr;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use http::header;
|
||||||
|
use pingora::connectors::http::Connector;
|
||||||
|
use pingora::http::{RequestHeader, ResponseHeader};
|
||||||
|
use pingora::proxy::{FailToProxy, ProxyHttp, Session};
|
||||||
|
use pingora::upstreams::peer::HttpPeer;
|
||||||
|
use pingora::{Error, ErrorSource, ErrorType, Result};
|
||||||
|
|
||||||
|
use crate::fetch;
|
||||||
|
use crate::forward_auth::{self, Outcome};
|
||||||
|
use crate::logging::{AccessRecord, now_secs, truncate_ip};
|
||||||
|
use crate::runtime::{HostRt, Op, Runtime};
|
||||||
|
use crate::share::{self, Decision};
|
||||||
|
use crate::shared::Shared;
|
||||||
|
|
||||||
|
pub struct EdgeProxy {
|
||||||
|
pub shared: Arc<Shared>,
|
||||||
|
pub connector: Connector,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Ctx {
|
||||||
|
/// The runtime current when the request started; used for the whole request.
|
||||||
|
rt: Option<Arc<Runtime>>,
|
||||||
|
host: Option<Arc<HostRt>>,
|
||||||
|
/// Chosen upstream and its resolved addresses; connect failures move to the next address.
|
||||||
|
upstream: Option<usize>,
|
||||||
|
addrs: Vec<std::net::SocketAddr>,
|
||||||
|
addr_idx: usize,
|
||||||
|
/// The Host header as the client sent it (with port, if any).
|
||||||
|
host_header: String,
|
||||||
|
start: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The request's host: the authority of an absolute-form target (or HTTP/2 :authority) wins
|
||||||
|
/// over the Host header, as RFC 9112 §3.2.2 requires and Go/Caddy do.
|
||||||
|
pub fn host_header(req: &RequestHeader) -> String {
|
||||||
|
req.uri
|
||||||
|
.authority()
|
||||||
|
.map(|a| a.as_str().to_owned())
|
||||||
|
.or_else(|| {
|
||||||
|
req.headers
|
||||||
|
.get(header::HOST)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(str::to_owned)
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Host without port, lowercase. `[v6]:port` keeps the brackets off.
|
||||||
|
pub fn hostname(host_header: &str) -> String {
|
||||||
|
let h = host_header.trim();
|
||||||
|
let name = if let Some(rest) = h.strip_prefix('[') {
|
||||||
|
rest.split(']').next().unwrap_or("")
|
||||||
|
} else {
|
||||||
|
h.rsplit_once(':').map_or(h, |(n, port)| {
|
||||||
|
if port.bytes().all(|c| c.is_ascii_digit()) {
|
||||||
|
n
|
||||||
|
} else {
|
||||||
|
h
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
|
name.to_ascii_lowercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn client_ip(session: &Session) -> Option<IpAddr> {
|
||||||
|
session
|
||||||
|
.client_addr()
|
||||||
|
.and_then(|a| a.as_inet())
|
||||||
|
.map(|a| a.ip())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A response with an empty body, like Caddy's `static_response` and error responses.
|
||||||
|
pub async fn respond_empty(session: &mut Session, code: u16) -> Result<()> {
|
||||||
|
let mut resp = ResponseHeader::build(code, Some(1))?;
|
||||||
|
resp.insert_header(header::CONTENT_LENGTH, "0")?;
|
||||||
|
session.write_response_header(Box::new(resp), true).await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(
|
||||||
|
ops: &[Op],
|
||||||
|
mut set: impl FnMut(&http::HeaderName, Option<&http::HeaderValue>) -> Result<()>,
|
||||||
|
) -> Result<()> {
|
||||||
|
for op in ops {
|
||||||
|
match op {
|
||||||
|
Op::Set(n, v) => set(n, Some(v))?,
|
||||||
|
Op::Remove(n) => set(n, None)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Any `Upgrade` field, any comma-separated token, equal to `websocket` (case-insensitive).
|
||||||
|
pub fn is_websocket_upgrade(req: &RequestHeader) -> bool {
|
||||||
|
req.headers.get_all(header::UPGRADE).iter().any(|v| {
|
||||||
|
String::from_utf8_lossy(v.as_bytes())
|
||||||
|
.split(',')
|
||||||
|
.any(|t| t.trim().eq_ignore_ascii_case("websocket"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ProxyHttp for EdgeProxy {
|
||||||
|
type CTX = Ctx;
|
||||||
|
|
||||||
|
fn new_ctx(&self) -> Ctx {
|
||||||
|
Ctx {
|
||||||
|
rt: None,
|
||||||
|
host: None,
|
||||||
|
upstream: None,
|
||||||
|
addrs: Vec::new(),
|
||||||
|
addr_idx: 0,
|
||||||
|
host_header: String::new(),
|
||||||
|
start: Instant::now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result<bool> {
|
||||||
|
let rt = self.shared.current();
|
||||||
|
ctx.rt = Some(rt.clone());
|
||||||
|
ctx.host_header = host_header(session.req_header());
|
||||||
|
let Some(host) = rt.host(&hostname(&ctx.host_header)).cloned() else {
|
||||||
|
respond_empty(session, 404).await?;
|
||||||
|
return Ok(true);
|
||||||
|
};
|
||||||
|
ctx.host = Some(host.clone());
|
||||||
|
|
||||||
|
let mut shared_access = false;
|
||||||
|
if !host.cfg.share_links {
|
||||||
|
share::strip_any_token(session)?;
|
||||||
|
} else {
|
||||||
|
let ip = client_ip(session);
|
||||||
|
let revs = self.shared.revocations();
|
||||||
|
match share::handle(
|
||||||
|
session,
|
||||||
|
&host.cfg.hostname,
|
||||||
|
rt.share_key.as_deref(),
|
||||||
|
&revs,
|
||||||
|
&self.shared.throttle,
|
||||||
|
ip,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
Decision::Answered => return Ok(true),
|
||||||
|
Decision::Allowed => shared_access = true,
|
||||||
|
Decision::Continue => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if host.cfg.forward_auth {
|
||||||
|
let fa = rt.forward_auth.as_ref().ok_or_else(|| {
|
||||||
|
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
|
||||||
|
})?;
|
||||||
|
// Client-sent identity headers never survive, whatever copy_headers says.
|
||||||
|
let req = session.req_header_mut();
|
||||||
|
for name in &fa.strip_headers {
|
||||||
|
req.remove_header(name);
|
||||||
|
}
|
||||||
|
if shared_access {
|
||||||
|
// A valid share link stands in for the sign-in on its prefix.
|
||||||
|
return self.after_auth(session, &host).await;
|
||||||
|
}
|
||||||
|
let ip = client_ip(session).map(|i| i.to_string());
|
||||||
|
let outcome = match forward_auth::check(
|
||||||
|
&self.connector,
|
||||||
|
fa,
|
||||||
|
session,
|
||||||
|
&ctx.host_header,
|
||||||
|
ip,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::auth", "forward-auth for {} failed, denying: {e}", host.cfg.hostname);
|
||||||
|
return Err(Error::explain(
|
||||||
|
ErrorType::HTTPStatus(502),
|
||||||
|
"forward-auth unreachable",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match outcome {
|
||||||
|
Outcome::Deny(resp, body) => {
|
||||||
|
let head = session.req_header().method == http::Method::HEAD;
|
||||||
|
let end = head || body.is_empty();
|
||||||
|
session.write_response_header(resp, end).await?;
|
||||||
|
if !end {
|
||||||
|
session.write_response_body(Some(body), true).await?;
|
||||||
|
}
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
Outcome::Allow(copy) => {
|
||||||
|
let req = session.req_header_mut();
|
||||||
|
for (name, value) in copy {
|
||||||
|
req.remove_header(&name);
|
||||||
|
if let Some(v) = value {
|
||||||
|
req.insert_header(name, v)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.after_auth(session, &host).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
|
||||||
|
let host = ctx
|
||||||
|
.host
|
||||||
|
.clone()
|
||||||
|
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?;
|
||||||
|
let idx = match ctx.upstream {
|
||||||
|
// A retry after a failed connect: same upstream, next address.
|
||||||
|
Some(i) => i,
|
||||||
|
None => {
|
||||||
|
let n = host.upstreams.len();
|
||||||
|
let first = host.next.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let i = (0..n)
|
||||||
|
.map(|k| (first + k) % n)
|
||||||
|
.find(|&k| host.upstreams[k].healthy.load(Ordering::Relaxed))
|
||||||
|
.ok_or_else(|| {
|
||||||
|
Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream")
|
||||||
|
})?;
|
||||||
|
let up = &host.upstreams[i];
|
||||||
|
ctx.addrs = match up.resolve().await {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(e) => {
|
||||||
|
log::warn!(target: "ianitor::proxy", "{}: cannot resolve upstream {}: {e}", host.cfg.hostname, up.authority);
|
||||||
|
return Err(Error::explain(
|
||||||
|
ErrorType::HTTPStatus(502),
|
||||||
|
"upstream does not resolve",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
ctx.upstream = Some(i);
|
||||||
|
ctx.addr_idx = 0;
|
||||||
|
i
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let up = &host.upstreams[idx];
|
||||||
|
let addr = *ctx
|
||||||
|
.addrs
|
||||||
|
.get(ctx.addr_idx)
|
||||||
|
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(502), "no address left"))?;
|
||||||
|
log::debug!(target: "ianitor::proxy", "{}: upstream {} at {addr}", host.cfg.hostname, up.authority);
|
||||||
|
Ok(Box::new(fetch::peer(addr, up)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fail_to_connect(
|
||||||
|
&self,
|
||||||
|
_s: &mut Session,
|
||||||
|
_p: &HttpPeer,
|
||||||
|
ctx: &mut Ctx,
|
||||||
|
mut e: Box<Error>,
|
||||||
|
) -> Box<Error> {
|
||||||
|
// Like Caddy's dialer: try every address of the chosen upstream, then 502. Other
|
||||||
|
// upstreams are not tried (Caddy's default has no lb_try_duration).
|
||||||
|
if ctx.addr_idx + 1 < ctx.addrs.len() {
|
||||||
|
ctx.addr_idx += 1;
|
||||||
|
e.set_retry(true);
|
||||||
|
} else {
|
||||||
|
e.set_retry(false);
|
||||||
|
}
|
||||||
|
e
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn upstream_request_filter(
|
||||||
|
&self,
|
||||||
|
session: &mut Session,
|
||||||
|
req: &mut RequestHeader,
|
||||||
|
ctx: &mut Ctx,
|
||||||
|
) -> Result<()> {
|
||||||
|
// Origin-form target and the routed host, also for absolute-form requests.
|
||||||
|
if req.uri.authority().is_some() {
|
||||||
|
let pq = req
|
||||||
|
.uri
|
||||||
|
.path_and_query()
|
||||||
|
.map_or("/", |p| p.as_str())
|
||||||
|
.to_owned();
|
||||||
|
let uri = pq
|
||||||
|
.parse::<http::Uri>()
|
||||||
|
.map_err(|_| Error::explain(ErrorType::HTTPStatus(400), "bad request target"))?;
|
||||||
|
req.set_uri(uri);
|
||||||
|
}
|
||||||
|
req.insert_header(header::HOST, ctx.host_header.as_str())?;
|
||||||
|
// Forwarding headers are always edge's own; client-supplied values are replaced.
|
||||||
|
match client_ip(session) {
|
||||||
|
Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
|
||||||
|
None => {
|
||||||
|
req.remove_header("X-Forwarded-For");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
req.insert_header("X-Forwarded-Proto", "https")?;
|
||||||
|
req.insert_header("X-Forwarded-Host", ctx.host_header.as_str())?;
|
||||||
|
if let Some(host) = &ctx.host {
|
||||||
|
apply(&host.request_ops, |n, v| {
|
||||||
|
match v {
|
||||||
|
Some(v) => req.insert_header(n.clone(), v.clone())?,
|
||||||
|
None => {
|
||||||
|
req.remove_header(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn upstream_response_filter(
|
||||||
|
&self,
|
||||||
|
_s: &mut Session,
|
||||||
|
resp: &mut ResponseHeader,
|
||||||
|
ctx: &mut Ctx,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(host) = &ctx.host else { return Ok(()) };
|
||||||
|
apply(&host.response_ops, |n, v| {
|
||||||
|
match v {
|
||||||
|
Some(v) => resp.insert_header(n.clone(), v.clone())?,
|
||||||
|
None => {
|
||||||
|
resp.remove_header(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
|
// Defence in depth: never hand a secret back to a client, even if the upstream echoes it.
|
||||||
|
if !host.secret_values.is_empty() {
|
||||||
|
let leaking: Vec<http::HeaderName> = resp
|
||||||
|
.headers
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, v)| host.secret_values.iter().any(|s| contains(v.as_bytes(), s)))
|
||||||
|
.map(|(n, _)| n.clone())
|
||||||
|
.collect();
|
||||||
|
for n in leaking {
|
||||||
|
log::warn!(target: "ianitor::secrets", "{}: dropped response header `{n}` because it contained a secret", host.cfg.hostname);
|
||||||
|
resp.remove_header(&n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fail_to_proxy(&self, session: &mut Session, e: &Error, _ctx: &mut Ctx) -> FailToProxy {
|
||||||
|
let code = match e.etype() {
|
||||||
|
ErrorType::HTTPStatus(c) => *c,
|
||||||
|
_ => match e.esource() {
|
||||||
|
ErrorSource::Upstream => 502,
|
||||||
|
ErrorSource::Downstream => match e.etype() {
|
||||||
|
ErrorType::WriteError | ErrorType::ReadError | ErrorType::ConnectionClosed => 0,
|
||||||
|
_ => 400,
|
||||||
|
},
|
||||||
|
ErrorSource::Internal | ErrorSource::Unset => 500,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if code > 0
|
||||||
|
&& session.response_written().is_none()
|
||||||
|
&& let Err(err) = respond_empty(session, code).await
|
||||||
|
{
|
||||||
|
log::debug!(target: "ianitor::proxy", "could not send the error response: {err}");
|
||||||
|
}
|
||||||
|
FailToProxy {
|
||||||
|
error_code: code,
|
||||||
|
can_reuse_downstream: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn logging(&self, session: &mut Session, _e: Option<&Error>, ctx: &mut Ctx) {
|
||||||
|
let Some(host) = &ctx.host else { return };
|
||||||
|
if !host.cfg.access_log {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(log) = ctx.rt.as_ref().and_then(|rt| rt.access_log.as_ref()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let req = session.req_header();
|
||||||
|
log.write(&AccessRecord {
|
||||||
|
ts: now_secs(),
|
||||||
|
host: &host.cfg.hostname,
|
||||||
|
method: req.method.as_str(),
|
||||||
|
path: req.uri.path(),
|
||||||
|
status: session.response_written().map_or(0, |r| r.status.as_u16()),
|
||||||
|
remote_ip: client_ip(session).map(|i| truncate_ip(i).to_string()),
|
||||||
|
duration_ms: u64::try_from(ctx.start.elapsed().as_millis()).unwrap_or(u64::MAX),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_summary(&self, session: &Session, ctx: &Ctx) -> String {
|
||||||
|
// Method, host and path only: no query string, no headers.
|
||||||
|
let req = session.req_header();
|
||||||
|
format!("{} {}{}", req.method, ctx.host_header, req.uri.path())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EdgeProxy {
|
||||||
|
/// The steps after the sign-in check: websocket refusal.
|
||||||
|
async fn after_auth(&self, session: &mut Session, host: &HostRt) -> Result<bool> {
|
||||||
|
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
|
||||||
|
respond_empty(session, 403).await?;
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
||||||
|
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostname_strips_port_and_case() {
|
||||||
|
assert_eq!(hostname("App.Test:8443"), "app.test");
|
||||||
|
assert_eq!(hostname("app.test"), "app.test");
|
||||||
|
assert_eq!(hostname("[::1]:443"), "::1");
|
||||||
|
assert_eq!(hostname(""), "");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn contains_finds_substrings() {
|
||||||
|
assert!(contains(b"abc-secret-def", b"secret"));
|
||||||
|
assert!(!contains(b"abc", b""));
|
||||||
|
assert!(!contains(b"sec", b"secret"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,505 @@
|
|||||||
|
// 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 edge config turned into ready-to-serve state: parsed upstreams and header
|
||||||
|
//! names, secrets loaded, certificates loaded, the share-link key loaded. Built at startup
|
||||||
|
//! and again on every reload; a reload swaps the whole [`Runtime`] at once (see `shared`).
|
||||||
|
|
||||||
|
use std::collections::{BTreeSet, HashMap, VecDeque};
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use http::{HeaderName, HeaderValue};
|
||||||
|
use ianitor_core::edge_config::{
|
||||||
|
EDGE_CONFIG_VERSION, EdgeConfig, EdgeHeaderOp, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
|
||||||
|
};
|
||||||
|
use ianitor_core::share::{KEY_CREDENTIAL, ShareKey};
|
||||||
|
use rustls::sign::CertifiedKey;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use crate::error::EdgeError;
|
||||||
|
use crate::logging::AccessLog;
|
||||||
|
use crate::secrets::Secrets;
|
||||||
|
use crate::tls::{certified_key, not_after};
|
||||||
|
|
||||||
|
pub enum Op {
|
||||||
|
Set(HeaderName, HeaderValue),
|
||||||
|
Remove(HeaderName),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One health probe result, as reported on the admin socket.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Check {
|
||||||
|
/// Increases by one per probe of this upstream.
|
||||||
|
pub seq: u64,
|
||||||
|
/// Unix seconds.
|
||||||
|
pub at: u64,
|
||||||
|
pub ok: bool,
|
||||||
|
/// `health_check` (the host's own check) or `watch` (`GET /` during a trial).
|
||||||
|
pub source: &'static str,
|
||||||
|
/// `refused`, `timeout`, `name`, `tls`, `server_error`, `not_found`, `redirect`,
|
||||||
|
/// `sign_in` or `bad_answer`; `None` when `ok`.
|
||||||
|
pub kind: Option<&'static str>,
|
||||||
|
pub status: Option<u16>,
|
||||||
|
pub latency_ms: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last few probe results of one upstream.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct HealthRecord {
|
||||||
|
inner: Mutex<(u64, VecDeque<Check>)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many results are kept per upstream.
|
||||||
|
pub const KEPT_CHECKS: usize = 5;
|
||||||
|
|
||||||
|
impl HealthRecord {
|
||||||
|
pub fn record(&self, mut c: Check) {
|
||||||
|
if let Ok(mut g) = self.inner.lock() {
|
||||||
|
g.0 += 1;
|
||||||
|
c.seq = g.0;
|
||||||
|
g.1.push_back(c);
|
||||||
|
while g.1.len() > KEPT_CHECKS {
|
||||||
|
g.1.pop_front();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn checks(&self) -> Vec<Check> {
|
||||||
|
self.inner
|
||||||
|
.lock()
|
||||||
|
.map(|g| g.1.iter().cloned().collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct UpstreamRt {
|
||||||
|
/// Host name or IP literal (IPv6 without brackets).
|
||||||
|
pub host: String,
|
||||||
|
pub port: u16,
|
||||||
|
/// `host:port` as configured; the Host header of health checks.
|
||||||
|
pub authority: String,
|
||||||
|
pub tls: bool,
|
||||||
|
pub sni: String,
|
||||||
|
pub healthy: AtomicBool,
|
||||||
|
pub health: HealthRecord,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct HostRt {
|
||||||
|
pub cfg: EdgeHost,
|
||||||
|
pub upstreams: Vec<UpstreamRt>,
|
||||||
|
pub next: AtomicUsize,
|
||||||
|
pub request_ops: Vec<Op>,
|
||||||
|
pub response_ops: Vec<Op>,
|
||||||
|
/// Values of the secrets this host injects; a response header containing one is dropped.
|
||||||
|
pub secret_values: Vec<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ForwardAuthRt {
|
||||||
|
pub upstream: UpstreamRt,
|
||||||
|
pub path_and_query: String,
|
||||||
|
pub copy_headers: Vec<HeaderName>,
|
||||||
|
/// Removed from every client request on a forward-auth host before anything else.
|
||||||
|
pub strip_headers: Vec<HeaderName>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Runtime {
|
||||||
|
pub cfg: EdgeConfig,
|
||||||
|
pub hosts: HashMap<String, Arc<HostRt>>,
|
||||||
|
pub forward_auth: Option<ForwardAuthRt>,
|
||||||
|
pub access_log: Option<AccessLog>,
|
||||||
|
/// Domi certificates (`tls = "domi"`), by hostname.
|
||||||
|
pub file_certs: HashMap<String, Arc<CertifiedKey>>,
|
||||||
|
/// `notAfter` (Unix seconds) of each Domi certificate.
|
||||||
|
pub file_cert_expiry: HashMap<String, i64>,
|
||||||
|
/// Loaded when any host has share links.
|
||||||
|
pub share_key: Option<Arc<ShareKey>>,
|
||||||
|
/// SHA-256 (hex) of the config file bytes this runtime was built from; empty when it was
|
||||||
|
/// built from a parsed config.
|
||||||
|
pub sha256: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Runtime {
|
||||||
|
pub fn host(&self, name: &str) -> Option<&Arc<HostRt>> {
|
||||||
|
self.hosts.get(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acme_hosts(&self) -> Vec<String> {
|
||||||
|
self.cfg
|
||||||
|
.hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| h.tls == EdgeTls::Acme)
|
||||||
|
.map(|h| h.hostname.clone())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acme_dir(&self) -> PathBuf {
|
||||||
|
Path::new(&self.cfg.state_dir).join("acme")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sha256_hex(data: &[u8]) -> String {
|
||||||
|
ring::digest::digest(&ring::digest::SHA256, data)
|
||||||
|
.as_ref()
|
||||||
|
.iter()
|
||||||
|
.map(|b| format!("{b:02x}"))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Largest config file read.
|
||||||
|
const MAX_CONFIG_BYTES: u64 = 16 << 20;
|
||||||
|
|
||||||
|
/// Read and parse a config file; returns the parsed config and the SHA-256 of its bytes.
|
||||||
|
pub fn read_config_file(path: &Path) -> Result<(EdgeConfig, String), EdgeError> {
|
||||||
|
let read_err = |source| EdgeError::Read {
|
||||||
|
path: path.to_owned(),
|
||||||
|
source,
|
||||||
|
};
|
||||||
|
let meta = std::fs::metadata(path).map_err(read_err)?;
|
||||||
|
if meta.len() > MAX_CONFIG_BYTES {
|
||||||
|
return Err(EdgeError::Config {
|
||||||
|
path: path.to_owned(),
|
||||||
|
message: "the file is larger than 16 MiB".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let bytes = std::fs::read(path).map_err(read_err)?;
|
||||||
|
let text = std::str::from_utf8(&bytes).map_err(|_| EdgeError::Config {
|
||||||
|
path: path.to_owned(),
|
||||||
|
message: "the file is not UTF-8".into(),
|
||||||
|
})?;
|
||||||
|
let cfg = parse_config(path, text)?;
|
||||||
|
Ok((cfg, sha256_hex(&bytes)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
|
||||||
|
read_config_file(path).map(|(c, _)| c)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_config(path: &Path, text: &str) -> Result<EdgeConfig, EdgeError> {
|
||||||
|
let cfg: EdgeConfig = serde_json::from_str(text).map_err(|e| EdgeError::Config {
|
||||||
|
path: path.to_owned(),
|
||||||
|
message: e.to_string(),
|
||||||
|
})?;
|
||||||
|
if cfg.version != EDGE_CONFIG_VERSION {
|
||||||
|
return Err(EdgeError::Version {
|
||||||
|
found: cfg.version,
|
||||||
|
expected: EDGE_CONFIG_VERSION,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
||||||
|
let err = |reason: &str| EdgeError::Upstream {
|
||||||
|
address: u.address.clone(),
|
||||||
|
reason: reason.to_owned(),
|
||||||
|
};
|
||||||
|
let (host, port) = u
|
||||||
|
.address
|
||||||
|
.rsplit_once(':')
|
||||||
|
.ok_or_else(|| err("expected host:port"))?;
|
||||||
|
let port: u16 = port.parse().map_err(|_| err("bad port"))?;
|
||||||
|
let host = host
|
||||||
|
.strip_prefix('[')
|
||||||
|
.and_then(|h| h.strip_suffix(']'))
|
||||||
|
.unwrap_or(host);
|
||||||
|
if host.is_empty() {
|
||||||
|
return Err(err("empty host"));
|
||||||
|
}
|
||||||
|
Ok(UpstreamRt {
|
||||||
|
host: host.to_owned(),
|
||||||
|
port,
|
||||||
|
authority: u.address.clone(),
|
||||||
|
tls: u.tls,
|
||||||
|
sni: u.sni.clone(),
|
||||||
|
healthy: AtomicBool::new(true),
|
||||||
|
health: HealthRecord::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How long a name lookup may take before the request fails with 502. Matches the 3 s dial
|
||||||
|
/// timeout (Caddy's default), which in Go also bounds the lookup.
|
||||||
|
pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(3);
|
||||||
|
|
||||||
|
impl UpstreamRt {
|
||||||
|
/// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's
|
||||||
|
/// dialer), so DNS changes and unresolvable names only affect requests, not startup.
|
||||||
|
/// A lookup that takes longer than [`RESOLVE_TIMEOUT`] is an error.
|
||||||
|
pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
|
||||||
|
resolve_with(
|
||||||
|
&self.host,
|
||||||
|
self.port,
|
||||||
|
RESOLVE_TIMEOUT,
|
||||||
|
|host, port| async move {
|
||||||
|
tokio::net::lookup_host((host.as_str(), port))
|
||||||
|
.await
|
||||||
|
.map(Iterator::collect)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`UpstreamRt::resolve`] with the lookup passed in, so the deadline can be tested.
|
||||||
|
pub async fn resolve_with<F, Fut>(
|
||||||
|
host: &str,
|
||||||
|
port: u16,
|
||||||
|
deadline: Duration,
|
||||||
|
lookup: F,
|
||||||
|
) -> std::io::Result<Vec<SocketAddr>>
|
||||||
|
where
|
||||||
|
F: FnOnce(String, u16) -> Fut,
|
||||||
|
Fut: Future<Output = std::io::Result<Vec<SocketAddr>>>,
|
||||||
|
{
|
||||||
|
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
|
||||||
|
return Ok(vec![SocketAddr::new(ip, port)]);
|
||||||
|
}
|
||||||
|
let addrs = match tokio::time::timeout(deadline, lookup(host.to_owned(), port)).await {
|
||||||
|
Ok(r) => r?,
|
||||||
|
Err(_) => {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::TimedOut,
|
||||||
|
format!("name lookup took longer than {deadline:?}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if addrs.is_empty() {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::NotFound,
|
||||||
|
"name resolves to no address",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(addrs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header_name(name: &str) -> Result<HeaderName, EdgeError> {
|
||||||
|
HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header {
|
||||||
|
name: name.to_owned(),
|
||||||
|
reason: "not a valid header name",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ops(
|
||||||
|
list: &[EdgeHeaderOp],
|
||||||
|
secrets: &Secrets,
|
||||||
|
values: &mut Vec<Vec<u8>>,
|
||||||
|
) -> Result<Vec<Op>, EdgeError> {
|
||||||
|
list.iter()
|
||||||
|
.map(|op| match op {
|
||||||
|
EdgeHeaderOp::Remove { name } => Ok(Op::Remove(header_name(name)?)),
|
||||||
|
EdgeHeaderOp::Set { name, value } => {
|
||||||
|
let v = match value {
|
||||||
|
EdgeValue::Literal { value } => {
|
||||||
|
HeaderValue::from_str(value).map_err(|_| EdgeError::Header {
|
||||||
|
name: name.clone(),
|
||||||
|
reason: "value is not a valid header value",
|
||||||
|
})?
|
||||||
|
}
|
||||||
|
EdgeValue::Secret { name: secret } => {
|
||||||
|
let s = secrets.get(secret).ok_or(EdgeError::Secret {
|
||||||
|
name: secret.clone(),
|
||||||
|
reason: "not loaded",
|
||||||
|
})?;
|
||||||
|
values.push(s.as_bytes().to_vec());
|
||||||
|
s.header_value()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(Op::Set(header_name(name)?, v))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read, parse and build a config file. Fails on the first problem; edge never serves a
|
||||||
|
/// half-built config.
|
||||||
|
pub fn build_file(path: &Path, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
|
||||||
|
let (cfg, sha) = read_config_file(path)?;
|
||||||
|
let mut rt = build(cfg, credentials_dir)?;
|
||||||
|
rt.sha256 = sha;
|
||||||
|
Ok(rt)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load secrets, certificates and the share-link key. Fails on the first problem.
|
||||||
|
pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
|
||||||
|
let mut names: BTreeSet<String> = cfg
|
||||||
|
.hosts
|
||||||
|
.iter()
|
||||||
|
.flat_map(|h| h.request_headers.iter().chain(&h.response_headers))
|
||||||
|
.filter_map(|op| match op {
|
||||||
|
EdgeHeaderOp::Set {
|
||||||
|
value: EdgeValue::Secret { name },
|
||||||
|
..
|
||||||
|
} => Some(name.clone()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let wants_share = cfg.hosts.iter().any(|h| h.share_links);
|
||||||
|
if wants_share {
|
||||||
|
names.insert(KEY_CREDENTIAL.to_owned());
|
||||||
|
}
|
||||||
|
let secrets = Secrets::load(&names, credentials_dir)?;
|
||||||
|
let share_key = match secrets.get(KEY_CREDENTIAL) {
|
||||||
|
Some(s) if wants_share => Some(Arc::new(ShareKey::new(s.as_bytes()).map_err(|_| {
|
||||||
|
EdgeError::Secret {
|
||||||
|
name: KEY_CREDENTIAL.into(),
|
||||||
|
reason: "the share-link key must be at least 32 characters",
|
||||||
|
}
|
||||||
|
})?)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut file_certs = HashMap::new();
|
||||||
|
let mut file_cert_expiry = HashMap::new();
|
||||||
|
let mut hosts = HashMap::new();
|
||||||
|
for h in &cfg.hosts {
|
||||||
|
if let EdgeTls::Files { cert, key } = &h.tls {
|
||||||
|
let read = |p: &str| {
|
||||||
|
std::fs::read(p).map_err(|source| EdgeError::Read {
|
||||||
|
path: PathBuf::from(p),
|
||||||
|
source,
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let cert_pem = read(cert)?;
|
||||||
|
let pair = certified_key(&cert_pem, &read(key)?).map_err(|reason| EdgeError::Cert {
|
||||||
|
host: h.hostname.clone(),
|
||||||
|
reason,
|
||||||
|
})?;
|
||||||
|
if let Some(exp) = not_after(&cert_pem) {
|
||||||
|
file_cert_expiry.insert(h.hostname.clone(), exp);
|
||||||
|
}
|
||||||
|
file_certs.insert(h.hostname.clone(), Arc::new(pair));
|
||||||
|
}
|
||||||
|
let mut secret_values = Vec::new();
|
||||||
|
let request_ops = ops(&h.request_headers, &secrets, &mut secret_values)?;
|
||||||
|
let response_ops = ops(&h.response_headers, &secrets, &mut secret_values)?;
|
||||||
|
let upstreams = h
|
||||||
|
.upstreams
|
||||||
|
.iter()
|
||||||
|
.map(upstream)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
if upstreams.is_empty() {
|
||||||
|
return Err(EdgeError::Upstream {
|
||||||
|
address: h.hostname.clone(),
|
||||||
|
reason: "host has no upstream".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
hosts.insert(
|
||||||
|
h.hostname.clone(),
|
||||||
|
Arc::new(HostRt {
|
||||||
|
cfg: h.clone(),
|
||||||
|
upstreams,
|
||||||
|
next: AtomicUsize::new(0),
|
||||||
|
request_ops,
|
||||||
|
response_ops,
|
||||||
|
secret_values,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let forward_auth = match &cfg.forward_auth {
|
||||||
|
Some(fa) => Some(ForwardAuthRt {
|
||||||
|
upstream: upstream(&fa.upstream)?,
|
||||||
|
path_and_query: fa.path_and_query.clone(),
|
||||||
|
copy_headers: fa
|
||||||
|
.copy_headers
|
||||||
|
.iter()
|
||||||
|
.map(|h| header_name(h))
|
||||||
|
.collect::<Result<_, _>>()?,
|
||||||
|
strip_headers: fa
|
||||||
|
.strip_headers
|
||||||
|
.iter()
|
||||||
|
.map(|h| header_name(h))
|
||||||
|
.collect::<Result<_, _>>()?,
|
||||||
|
}),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
if forward_auth.is_none() && cfg.hosts.iter().any(|h| h.forward_auth) {
|
||||||
|
return Err(EdgeError::Config {
|
||||||
|
path: PathBuf::from("<edge config>"),
|
||||||
|
message: "a host uses forward-auth but no forward_auth endpoint is configured".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let access_log = if cfg.hosts.iter().any(|h| h.access_log) {
|
||||||
|
Some(AccessLog::open(Path::new(&cfg.access_log))?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Runtime {
|
||||||
|
cfg,
|
||||||
|
hosts,
|
||||||
|
forward_auth,
|
||||||
|
access_log,
|
||||||
|
file_certs,
|
||||||
|
file_cert_expiry,
|
||||||
|
share_key,
|
||||||
|
sha256: String::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod resolve_tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test(start_paused = true)]
|
||||||
|
async fn a_slow_resolver_times_out() {
|
||||||
|
let t = tokio::time::Instant::now();
|
||||||
|
let err = resolve_with("slow.test", 80, RESOLVE_TIMEOUT, |_, _| async {
|
||||||
|
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||||
|
Ok(vec!["127.0.0.1:80".parse().unwrap()])
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
|
||||||
|
assert_eq!(t.elapsed(), RESOLVE_TIMEOUT);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(start_paused = true)]
|
||||||
|
async fn a_prompt_resolver_and_ip_literals_pass() {
|
||||||
|
let a: SocketAddr = "127.0.0.1:80".parse().unwrap();
|
||||||
|
let got = resolve_with(
|
||||||
|
"ok.test",
|
||||||
|
80,
|
||||||
|
RESOLVE_TIMEOUT,
|
||||||
|
|_, _| async move { Ok(vec![a]) },
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(got.unwrap(), vec![a]);
|
||||||
|
let got = resolve_with("::1", 8080, RESOLVE_TIMEOUT, |_, _| async {
|
||||||
|
unreachable!("IP literals are not looked up")
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(got.unwrap(), vec!["[::1]:8080".parse().unwrap()]);
|
||||||
|
let got = resolve_with("empty.test", 80, RESOLVE_TIMEOUT, |_, _| async {
|
||||||
|
Ok(vec![])
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn health_records_keep_the_last_five() {
|
||||||
|
let r = HealthRecord::default();
|
||||||
|
for i in 0..8 {
|
||||||
|
r.record(Check {
|
||||||
|
seq: 0,
|
||||||
|
at: i,
|
||||||
|
ok: i % 2 == 0,
|
||||||
|
source: "health_check",
|
||||||
|
kind: None,
|
||||||
|
status: None,
|
||||||
|
latency_ms: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let c = r.checks();
|
||||||
|
assert_eq!(c.len(), KEPT_CHECKS);
|
||||||
|
assert_eq!(c.first().unwrap().seq, 4);
|
||||||
|
assert_eq!(c.last().unwrap().seq, 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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/.
|
||||||
|
|
||||||
|
//! Secrets referenced by header rules, read once at startup from `$CREDENTIALS_DIRECTORY`
|
||||||
|
//! (systemd `LoadCredential=`). A [`Secret`] never prints its value: `Debug` and `Display`
|
||||||
|
//! are redacted, the header value is marked sensitive (HPACK never-index) and errors name
|
||||||
|
//! the secret, never its content.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::fmt;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use http::HeaderValue;
|
||||||
|
|
||||||
|
use crate::error::EdgeError;
|
||||||
|
|
||||||
|
/// Largest credential file accepted.
|
||||||
|
const MAX_LEN: u64 = 8192;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Secret {
|
||||||
|
value: HeaderValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Secret {
|
||||||
|
pub fn header_value(&self) -> HeaderValue {
|
||||||
|
self.value.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_bytes(&self) -> &[u8] {
|
||||||
|
self.value.as_bytes()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for Secret {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("Secret(<redacted>)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Secret {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("<redacted>")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turn a credential file's bytes into a header value. One trailing newline (`\n` or `\r\n`)
|
||||||
|
/// is dropped, as Caddy's `{file.*}` placeholder does; anything else must be one line of
|
||||||
|
/// visible ASCII, spaces and tabs.
|
||||||
|
pub fn parse(name: &str, raw: &[u8]) -> Result<Secret, EdgeError> {
|
||||||
|
let err = |reason| EdgeError::Secret {
|
||||||
|
name: name.to_owned(),
|
||||||
|
reason,
|
||||||
|
};
|
||||||
|
let trimmed = raw
|
||||||
|
.strip_suffix(b"\r\n")
|
||||||
|
.or_else(|| raw.strip_suffix(b"\n"))
|
||||||
|
.unwrap_or(raw);
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
return Err(err("the credential is empty"));
|
||||||
|
}
|
||||||
|
if !trimmed
|
||||||
|
.iter()
|
||||||
|
.all(|c| (0x20..0x7f).contains(c) || *c == b'\t')
|
||||||
|
{
|
||||||
|
return Err(err("the credential must be a single line of visible ASCII"));
|
||||||
|
}
|
||||||
|
let mut value = HeaderValue::from_bytes(trimmed)
|
||||||
|
.map_err(|_| err("the credential is not a valid header value"))?;
|
||||||
|
value.set_sensitive(true);
|
||||||
|
Ok(Secret { value })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Secrets(BTreeMap<String, Secret>);
|
||||||
|
|
||||||
|
impl Secrets {
|
||||||
|
pub fn get(&self, name: &str) -> Option<&Secret> {
|
||||||
|
self.0.get(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load every named secret from `dir` (the value of `$CREDENTIALS_DIRECTORY`).
|
||||||
|
pub fn load(names: &BTreeSet<String>, dir: Option<&Path>) -> Result<Secrets, EdgeError> {
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
for name in names {
|
||||||
|
// Names are validated by core, but the edge config is input too.
|
||||||
|
if name.is_empty()
|
||||||
|
|| !name
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_' || c == b'-')
|
||||||
|
{
|
||||||
|
return Err(EdgeError::Secret {
|
||||||
|
name: name.clone(),
|
||||||
|
reason: "the name is not a valid credential name",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let Some(dir) = dir else {
|
||||||
|
return Err(EdgeError::Secret {
|
||||||
|
name: name.clone(),
|
||||||
|
reason: "$CREDENTIALS_DIRECTORY is not set (use systemd LoadCredential=)",
|
||||||
|
});
|
||||||
|
};
|
||||||
|
let path = dir.join(name);
|
||||||
|
let meta = std::fs::metadata(&path).map_err(|_| EdgeError::Secret {
|
||||||
|
name: name.clone(),
|
||||||
|
reason: "no such credential in $CREDENTIALS_DIRECTORY",
|
||||||
|
})?;
|
||||||
|
if meta.len() > MAX_LEN {
|
||||||
|
return Err(EdgeError::Secret {
|
||||||
|
name: name.clone(),
|
||||||
|
reason: "the credential is larger than 8 KiB",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let raw = std::fs::read(&path).map_err(|_| EdgeError::Secret {
|
||||||
|
name: name.clone(),
|
||||||
|
reason: "the credential cannot be read",
|
||||||
|
})?;
|
||||||
|
out.insert(name.clone(), parse(name, &raw)?);
|
||||||
|
}
|
||||||
|
Ok(Secrets(out))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trailing_newline_is_dropped_once() {
|
||||||
|
assert_eq!(parse("a", b"value\n").unwrap().as_bytes(), b"value");
|
||||||
|
assert_eq!(parse("a", b"value\r\n").unwrap().as_bytes(), b"value");
|
||||||
|
assert_eq!(parse("a", b"value").unwrap().as_bytes(), b"value");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multi_line_and_control_bytes_are_refused() {
|
||||||
|
for bad in [
|
||||||
|
&b"a\nb"[..],
|
||||||
|
b"a\n\n",
|
||||||
|
b"a\rb",
|
||||||
|
b"\0",
|
||||||
|
b"",
|
||||||
|
b"\n",
|
||||||
|
"ü".as_bytes(),
|
||||||
|
] {
|
||||||
|
assert!(parse("a", bad).is_err(), "{bad:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn debug_and_display_never_show_the_value() {
|
||||||
|
let s = parse("a", b"hunter2").unwrap();
|
||||||
|
assert!(!format!("{s:?} {s}").contains("hunter2"));
|
||||||
|
assert!(s.header_value().is_sensitive());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn errors_never_contain_the_value() {
|
||||||
|
let e = parse("api", b"hunter2\nx").unwrap_err();
|
||||||
|
assert!(!e.to_string().contains("hunter2"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,481 @@
|
|||||||
|
// 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 hosts with `share_links = true` (tokens: `ianitor_core::share`).
|
||||||
|
//!
|
||||||
|
//! 1. `GET <path>?share=ish1.…` within the link's prefix: edge checks the token and answers
|
||||||
|
//! `303` to the same URL without `share=`, setting the session cookie (`__Secure-`, Path =
|
||||||
|
//! prefix, HttpOnly, Secure, SameSite=Lax, Max-Age = time left). The token is in a URL once.
|
||||||
|
//! A password link instead gets the password page; its form posts the token and the
|
||||||
|
//! password to [`PASSWORD_PATH`], and on success edge sets the cookie and redirects to
|
||||||
|
//! the prefix.
|
||||||
|
//! 2. A request carrying a valid session cookie for a path within its prefix skips
|
||||||
|
//! forward-auth. The cookie (and any `share=` token) is removed before the request goes on,
|
||||||
|
//! so neither the upstream nor the auth server ever sees it.
|
||||||
|
//! 3. A token outside its prefix, or one for a host without share links, is ignored: the
|
||||||
|
//! request takes the normal sign-in, without the `share=` parameter.
|
||||||
|
//!
|
||||||
|
//! SameSite=Lax, not Strict: a visitor arrives by clicking a link in another site or app, and
|
||||||
|
//! browsers do not send Strict cookies on the redirect that follows such a navigation.
|
||||||
|
//! Wrong passwords are limited to 5 a minute per link and visitor /24 (and /48).
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::net::IpAddr;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use bytes::Bytes;
|
||||||
|
use http::header;
|
||||||
|
use ianitor_core::share::{
|
||||||
|
COOKIE_NAME, Claims, LINK_PREFIX, PASSWORD_PATH, QUERY_PARAM, Rejection, ShareId, ShareKey,
|
||||||
|
path_within, peek, session_value, verify_link, verify_session,
|
||||||
|
};
|
||||||
|
use pingora::http::ResponseHeader;
|
||||||
|
use pingora::proxy::Session;
|
||||||
|
use pingora::{Error, ErrorType, Result};
|
||||||
|
|
||||||
|
use crate::logging::{now_secs, truncate_ip};
|
||||||
|
use crate::pages::{self, Page};
|
||||||
|
use crate::shared::RevocationState;
|
||||||
|
|
||||||
|
const WINDOW: Duration = Duration::from_secs(60);
|
||||||
|
/// Wrong passwords a minute for one link from one network.
|
||||||
|
const MAX_FAILURES: u32 = 5;
|
||||||
|
/// Wrong passwords a minute from one network, whatever the link: the link id a guess names
|
||||||
|
/// is unproven, so per-link counting alone could be dodged with made-up ids.
|
||||||
|
const MAX_NETWORK_FAILURES: u32 = 20;
|
||||||
|
const MAX_ENTRIES: usize = 10_000;
|
||||||
|
const MAX_FORM: usize = 8 * 1024;
|
||||||
|
|
||||||
|
type Window = (Instant, u32);
|
||||||
|
|
||||||
|
/// Wrong-password counters per (link, visitor network) and per visitor network. Entries live
|
||||||
|
/// one minute. A full table refuses newcomers rather than forgetting anyone, so flooding it
|
||||||
|
/// can lock visitors out for a minute but never reset a counter.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Throttle {
|
||||||
|
inner: Mutex<Counters>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Counters {
|
||||||
|
links: HashMap<(ShareId, IpAddr), Window>,
|
||||||
|
networks: HashMap<IpAddr, Window>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn live(w: &Window) -> bool {
|
||||||
|
w.0.elapsed() < WINDOW
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count<K: std::hash::Hash + Eq>(m: &mut HashMap<K, Window>, k: K) {
|
||||||
|
if m.len() >= MAX_ENTRIES && !m.contains_key(&k) {
|
||||||
|
m.retain(|_, w| live(w));
|
||||||
|
if m.len() >= MAX_ENTRIES {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let e = m.entry(k).or_insert((Instant::now(), 0));
|
||||||
|
if !live(e) {
|
||||||
|
*e = (Instant::now(), 0);
|
||||||
|
}
|
||||||
|
e.1 = e.1.saturating_add(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Throttle {
|
||||||
|
fn net(ip: Option<IpAddr>) -> IpAddr {
|
||||||
|
ip.map_or(IpAddr::from([0, 0, 0, 0]), truncate_ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when this visitor may try a password for this link now.
|
||||||
|
pub fn allowed(&self, id: ShareId, ip: Option<IpAddr>) -> bool {
|
||||||
|
let Ok(mut c) = self.inner.lock() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let net = Self::net(ip);
|
||||||
|
let under = |w: Option<&Window>, max: u32| w.is_none_or(|w| !live(w) || w.1 < max);
|
||||||
|
if !under(c.networks.get(&net), MAX_NETWORK_FAILURES)
|
||||||
|
|| !under(c.links.get(&(id, net)), MAX_FAILURES)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// A full table that has no room for this visitor: refuse.
|
||||||
|
for full in [
|
||||||
|
c.links.len() >= MAX_ENTRIES,
|
||||||
|
c.networks.len() >= MAX_ENTRIES,
|
||||||
|
] {
|
||||||
|
if full {
|
||||||
|
c.links.retain(|_, w| live(w));
|
||||||
|
c.networks.retain(|_, w| live(w));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let room_links = c.links.len() < MAX_ENTRIES || c.links.contains_key(&(id, net));
|
||||||
|
let room_nets = c.networks.len() < MAX_ENTRIES || c.networks.contains_key(&net);
|
||||||
|
room_links && room_nets
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn failed(&self, id: ShareId, ip: Option<IpAddr>) {
|
||||||
|
let Ok(mut c) = self.inner.lock() else { return };
|
||||||
|
let net = Self::net(ip);
|
||||||
|
count(&mut c.links, (id, net));
|
||||||
|
count(&mut c.networks, net);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the share layer decided for a request.
|
||||||
|
pub enum Decision {
|
||||||
|
/// Answered here (redirect or visitor page); stop.
|
||||||
|
Answered,
|
||||||
|
/// A valid session cookie covers this path: skip forward-auth.
|
||||||
|
Allowed,
|
||||||
|
/// Nothing to do with share links: continue as usual.
|
||||||
|
Continue,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> u64 {
|
||||||
|
now_secs() as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove every share cookie from the request; return their values.
|
||||||
|
fn take_cookies(session: &mut Session) -> Result<Vec<String>> {
|
||||||
|
let req = session.req_header_mut();
|
||||||
|
let all: Vec<String> = req
|
||||||
|
.headers
|
||||||
|
.get_all(header::COOKIE)
|
||||||
|
.iter()
|
||||||
|
.map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned())
|
||||||
|
.collect();
|
||||||
|
if all.is_empty() {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
let mut ours = Vec::new();
|
||||||
|
let mut rest = Vec::new();
|
||||||
|
for line in &all {
|
||||||
|
for part in line.split(';') {
|
||||||
|
let p = part.trim();
|
||||||
|
if p.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match p.split_once('=') {
|
||||||
|
Some((n, v)) if n.trim() == COOKIE_NAME => ours.push(v.trim().to_owned()),
|
||||||
|
_ => rest.push(p.to_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ours.is_empty() {
|
||||||
|
return Ok(ours);
|
||||||
|
}
|
||||||
|
req.remove_header(&header::COOKIE);
|
||||||
|
if !rest.is_empty() {
|
||||||
|
req.insert_header(header::COOKIE, rest.join("; "))?;
|
||||||
|
}
|
||||||
|
Ok(ours)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Split the query into our token (the first `share=ish1.…`) and everything else, kept in
|
||||||
|
/// its original encoding.
|
||||||
|
fn split_query(query: &str) -> (Option<String>, String) {
|
||||||
|
let mut token = None;
|
||||||
|
let mut rest = Vec::new();
|
||||||
|
for pair in query.split('&') {
|
||||||
|
// Every `share=ish1.…`, also with the name or value encoded, comes out; the first
|
||||||
|
// one is the token.
|
||||||
|
if let Some((k, v)) = form_urlencoded::parse(pair.as_bytes()).next()
|
||||||
|
&& k == QUERY_PARAM
|
||||||
|
&& v.starts_with(LINK_PREFIX)
|
||||||
|
{
|
||||||
|
if token.is_none() {
|
||||||
|
token = Some(v.into_owned());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !pair.is_empty() {
|
||||||
|
rest.push(pair);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(token, rest.join("&"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_query(path: &str, query: &str) -> String {
|
||||||
|
if query.is_empty() {
|
||||||
|
path.to_owned()
|
||||||
|
} else {
|
||||||
|
format!("{path}?{query}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// On a host without share links: drop any `share=ish1.…` token from the request target, so
|
||||||
|
/// neither the auth server (X-Forwarded-Uri) nor the upstream ever sees one.
|
||||||
|
pub fn strip_any_token(session: &mut Session) -> Result<()> {
|
||||||
|
let Some(query) = session.req_header().uri.query().map(str::to_owned) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let (token, rest) = split_query(&query);
|
||||||
|
if token.is_some() {
|
||||||
|
let path = session.req_header().uri.path().to_owned();
|
||||||
|
strip_token(session, &path, &rest)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop the `share=` token from the request target, so the upstream never sees it.
|
||||||
|
fn strip_token(session: &mut Session, path: &str, rest: &str) -> Result<()> {
|
||||||
|
let uri = with_query(path, rest)
|
||||||
|
.parse::<http::Uri>()
|
||||||
|
.map_err(|_| Error::explain(ErrorType::HTTPStatus(400), "bad request target"))?;
|
||||||
|
session.req_header_mut().set_uri(uri);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cookie(value: &str, claims: &Claims) -> String {
|
||||||
|
let left = claims.expires_at.saturating_sub(now());
|
||||||
|
format!(
|
||||||
|
"{COOKIE_NAME}={value}; Path={}; Max-Age={left}; HttpOnly; Secure; SameSite=Lax",
|
||||||
|
claims.prefix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn redirect(session: &mut Session, location: &str, set_cookie: Option<String>) -> Result<()> {
|
||||||
|
let mut resp = ResponseHeader::build(303, Some(5))?;
|
||||||
|
resp.insert_header(header::LOCATION, location)?;
|
||||||
|
resp.insert_header(header::CACHE_CONTROL, "no-store")?;
|
||||||
|
resp.insert_header("Referrer-Policy", "no-referrer")?;
|
||||||
|
resp.insert_header(header::CONTENT_LENGTH, "0")?;
|
||||||
|
if let Some(c) = set_cookie {
|
||||||
|
resp.insert_header(header::SET_COOKIE, c)?;
|
||||||
|
}
|
||||||
|
session.write_response_header(Box::new(resp), true).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn page(session: &mut Session, p: Page<'_>) -> Result<()> {
|
||||||
|
let html = pages::render(&p);
|
||||||
|
let mut resp = ResponseHeader::build(p.status(), Some(8))?;
|
||||||
|
resp.insert_header(header::CONTENT_TYPE, "text/html; charset=utf-8")?;
|
||||||
|
resp.insert_header(header::CACHE_CONTROL, "no-store")?;
|
||||||
|
resp.insert_header("Referrer-Policy", "no-referrer")?;
|
||||||
|
resp.insert_header("X-Robots-Tag", "noindex")?;
|
||||||
|
resp.insert_header(
|
||||||
|
"Content-Security-Policy",
|
||||||
|
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'",
|
||||||
|
)?;
|
||||||
|
resp.insert_header(header::CONTENT_LENGTH, html.len().to_string())?;
|
||||||
|
let head = session.req_header().method == http::Method::HEAD;
|
||||||
|
session.write_response_header(Box::new(resp), head).await?;
|
||||||
|
if !head {
|
||||||
|
session
|
||||||
|
.write_response_body(Some(Bytes::from(html)), true)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rejected_page(r: Rejection, host: &str) -> Page<'_> {
|
||||||
|
match r {
|
||||||
|
Rejection::Expired { expires_at } => Page::Expired {
|
||||||
|
host,
|
||||||
|
until: expires_at,
|
||||||
|
},
|
||||||
|
_ => Page::Invalid { host },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_form(session: &mut Session) -> Result<Option<Vec<u8>>> {
|
||||||
|
let mut body = Vec::new();
|
||||||
|
while let Some(chunk) = session.read_request_body().await? {
|
||||||
|
if body.len() + chunk.len() > MAX_FORM {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
body.extend_from_slice(&chunk);
|
||||||
|
}
|
||||||
|
Ok(Some(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The share layer for one request on a host with share links.
|
||||||
|
pub async fn handle(
|
||||||
|
session: &mut Session,
|
||||||
|
host: &str,
|
||||||
|
key: Option<&ShareKey>,
|
||||||
|
revocations: &RevocationState,
|
||||||
|
throttle: &Throttle,
|
||||||
|
client_ip: Option<IpAddr>,
|
||||||
|
) -> Result<Decision> {
|
||||||
|
let cookies = take_cookies(session)?;
|
||||||
|
let path = session.req_header().uri.path().to_owned();
|
||||||
|
let query = session.req_header().uri.query().unwrap_or("").to_owned();
|
||||||
|
// Without the key or a readable revocation file, no share link is honoured.
|
||||||
|
let usable = key.filter(|_| revocations.loaded);
|
||||||
|
let revs = &revocations.revocations;
|
||||||
|
|
||||||
|
if path == PASSWORD_PATH {
|
||||||
|
let Some(key) = usable else {
|
||||||
|
page(session, Page::Invalid { host }).await?;
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
};
|
||||||
|
if session.req_header().method != http::Method::POST {
|
||||||
|
page(session, Page::Invalid { host }).await?;
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
}
|
||||||
|
let Some(body) = read_form(session).await? else {
|
||||||
|
page(session, Page::Invalid { host }).await?;
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
};
|
||||||
|
let mut token = String::new();
|
||||||
|
let mut password = String::new();
|
||||||
|
for (k, v) in form_urlencoded::parse(&body) {
|
||||||
|
match k.as_ref() {
|
||||||
|
"t" => token = v.into_owned(),
|
||||||
|
"password" => password = v.into_owned(),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Ok(claimed) = peek(&token) else {
|
||||||
|
page(session, Page::Invalid { host }).await?;
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
};
|
||||||
|
if !throttle.allowed(claimed.id, client_ip) {
|
||||||
|
page(
|
||||||
|
session,
|
||||||
|
Page::Password {
|
||||||
|
host,
|
||||||
|
token: &token,
|
||||||
|
until: claimed.expires_at,
|
||||||
|
problem: Some(pages::Problem::TooMany),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
}
|
||||||
|
match verify_link(key, host, &token, Some(&password), now(), revs) {
|
||||||
|
Ok(c) => {
|
||||||
|
let v = session_value(key, host, &c);
|
||||||
|
redirect(session, &c.prefix, Some(cookie(&v, &c))).await?;
|
||||||
|
}
|
||||||
|
Err(Rejection::Invalid) => {
|
||||||
|
throttle.failed(claimed.id, client_ip);
|
||||||
|
page(
|
||||||
|
session,
|
||||||
|
Page::Password {
|
||||||
|
host,
|
||||||
|
token: &token,
|
||||||
|
until: claimed.expires_at,
|
||||||
|
problem: Some(pages::Problem::WrongPassword),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Err(r) => page(session, rejected_page(r, host)).await?,
|
||||||
|
}
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
}
|
||||||
|
|
||||||
|
let (token, rest) = split_query(&query);
|
||||||
|
if let Some(token) = token {
|
||||||
|
let claimed = peek(&token);
|
||||||
|
let within = claimed
|
||||||
|
.as_ref()
|
||||||
|
.is_ok_and(|c| path_within(&c.prefix, &path));
|
||||||
|
if claimed.is_ok() && !within {
|
||||||
|
// Outside its prefix: as if there were no link, minus the token.
|
||||||
|
strip_token(session, &path, &rest)?;
|
||||||
|
return Ok(Decision::Continue);
|
||||||
|
}
|
||||||
|
let Some(key) = usable else {
|
||||||
|
page(session, Page::Invalid { host }).await?;
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
};
|
||||||
|
let claimed = match claimed {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(_) => {
|
||||||
|
page(session, Page::Invalid { host }).await?;
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if claimed.password {
|
||||||
|
if now() >= claimed.expires_at {
|
||||||
|
page(
|
||||||
|
session,
|
||||||
|
Page::Expired {
|
||||||
|
host,
|
||||||
|
until: claimed.expires_at,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
} else {
|
||||||
|
let problem =
|
||||||
|
(!throttle.allowed(claimed.id, client_ip)).then_some(pages::Problem::TooMany);
|
||||||
|
page(
|
||||||
|
session,
|
||||||
|
Page::Password {
|
||||||
|
host,
|
||||||
|
token: &token,
|
||||||
|
until: claimed.expires_at,
|
||||||
|
problem,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
}
|
||||||
|
match verify_link(key, host, &token, None, now(), revs) {
|
||||||
|
Ok(c) => {
|
||||||
|
let v = session_value(key, host, &c);
|
||||||
|
redirect(session, &with_query(&path, &rest), Some(cookie(&v, &c))).await?;
|
||||||
|
}
|
||||||
|
Err(r) => page(session, rejected_page(r, host)).await?,
|
||||||
|
}
|
||||||
|
return Ok(Decision::Answered);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(key) = usable {
|
||||||
|
let t = now();
|
||||||
|
for v in &cookies {
|
||||||
|
if let Ok(c) = verify_session(key, host, v, t, revs)
|
||||||
|
&& path_within(&c.prefix, &path)
|
||||||
|
{
|
||||||
|
return Ok(Decision::Allowed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Decision::Continue)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_token_is_split_from_the_query() {
|
||||||
|
assert_eq!(
|
||||||
|
split_query("a=1&share=ish1.abc&b=2"),
|
||||||
|
(Some("ish1.abc".into()), "a=1&b=2".into())
|
||||||
|
);
|
||||||
|
assert_eq!(split_query("share=holiday"), (None, "share=holiday".into()));
|
||||||
|
assert_eq!(
|
||||||
|
split_query("x=%20&share=ish1.a%2Db"),
|
||||||
|
(Some("ish1.a-b".into()), "x=%20".into())
|
||||||
|
);
|
||||||
|
assert_eq!(split_query(""), (None, String::new()));
|
||||||
|
assert_eq!(
|
||||||
|
split_query("share=ish1.a&b=1&share=ish1.b&sh%61re=ish1.c"),
|
||||||
|
(Some("ish1.a".into()), "b=1".into())
|
||||||
|
);
|
||||||
|
assert_eq!(split_query("sharex=ish1.a"), (None, "sharex=ish1.a".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_throttle_allows_five_failures_a_minute_per_link_and_network() {
|
||||||
|
let t = Throttle::default();
|
||||||
|
let id = ShareId([1; 16]);
|
||||||
|
let ip: IpAddr = "192.0.2.10".parse().unwrap_or(IpAddr::from([0, 0, 0, 0]));
|
||||||
|
let same_net: IpAddr = "192.0.2.99".parse().unwrap_or(IpAddr::from([0, 0, 0, 0]));
|
||||||
|
let other_net: IpAddr = "198.51.100.1".parse().unwrap_or(IpAddr::from([0, 0, 0, 0]));
|
||||||
|
for _ in 0..5 {
|
||||||
|
assert!(t.allowed(id, Some(ip)));
|
||||||
|
t.failed(id, Some(ip));
|
||||||
|
}
|
||||||
|
assert!(!t.allowed(id, Some(ip)));
|
||||||
|
assert!(!t.allowed(id, Some(same_net)));
|
||||||
|
assert!(t.allowed(id, Some(other_net)));
|
||||||
|
assert!(t.allowed(ShareId([2; 16]), Some(ip)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,492 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! State that lives as long as the process, across config reloads (ROADMAP §8.4).
|
||||||
|
//!
|
||||||
|
//! A reload builds a complete new [`Runtime`] from the config file and swaps it in with one
|
||||||
|
//! atomic pointer store. Listeners, TLS sessions and keep-alive connections are untouched:
|
||||||
|
//! each request takes the runtime that is current when it starts and keeps it until it ends,
|
||||||
|
//! so nothing in flight sees a half-applied config, and the next request on the same
|
||||||
|
//! connection already uses the new one. A config that fails to build is refused and the old
|
||||||
|
//! one keeps serving.
|
||||||
|
//!
|
||||||
|
//! A **trial** is a reload control has not confirmed yet: edge keeps the previous runtime and
|
||||||
|
//! swaps it back by itself when the deadline passes without a confirmation. So if control
|
||||||
|
//! dies in the middle of an apply, edge returns to the last good config on its own, and
|
||||||
|
//! because the trial is read from a separate file, a restarted edge reads the last good
|
||||||
|
//! config too.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use arc_swap::ArcSwap;
|
||||||
|
use ianitor_core::share::{Revocations, ShareId};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::error::EdgeError;
|
||||||
|
use crate::logging::now_secs;
|
||||||
|
use crate::runtime::{self, Runtime};
|
||||||
|
use crate::tls::CertStore;
|
||||||
|
|
||||||
|
/// Health probes of watched hosts during a trial.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct WatchSpec {
|
||||||
|
pub hosts: Vec<String>,
|
||||||
|
pub every: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Trial {
|
||||||
|
id: u64,
|
||||||
|
sha256: String,
|
||||||
|
previous: Arc<Runtime>,
|
||||||
|
deadline: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The share-link revocation file as edge last read it.
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct RevocationState {
|
||||||
|
pub revocations: Revocations,
|
||||||
|
/// False when the file is missing or never read: share links are then refused.
|
||||||
|
pub loaded: bool,
|
||||||
|
pub error: Option<String>,
|
||||||
|
/// SHA-256 of the file as last read; the poller re-reads when it changes.
|
||||||
|
stamp: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct RevocationFile {
|
||||||
|
epoch: u32,
|
||||||
|
deny: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Most ids on the deny list.
|
||||||
|
pub const MAX_DENY: usize = 10_000;
|
||||||
|
|
||||||
|
/// Certificate state per host, for control (docs/ui-api.md G5).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct CertState {
|
||||||
|
/// `ok`, `pending` or `failed`.
|
||||||
|
pub state: &'static str,
|
||||||
|
pub not_after: Option<i64>,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Paths {
|
||||||
|
pub config: PathBuf,
|
||||||
|
pub trial: PathBuf,
|
||||||
|
pub revocations: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why an admin request was refused.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum AdminError {
|
||||||
|
#[error("{0}")]
|
||||||
|
Refused(#[from] EdgeError),
|
||||||
|
#[error("{0}")]
|
||||||
|
Conflict(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Shared {
|
||||||
|
current: ArcSwap<Runtime>,
|
||||||
|
pub certs: Arc<CertStore>,
|
||||||
|
generation: AtomicU64,
|
||||||
|
changed: tokio::sync::watch::Sender<u64>,
|
||||||
|
trial: Mutex<Option<Trial>>,
|
||||||
|
trial_ids: AtomicU64,
|
||||||
|
watch: Mutex<Option<WatchSpec>>,
|
||||||
|
pub paths: Paths,
|
||||||
|
credentials_dir: Option<PathBuf>,
|
||||||
|
revocations: ArcSwap<RevocationState>,
|
||||||
|
/// The highest revocation epoch seen since start; a file with a lower one is refused.
|
||||||
|
epoch_seen: std::sync::atomic::AtomicU32,
|
||||||
|
/// Set when the saved epoch floor could not be read: share links stay refused.
|
||||||
|
floor_error: Option<String>,
|
||||||
|
pub throttle: crate::share::Throttle,
|
||||||
|
cert_states: Mutex<HashMap<String, CertState>>,
|
||||||
|
pub acme_wake: tokio::sync::Notify,
|
||||||
|
pub started_at: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn same_listeners(a: &Runtime, b: &Runtime) -> Result<(), EdgeError> {
|
||||||
|
if a.cfg.http_listen != b.cfg.http_listen || a.cfg.https_listen != b.cfg.https_listen {
|
||||||
|
return Err(EdgeError::Config {
|
||||||
|
path: PathBuf::from("<new config>"),
|
||||||
|
message: "the listen addresses can only change with a restart".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Shared {
|
||||||
|
pub fn new(rt: Runtime, paths: Paths, credentials_dir: Option<PathBuf>) -> Arc<Shared> {
|
||||||
|
let (floor, floor_error) = match read_epoch_floor(&rt) {
|
||||||
|
Ok(f) => (f, None),
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::share", "{e}");
|
||||||
|
(u32::MAX, Some(e))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let certs = Arc::new(CertStore::default());
|
||||||
|
certs.replace_files(rt.file_certs.clone());
|
||||||
|
let (changed, _) = tokio::sync::watch::channel(1);
|
||||||
|
let s = Arc::new(Shared {
|
||||||
|
current: ArcSwap::from_pointee(rt),
|
||||||
|
certs,
|
||||||
|
generation: AtomicU64::new(1),
|
||||||
|
changed,
|
||||||
|
trial: Mutex::new(None),
|
||||||
|
trial_ids: AtomicU64::new(0),
|
||||||
|
watch: Mutex::new(None),
|
||||||
|
paths,
|
||||||
|
credentials_dir,
|
||||||
|
revocations: ArcSwap::from_pointee(RevocationState::default()),
|
||||||
|
epoch_seen: std::sync::atomic::AtomicU32::new(floor),
|
||||||
|
floor_error,
|
||||||
|
throttle: crate::share::Throttle::default(),
|
||||||
|
cert_states: Mutex::new(HashMap::new()),
|
||||||
|
acme_wake: tokio::sync::Notify::new(),
|
||||||
|
started_at: now_secs() as u64,
|
||||||
|
});
|
||||||
|
if let Err(e) = s.reload_revocations() {
|
||||||
|
log::error!(target: "ianitor::share", "{e}; share links are refused until it is fixed");
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The runtime serving new requests now.
|
||||||
|
pub fn current(&self) -> Arc<Runtime> {
|
||||||
|
self.current.load_full()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generation(&self) -> u64 {
|
||||||
|
self.generation.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes whenever the runtime or the trial watch changes.
|
||||||
|
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
|
||||||
|
self.changed.subscribe()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn watch_spec(&self) -> Option<WatchSpec> {
|
||||||
|
self.watch.lock().ok().and_then(|w| w.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn notify(&self) {
|
||||||
|
self.changed.send_replace(self.generation());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install(&self, rt: Arc<Runtime>) {
|
||||||
|
self.certs.replace_files(rt.file_certs.clone());
|
||||||
|
self.current.store(rt);
|
||||||
|
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||||
|
self.notify();
|
||||||
|
self.acme_wake.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build(&self, path: &Path) -> Result<Runtime, EdgeError> {
|
||||||
|
let rt = runtime::build_file(path, self.credentials_dir.as_deref())?;
|
||||||
|
same_listeners(&self.current(), &rt)?;
|
||||||
|
Ok(rt)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reload from the config file. Refused while a trial runs.
|
||||||
|
pub fn reload(&self) -> Result<Arc<Runtime>, AdminError> {
|
||||||
|
let guard = self.trial.lock().map_err(|_| poisoned())?;
|
||||||
|
if guard.is_some() {
|
||||||
|
return Err(AdminError::Conflict(
|
||||||
|
"a trial config is running; confirm or abort it first".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let rt = Arc::new(self.build(&self.paths.config)?);
|
||||||
|
self.install(rt.clone());
|
||||||
|
drop(guard);
|
||||||
|
log::info!(target: "ianitor::reload", "config reloaded ({} hosts, sha256 {})", rt.hosts.len(), short(&rt.sha256));
|
||||||
|
Ok(rt)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serve the trial config until [`Shared::confirm`] or the deadline. Returns the trial id
|
||||||
|
/// (for [`Shared::expire_trial`]) and the runtime.
|
||||||
|
pub fn start_trial(
|
||||||
|
&self,
|
||||||
|
confirm_within: Duration,
|
||||||
|
watch: Option<WatchSpec>,
|
||||||
|
) -> Result<(u64, Arc<Runtime>), AdminError> {
|
||||||
|
let mut guard = self.trial.lock().map_err(|_| poisoned())?;
|
||||||
|
if guard.is_some() {
|
||||||
|
return Err(AdminError::Conflict(
|
||||||
|
"a trial config is already running".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let rt = Arc::new(self.build(&self.paths.trial)?);
|
||||||
|
let id = self.trial_ids.fetch_add(1, Ordering::SeqCst) + 1;
|
||||||
|
*guard = Some(Trial {
|
||||||
|
id,
|
||||||
|
sha256: rt.sha256.clone(),
|
||||||
|
previous: self.current(),
|
||||||
|
deadline: Instant::now() + confirm_within,
|
||||||
|
});
|
||||||
|
if let Ok(mut w) = self.watch.lock() {
|
||||||
|
*w = watch;
|
||||||
|
}
|
||||||
|
self.install(rt.clone());
|
||||||
|
log::info!(target: "ianitor::reload", "trial config {} running; reverts in {confirm_within:?} unless confirmed", short(&rt.sha256));
|
||||||
|
Ok((id, rt))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep the trial config. Fails unless a trial with this hash is running.
|
||||||
|
pub fn confirm(&self, sha256: &str) -> Result<(), AdminError> {
|
||||||
|
let mut guard = self.trial.lock().map_err(|_| poisoned())?;
|
||||||
|
match guard.as_ref() {
|
||||||
|
Some(t) if t.sha256 == sha256 => {}
|
||||||
|
Some(_) => {
|
||||||
|
return Err(AdminError::Conflict(
|
||||||
|
"the running trial has another config".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
None => return Err(AdminError::Conflict("no trial config is running".into())),
|
||||||
|
}
|
||||||
|
*guard = None;
|
||||||
|
self.end_watch();
|
||||||
|
log::info!(target: "ianitor::reload", "trial config {} confirmed", short(sha256));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end_watch(&self) {
|
||||||
|
if let Ok(mut w) = self.watch.lock() {
|
||||||
|
*w = None;
|
||||||
|
}
|
||||||
|
self.notify();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Go back to the config before the trial. Returns whether there was a trial.
|
||||||
|
pub fn abort(&self) -> bool {
|
||||||
|
self.revert_trial(None, "aborted")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when a trial's deadline passes.
|
||||||
|
pub fn expire_trial(&self, id: u64) {
|
||||||
|
self.revert_trial(Some(id), "not confirmed in time");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn revert_trial(&self, id: Option<u64>, why: &str) -> bool {
|
||||||
|
let Ok(mut guard) = self.trial.lock() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let matches = guard.as_ref().is_some_and(|t| id.is_none_or(|i| i == t.id));
|
||||||
|
if !matches {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(t) = guard.take() else { return false };
|
||||||
|
self.install(t.previous.clone());
|
||||||
|
self.end_watch();
|
||||||
|
log::warn!(target: "ianitor::reload", "trial config {} {why}; back to {}", short(&t.sha256), short(&t.previous.sha256));
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (sha256, seconds left, previous sha256) of the running trial.
|
||||||
|
pub fn trial_info(&self) -> Option<(String, u64, String)> {
|
||||||
|
let g = self.trial.lock().ok()?;
|
||||||
|
g.as_ref().map(|t| {
|
||||||
|
(
|
||||||
|
t.sha256.clone(),
|
||||||
|
t.deadline
|
||||||
|
.saturating_duration_since(Instant::now())
|
||||||
|
.as_secs(),
|
||||||
|
t.previous.sha256.clone(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn trial_deadline(&self, id: u64) -> Option<Instant> {
|
||||||
|
let g = self.trial.lock().ok()?;
|
||||||
|
g.as_ref().filter(|t| t.id == id).map(|t| t.deadline)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ share-link revocations
|
||||||
|
|
||||||
|
pub fn revocations(&self) -> Arc<RevocationState> {
|
||||||
|
self.revocations.load_full()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-read the revocation file. A missing file means "refuse every share link"; a broken
|
||||||
|
/// one keeps the last good state.
|
||||||
|
pub fn reload_revocations(&self) -> Result<(), EdgeError> {
|
||||||
|
let Some(path) = &self.paths.revocations else {
|
||||||
|
self.revocations.store(Arc::new(RevocationState {
|
||||||
|
error: Some("no revocation file is configured".into()),
|
||||||
|
..RevocationState::default()
|
||||||
|
}));
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let meta = match std::fs::metadata(path) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(source) => {
|
||||||
|
self.revocations.store(Arc::new(RevocationState {
|
||||||
|
error: Some(format!("cannot read {}: {source}", path.display())),
|
||||||
|
..RevocationState::default()
|
||||||
|
}));
|
||||||
|
return Err(EdgeError::Read {
|
||||||
|
path: path.clone(),
|
||||||
|
source,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let text = std::fs::read(path).ok();
|
||||||
|
let sha = text.as_deref().map(runtime::sha256_hex);
|
||||||
|
let fail = |message: String| {
|
||||||
|
let mut old = RevocationState::clone(&self.revocations());
|
||||||
|
old.error = Some(message.clone());
|
||||||
|
// Remember this content, so the poller reports it once, not every 5 s.
|
||||||
|
if old.loaded {
|
||||||
|
old.stamp = sha.clone();
|
||||||
|
}
|
||||||
|
self.revocations.store(Arc::new(old));
|
||||||
|
EdgeError::Config {
|
||||||
|
path: path.clone(),
|
||||||
|
message,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if meta.len() > 1 << 20 {
|
||||||
|
return Err(fail("the revocation file is larger than 1 MiB".into()));
|
||||||
|
}
|
||||||
|
let text = text
|
||||||
|
.and_then(|b| String::from_utf8(b).ok())
|
||||||
|
.ok_or_else(|| fail("cannot read the revocation file as text".into()))?;
|
||||||
|
let file: RevocationFile =
|
||||||
|
serde_json::from_str(&text).map_err(|e| fail(format!("not a revocation file: {e}")))?;
|
||||||
|
if file.deny.len() > MAX_DENY {
|
||||||
|
return Err(fail(format!("more than {MAX_DENY} stopped links")));
|
||||||
|
}
|
||||||
|
let mut deny = std::collections::BTreeSet::new();
|
||||||
|
for id in &file.deny {
|
||||||
|
deny.insert(
|
||||||
|
ShareId::from_hex(id)
|
||||||
|
.ok_or_else(|| fail("a link id is not 32 hex digits".into()))?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(e) = &self.floor_error {
|
||||||
|
return Err(fail(e.clone()));
|
||||||
|
}
|
||||||
|
// The epoch only goes up: a lower one would bring stopped links back.
|
||||||
|
let seen = self.epoch_seen.load(Ordering::SeqCst);
|
||||||
|
if file.epoch < seen {
|
||||||
|
return Err(fail(format!(
|
||||||
|
"the revocation epoch went down from {seen} to {}; keeping the old state",
|
||||||
|
file.epoch
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if file.epoch > seen {
|
||||||
|
self.epoch_seen.store(file.epoch, Ordering::SeqCst);
|
||||||
|
if let Err(e) = write_epoch_floor(&self.current(), file.epoch) {
|
||||||
|
// Still refused within this process; only a restart could forget it.
|
||||||
|
log::error!(target: "ianitor::share", "cannot save the revocation epoch floor: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let stamp = Some(runtime::sha256_hex(text.as_bytes()));
|
||||||
|
self.revocations.store(Arc::new(RevocationState {
|
||||||
|
revocations: Revocations {
|
||||||
|
epoch: file.epoch,
|
||||||
|
deny,
|
||||||
|
},
|
||||||
|
loaded: true,
|
||||||
|
error: None,
|
||||||
|
stamp,
|
||||||
|
}));
|
||||||
|
log::info!(target: "ianitor::share", "share-link revocations loaded: epoch {}, {} stopped", file.epoch, file.deny.len());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-read the revocation file if it changed (or vanished) since the last read.
|
||||||
|
pub fn poll_revocations(&self) {
|
||||||
|
let Some(path) = &self.paths.revocations else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// Content, not mtime: two writes within one timer tick have the same mtime.
|
||||||
|
let now = std::fs::metadata(path)
|
||||||
|
.ok()
|
||||||
|
.filter(|m| m.len() <= 1 << 20)
|
||||||
|
.and_then(|_| std::fs::read(path).ok())
|
||||||
|
.map(|b| runtime::sha256_hex(&b));
|
||||||
|
let state = self.revocations();
|
||||||
|
if (now != state.stamp || (now.is_none() && state.loaded))
|
||||||
|
&& let Err(e) = self.reload_revocations()
|
||||||
|
{
|
||||||
|
log::error!(target: "ianitor::share", "{e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ certificates
|
||||||
|
|
||||||
|
pub fn set_cert_state(&self, host: &str, state: CertState) {
|
||||||
|
if let Ok(mut m) = self.cert_states.lock() {
|
||||||
|
m.insert(host.to_owned(), state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cert_state(&self, host: &str) -> Option<CertState> {
|
||||||
|
self.cert_states.lock().ok()?.get(host).cloned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Edge's own record of the highest revocation epoch it has accepted, in its state
|
||||||
|
/// directory: a restart (even after control's files were rolled back) still refuses lower.
|
||||||
|
fn epoch_floor_path(rt: &Runtime) -> PathBuf {
|
||||||
|
Path::new(&rt.cfg.state_dir).join("share-epoch-floor")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Missing: 0. Unreadable or not a number: an error, and share links stay refused (failing
|
||||||
|
/// open would forget which links were stopped).
|
||||||
|
fn read_epoch_floor(rt: &Runtime) -> Result<u32, String> {
|
||||||
|
let path = epoch_floor_path(rt);
|
||||||
|
match std::fs::read_to_string(&path) {
|
||||||
|
Ok(s) => s.trim().parse().map_err(|_| {
|
||||||
|
format!(
|
||||||
|
"{} is not a number; share links are refused until it is fixed",
|
||||||
|
path.display()
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
|
||||||
|
Err(e) => Err(format!(
|
||||||
|
"cannot read {} ({e}); share links are refused until it is fixed",
|
||||||
|
path.display()
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_epoch_floor(rt: &Runtime, epoch: u32) -> std::io::Result<()> {
|
||||||
|
let path = epoch_floor_path(rt);
|
||||||
|
if let Some(dir) = path.parent() {
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
}
|
||||||
|
// Unique per write: the admin socket and the poller can both reload the revocations.
|
||||||
|
static WRITES: AtomicU64 = AtomicU64::new(0);
|
||||||
|
let tmp = path.with_extension(format!(
|
||||||
|
"tmp-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
WRITES.fetch_add(1, Ordering::Relaxed)
|
||||||
|
));
|
||||||
|
{
|
||||||
|
use std::io::Write;
|
||||||
|
let mut f = std::fs::File::create(&tmp)?;
|
||||||
|
f.write_all(format!("{epoch}\n").as_bytes())?;
|
||||||
|
f.sync_all()?;
|
||||||
|
}
|
||||||
|
std::fs::rename(&tmp, &path)?;
|
||||||
|
match path.parent() {
|
||||||
|
Some(dir) => std::fs::File::open(dir)?.sync_all(),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poisoned() -> AdminError {
|
||||||
|
AdminError::Conflict("internal state is unavailable".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn short(sha: &str) -> &str {
|
||||||
|
sha.get(..12).unwrap_or(sha)
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Certificate selection by SNI. Certificates can be swapped at runtime (ACME renewals)
|
||||||
|
//! without touching connections in flight.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use arc_swap::ArcSwap;
|
||||||
|
use rustls::server::{ClientHello, ResolvesServerCert};
|
||||||
|
use rustls::sign::CertifiedKey;
|
||||||
|
use rustls_pki_types::pem::PemObject;
|
||||||
|
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
|
||||||
|
|
||||||
|
/// Lives as long as the process: Domi certificates are replaced as a set on every reload,
|
||||||
|
/// ACME certificates are added by the ACME service and kept across reloads.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct CertStore {
|
||||||
|
/// ACME certificates (and anything inserted one by one).
|
||||||
|
certs: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
|
||||||
|
/// Domi certificates of the current config.
|
||||||
|
files: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CertStore {
|
||||||
|
pub fn insert(&self, host: &str, key: CertifiedKey) {
|
||||||
|
let key = Arc::new(key);
|
||||||
|
self.certs.rcu(|m| {
|
||||||
|
let mut m = HashMap::clone(m);
|
||||||
|
m.insert(host.to_owned(), key.clone());
|
||||||
|
m
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace the Domi certificates (on reload).
|
||||||
|
pub fn replace_files(&self, files: HashMap<String, Arc<CertifiedKey>>) {
|
||||||
|
self.files.store(Arc::new(files));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn has(&self, host: &str) -> bool {
|
||||||
|
self.files.load().contains_key(host) || self.certs.load().contains_key(host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResolvesServerCert for CertStore {
|
||||||
|
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
|
||||||
|
// No SNI or an unknown name: no certificate, the handshake fails (as with Caddy).
|
||||||
|
let name = hello.server_name()?.to_ascii_lowercase();
|
||||||
|
if let Some(k) = self.files.load().get(&name) {
|
||||||
|
return Some(k.clone());
|
||||||
|
}
|
||||||
|
self.certs.load().get(&name).cloned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse a PEM chain and PEM private key into a rustls key pair, checking they match.
|
||||||
|
pub fn certified_key(cert_pem: &[u8], key_pem: &[u8]) -> Result<CertifiedKey, String> {
|
||||||
|
let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(cert_pem)
|
||||||
|
.collect::<Result<_, _>>()
|
||||||
|
.map_err(|e| format!("cannot parse the certificate chain: {e}"))?;
|
||||||
|
if chain.is_empty() {
|
||||||
|
return Err("the certificate file has no certificate".into());
|
||||||
|
}
|
||||||
|
// Never include key bytes in an error.
|
||||||
|
let key = PrivateKeyDer::from_pem_slice(key_pem)
|
||||||
|
.map_err(|_| "cannot parse the private key".to_owned())?;
|
||||||
|
let provider = rustls::crypto::ring::default_provider();
|
||||||
|
CertifiedKey::from_der(chain, key, &provider)
|
||||||
|
.map_err(|e| format!("certificate and key do not form a usable pair: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `notAfter` of the first certificate in a PEM chain, as Unix seconds.
|
||||||
|
pub fn not_after(cert_pem: &[u8]) -> Option<i64> {
|
||||||
|
let first = CertificateDer::pem_slice_iter(cert_pem).next()?.ok()?;
|
||||||
|
let (_, cert) = x509_parser::parse_x509_certificate(first.as_ref()).ok()?;
|
||||||
|
Some(cert.validity().not_after.timestamp())
|
||||||
|
}
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! ACME end to end against Pebble (Let's Encrypt's test ACME server) on 127.0.0.1:
|
||||||
|
//! edge creates an account, answers the HTTP-01 challenge on its HTTP listener, obtains a
|
||||||
|
//! certificate, stores it with private permissions and serves it by SNI, next to a host with a
|
||||||
|
//! Domi (test CA) certificate. Needs `pebble` and `pebble-challtestsrv` on PATH; without them
|
||||||
|
//! the test fails unless `IANITOR_ALLOW_SKIP=1`.
|
||||||
|
//!
|
||||||
|
//! This is not Let's Encrypt staging: that needs a public domain and DNS.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::common::{EdgeSpec, host_file, spawn};
|
||||||
|
use ianitor_testkit::client::{self, Req};
|
||||||
|
use ianitor_testkit::proc::{
|
||||||
|
ChildGuard, TempDir, free_port, local, require_binary, wait_for_port,
|
||||||
|
};
|
||||||
|
use ianitor_testkit::tls::{TestCa, roots_from_pem};
|
||||||
|
use ianitor_testkit::upstream::Echo;
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn certificate_is_obtained_from_pebble_and_served() {
|
||||||
|
let (Some(pebble), Some(challtestsrv)) = (
|
||||||
|
require_binary("pebble"),
|
||||||
|
require_binary("pebble-challtestsrv"),
|
||||||
|
) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let dir = TempDir::new("pebble");
|
||||||
|
// Pebble's own HTTPS endpoint needs a certificate; our test CA signs one for 127.0.0.1.
|
||||||
|
let ca = TestCa::new("Pebble Listener CA");
|
||||||
|
let leaf = ca.issue(&["127.0.0.1"]);
|
||||||
|
std::fs::write(dir.join("pebble.crt"), &leaf.cert_pem).unwrap();
|
||||||
|
std::fs::write(dir.join("pebble.key"), &leaf.key_pem).unwrap();
|
||||||
|
std::fs::write(dir.join("listener-ca.pem"), &ca.cert_pem).unwrap();
|
||||||
|
|
||||||
|
let (acme_port, mgmt_port, dns_port, cts_mgmt, tls_port) = (
|
||||||
|
free_port(),
|
||||||
|
free_port(),
|
||||||
|
free_port(),
|
||||||
|
free_port(),
|
||||||
|
free_port(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let edge_http = free_port();
|
||||||
|
let config = serde_json::json!({ "pebble": {
|
||||||
|
"listenAddress": format!("127.0.0.1:{acme_port}"),
|
||||||
|
"managementListenAddress": format!("127.0.0.1:{mgmt_port}"),
|
||||||
|
"certificate": dir.str("pebble.crt"),
|
||||||
|
"privateKey": dir.str("pebble.key"),
|
||||||
|
"httpPort": edge_http,
|
||||||
|
"tlsPort": tls_port,
|
||||||
|
"ocspResponderURL": "",
|
||||||
|
"externalAccountBindingRequired": false,
|
||||||
|
"domainBlocklist": [],
|
||||||
|
"retryAfter": { "authz": 1, "order": 1 },
|
||||||
|
"profiles": { "default": { "description": "test", "validityPeriod": 7_776_000 } }
|
||||||
|
}});
|
||||||
|
std::fs::write(dir.join("pebble.json"), config.to_string()).unwrap();
|
||||||
|
let log = std::fs::File::create(dir.join("pebble.log")).unwrap();
|
||||||
|
|
||||||
|
// Fake DNS: every name resolves to 127.0.0.1, so Pebble validates against edge.
|
||||||
|
let _cts = ChildGuard(
|
||||||
|
Command::new(challtestsrv)
|
||||||
|
.args(["-defaultIPv4", "127.0.0.1", "-defaultIPv6", ""])
|
||||||
|
.args(["-dns01", &format!("127.0.0.1:{dns_port}")])
|
||||||
|
.args(["-management", &format!("127.0.0.1:{cts_mgmt}")])
|
||||||
|
.args(["-http01", "", "-https01", "", "-tlsalpn01", "", "-doh", ""])
|
||||||
|
.stdout(Stdio::from(log.try_clone().unwrap()))
|
||||||
|
.stderr(Stdio::from(log.try_clone().unwrap()))
|
||||||
|
.spawn()
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
let _pebble = ChildGuard(
|
||||||
|
Command::new(pebble)
|
||||||
|
.arg("-config")
|
||||||
|
.arg(dir.join("pebble.json"))
|
||||||
|
.args(["-dnsserver", &format!("127.0.0.1:{dns_port}")])
|
||||||
|
.env("PEBBLE_VA_NOSLEEP", "1")
|
||||||
|
.env("PEBBLE_WFE_NONCEREJECT", "0")
|
||||||
|
.env("PEBBLE_AUTHZREUSE", "0")
|
||||||
|
.stdout(Stdio::from(log.try_clone().unwrap()))
|
||||||
|
.stderr(Stdio::from(log))
|
||||||
|
.spawn()
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
wait_for_port(local(acme_port), Duration::from_secs(20)),
|
||||||
|
"pebble did not start"
|
||||||
|
);
|
||||||
|
assert!(wait_for_port(local(mgmt_port), Duration::from_secs(5)));
|
||||||
|
|
||||||
|
// Edge starts after Pebble, so its first ACME round succeeds.
|
||||||
|
let echo_acme = Echo::start("acme-upstream").await;
|
||||||
|
let echo_domi = Echo::start("domi-upstream").await;
|
||||||
|
let site = format!(
|
||||||
|
"[acme]\nemail = \"admin@example.org\"\ndirectory = \"https://127.0.0.1:{acme_port}/dir\"\n"
|
||||||
|
);
|
||||||
|
let mut edge = spawn(EdgeSpec {
|
||||||
|
site: &site,
|
||||||
|
hosts: vec![
|
||||||
|
(
|
||||||
|
"hosts/acme.test.toml".into(),
|
||||||
|
format!(
|
||||||
|
"hostname = \"acme.test\"\ntls = \"letsencrypt\"\nupstreams = [\"{}\"]\n",
|
||||||
|
echo_acme.url()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
host_file(
|
||||||
|
"domi.test",
|
||||||
|
&format!("upstreams = [\"{}\"]\n", echo_domi.url()),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
log_level: "debug",
|
||||||
|
extra_args: vec!["--acme-root".into(), dir.str("listener-ca.pem")],
|
||||||
|
http_port: Some(edge_http),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
wait_for_port(edge.http, Duration::from_secs(20)),
|
||||||
|
"edge HTTP listener:\n{}",
|
||||||
|
edge.stderr()
|
||||||
|
);
|
||||||
|
|
||||||
|
// The root Pebble signs with (generated at Pebble start).
|
||||||
|
let root = client::https(
|
||||||
|
local(mgmt_port),
|
||||||
|
"127.0.0.1",
|
||||||
|
ca.roots(),
|
||||||
|
&Req::get(&format!("127.0.0.1:{mgmt_port}"), "/roots/0"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(root.status, 200);
|
||||||
|
let pebble_roots = roots_from_pem(&root.text());
|
||||||
|
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(90);
|
||||||
|
let served = loop {
|
||||||
|
if let Ok(r) = client::https(
|
||||||
|
edge.https,
|
||||||
|
"acme.test",
|
||||||
|
pebble_roots.clone(),
|
||||||
|
&Req::get("acme.test", "/via-acme"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
break r;
|
||||||
|
}
|
||||||
|
if Instant::now() > deadline || edge.exited().is_some() {
|
||||||
|
panic!(
|
||||||
|
"no ACME certificate served in time.\n--- edge ---\n{}\n--- pebble ---\n{}",
|
||||||
|
edge.stderr(),
|
||||||
|
std::fs::read_to_string(dir.join("pebble.log")).unwrap_or_default()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||||
|
};
|
||||||
|
assert_eq!(served.status, 200);
|
||||||
|
assert!(served.text().contains("acme-upstream"), "{}", served.text());
|
||||||
|
assert!(
|
||||||
|
edge.stderr().contains("acme.test: certificate issued"),
|
||||||
|
"{}",
|
||||||
|
edge.stderr()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
edge.stderr()
|
||||||
|
.contains("answered HTTP-01 challenge for acme.test"),
|
||||||
|
"the challenge was really validated"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The Domi host keeps working with its own CA next to the ACME host.
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"domi.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("domi.test", "/"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
assert!(r.text().contains("domi-upstream"));
|
||||||
|
|
||||||
|
// Stored with private permissions.
|
||||||
|
let acme_dir = edge.dir.join("state/acme");
|
||||||
|
for f in ["acme.test.key", "acme.test.crt"] {
|
||||||
|
let mode = std::fs::metadata(acme_dir.join(f))
|
||||||
|
.unwrap()
|
||||||
|
.permissions()
|
||||||
|
.mode()
|
||||||
|
& 0o777;
|
||||||
|
assert_eq!(mode, 0o600, "{f} has mode {mode:o}");
|
||||||
|
}
|
||||||
|
let account = std::fs::read_dir(&acme_dir)
|
||||||
|
.unwrap()
|
||||||
|
.map(|e| e.unwrap().path())
|
||||||
|
.find(|p| {
|
||||||
|
p.file_name()
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.starts_with("account-")
|
||||||
|
})
|
||||||
|
.expect("account file stored");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::metadata(account).unwrap().permissions().mode() & 0o777,
|
||||||
|
0o600
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!edge.stderr().contains("PRIVATE KEY"),
|
||||||
|
"no key material in the log"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Runs the real `ianitor-edge` binary on 127.0.0.1 with a compiled config, a test CA for
|
||||||
|
//! `tls = "domi"` hosts and a credentials directory. stderr goes to a file the tests inspect.
|
||||||
|
//! Every edge also gets an admin socket and a share-link revocation file in its directory.
|
||||||
|
|
||||||
|
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use ianitor_core::compile::{self, CompileOptions};
|
||||||
|
use ianitor_core::{SourceFile, TlsMode, load};
|
||||||
|
use ianitor_testkit::more::{JsonResp, unix_json};
|
||||||
|
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
|
||||||
|
use ianitor_testkit::tls::TestCa;
|
||||||
|
use rustls::RootCertStore;
|
||||||
|
|
||||||
|
/// The share-link key written as the `share-link-key` credential of every test edge.
|
||||||
|
pub const SHARE_KEY: &[u8] = b"edge-test-share-key-0123456789abcdef0123456789";
|
||||||
|
|
||||||
|
pub struct Edge {
|
||||||
|
pub child: ChildGuard,
|
||||||
|
pub http: SocketAddr,
|
||||||
|
pub https: SocketAddr,
|
||||||
|
pub dir: TempDir,
|
||||||
|
pub ca: TestCa,
|
||||||
|
pub config_text: String,
|
||||||
|
pub opts: CompileOptions,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Edge {
|
||||||
|
pub fn roots(&self) -> Arc<RootCertStore> {
|
||||||
|
self.ca.roots()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stderr(&self) -> String {
|
||||||
|
std::fs::read_to_string(self.dir.join("edge.stderr")).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn access_log(&self) -> String {
|
||||||
|
std::fs::read_to_string(self.dir.join("logs/access.log")).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything edge wrote or was given, except the credentials themselves.
|
||||||
|
pub fn all_output(&self) -> String {
|
||||||
|
format!(
|
||||||
|
"{}\n{}\n{}",
|
||||||
|
self.stderr(),
|
||||||
|
self.access_log(),
|
||||||
|
self.config_text
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn exited(&mut self) -> Option<std::process::ExitStatus> {
|
||||||
|
self.child.0.try_wait().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn admin_socket(&self) -> PathBuf {
|
||||||
|
self.dir.join("admin.sock")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn config_path(&self) -> PathBuf {
|
||||||
|
self.dir.join("edge.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn trial_path(&self) -> PathBuf {
|
||||||
|
self.dir.join("edge.json.trial")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn revocations_path(&self) -> PathBuf {
|
||||||
|
self.dir.join("share-revocations.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compile routes with this edge's options (same ports, same directories).
|
||||||
|
pub fn compile(&self, site: &str, hosts: &[(String, String)]) -> String {
|
||||||
|
compile_with(&self.dir, &self.ca, &self.opts, site, hosts)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Call the admin socket.
|
||||||
|
pub async fn admin(
|
||||||
|
&self,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
body: Option<serde_json::Value>,
|
||||||
|
) -> JsonResp {
|
||||||
|
unix_json(&self.admin_socket(), method, path, body.as_ref())
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("admin {method} {path}: {e}\n{}", self.stderr()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_revocations(&self, epoch: u32, deny: &[String]) {
|
||||||
|
let v = serde_json::json!({ "epoch": epoch, "deny": deny });
|
||||||
|
std::fs::write(self.revocations_path(), v.to_string()).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EdgeSpec<'a> {
|
||||||
|
pub site: &'a str,
|
||||||
|
pub hosts: Vec<(String, String)>,
|
||||||
|
pub secrets: Vec<(String, Vec<u8>)>,
|
||||||
|
pub log_level: &'a str,
|
||||||
|
pub extra_args: Vec<String>,
|
||||||
|
/// Fixed HTTP port (e.g. one Pebble was told to validate against).
|
||||||
|
pub http_port: Option<u16>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for EdgeSpec<'_> {
|
||||||
|
fn default() -> Self {
|
||||||
|
EdgeSpec {
|
||||||
|
site: "",
|
||||||
|
hosts: Vec::new(),
|
||||||
|
secrets: Vec::new(),
|
||||||
|
log_level: "info",
|
||||||
|
extra_args: Vec::new(),
|
||||||
|
http_port: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load and compile; write a Domi certificate for every `tls = "domi"` host that has none.
|
||||||
|
fn compile_with(
|
||||||
|
dir: &TempDir,
|
||||||
|
ca: &TestCa,
|
||||||
|
opts: &CompileOptions,
|
||||||
|
site: &str,
|
||||||
|
hosts: &[(String, String)],
|
||||||
|
) -> String {
|
||||||
|
let sources: Vec<SourceFile> = hosts
|
||||||
|
.iter()
|
||||||
|
.map(|(n, c)| SourceFile {
|
||||||
|
name: n,
|
||||||
|
contents: c,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let model = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: site,
|
||||||
|
},
|
||||||
|
&sources,
|
||||||
|
)
|
||||||
|
.expect("valid routes");
|
||||||
|
for h in model.hosts() {
|
||||||
|
let crt = dir.join(&format!("certs/{}.crt", h.hostname));
|
||||||
|
if h.tls == TlsMode::Domi && !crt.exists() {
|
||||||
|
let leaf = ca.issue(&[h.hostname.as_str()]);
|
||||||
|
std::fs::write(&crt, leaf.cert_pem).unwrap();
|
||||||
|
std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compile::edge(&model, opts).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compile, write certificates and credentials, start the binary. Does not wait for readiness.
|
||||||
|
pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
|
||||||
|
let dir = TempDir::new("edge");
|
||||||
|
for d in ["certs", "state", "creds", "logs"] {
|
||||||
|
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||||
|
}
|
||||||
|
let ca = TestCa::new("Ianitor Test CA");
|
||||||
|
std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap();
|
||||||
|
for (name, value) in &spec.secrets {
|
||||||
|
std::fs::write(dir.join(&format!("creds/{name}")), value).unwrap();
|
||||||
|
}
|
||||||
|
std::fs::write(
|
||||||
|
dir.join("share-revocations.json"),
|
||||||
|
"{\"epoch\": 0, \"deny\": []}",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let http = local(spec.http_port.unwrap_or_else(free_port));
|
||||||
|
let https = local(free_port());
|
||||||
|
let opts = CompileOptions {
|
||||||
|
http_listen: http,
|
||||||
|
https_listen: https,
|
||||||
|
cert_dir: dir.str("certs"),
|
||||||
|
state_dir: dir.str("state"),
|
||||||
|
access_log: dir.str("logs/access.log"),
|
||||||
|
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
|
||||||
|
caddy_admin: None,
|
||||||
|
};
|
||||||
|
let config_text = compile_with(&dir, &ca, &opts, spec.site, &spec.hosts);
|
||||||
|
std::fs::write(dir.join("edge.json"), &config_text).unwrap();
|
||||||
|
|
||||||
|
let child = launch(&dir, &spec.extra_args, spec.log_level);
|
||||||
|
Edge {
|
||||||
|
child,
|
||||||
|
http,
|
||||||
|
https,
|
||||||
|
dir,
|
||||||
|
ca,
|
||||||
|
config_text,
|
||||||
|
opts,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn launch(dir: &TempDir, extra_args: &[String], log_level: &str) -> ChildGuard {
|
||||||
|
let stderr = std::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.append(true)
|
||||||
|
.open(dir.join("edge.stderr"))
|
||||||
|
.unwrap();
|
||||||
|
let mut cmd = Command::new(env!("CARGO_BIN_EXE_ianitor-edge"));
|
||||||
|
cmd.arg("--config").arg(dir.join("edge.json"));
|
||||||
|
cmd.arg("--admin-socket").arg(dir.join("admin.sock"));
|
||||||
|
cmd.arg("--share-revocations")
|
||||||
|
.arg(dir.join("share-revocations.json"));
|
||||||
|
cmd.args(extra_args);
|
||||||
|
cmd.env("CREDENTIALS_DIRECTORY", dir.join("creds"));
|
||||||
|
cmd.env("IANITOR_LOG", log_level);
|
||||||
|
cmd.stdout(Stdio::from(stderr.try_clone().unwrap()))
|
||||||
|
.stderr(Stdio::from(stderr));
|
||||||
|
ChildGuard(cmd.spawn().expect("spawn ianitor-edge"))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Edge {
|
||||||
|
/// Stop edge and start it again on the same directory, config and ports.
|
||||||
|
pub fn restart(&mut self) {
|
||||||
|
let _ = self.child.0.kill();
|
||||||
|
let _ = self.child.0.wait();
|
||||||
|
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||||
|
while std::net::TcpStream::connect(self.https).is_ok()
|
||||||
|
&& std::time::Instant::now() < deadline
|
||||||
|
{
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_file(self.admin_socket());
|
||||||
|
self.child = launch(&self.dir, &[], "info");
|
||||||
|
let ok = wait_for_port(self.https, Duration::from_secs(20));
|
||||||
|
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||||
|
while !self.admin_socket().exists() && std::time::Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
ok && self.admin_socket().exists(),
|
||||||
|
"edge did not restart:\n{}",
|
||||||
|
self.stderr()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spawn and wait until both listeners and the admin socket accept connections.
|
||||||
|
pub fn start(spec: EdgeSpec<'_>) -> Edge {
|
||||||
|
let mut e = spawn(spec);
|
||||||
|
let ok = wait_for_port(e.https, Duration::from_secs(20))
|
||||||
|
&& wait_for_port(e.http, Duration::from_secs(5));
|
||||||
|
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||||
|
while !e.admin_socket().exists() && std::time::Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
}
|
||||||
|
if !ok || !e.admin_socket().exists() || e.exited().is_some() {
|
||||||
|
panic!("ianitor-edge did not start:\n{}", e.stderr());
|
||||||
|
}
|
||||||
|
e
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn host_file(hostname: &str, body: &str) -> (String, String) {
|
||||||
|
(
|
||||||
|
format!("hosts/{hostname}.toml"),
|
||||||
|
format!("hostname = \"{hostname}\"\ntls = \"domi\"\n{body}"),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Forward-auth (Authelia-compatible): a denial never reaches the upstream, the auth answer
|
||||||
|
//! goes back to the client unchanged, and an allowed request carries the identity headers
|
||||||
|
//! from the auth server and never the client's own.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
|
||||||
|
use crate::common::{EdgeSpec, host_file, start};
|
||||||
|
use ianitor_testkit::authelia::MockAuthelia;
|
||||||
|
use ianitor_testkit::client::{self, Req, WsOutcome};
|
||||||
|
use ianitor_testkit::upstream::{Echo, WsEcho, closed_port};
|
||||||
|
|
||||||
|
fn site(auth_url: &str) -> String {
|
||||||
|
format!("[forward_auth]\nurl = \"{auth_url}\"\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn denial_never_reaches_the_upstream() {
|
||||||
|
let authelia = MockAuthelia::start().await;
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let ws = WsEcho::start().await;
|
||||||
|
let site = site(&authelia.url());
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
site: &site,
|
||||||
|
hosts: vec![
|
||||||
|
host_file(
|
||||||
|
"auth.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
host_file(
|
||||||
|
"wsauth.test",
|
||||||
|
&format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", ws.url()),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let roots = edge.roots();
|
||||||
|
let go = |req: Req| {
|
||||||
|
let roots = roots.clone();
|
||||||
|
let addr = edge.https;
|
||||||
|
async move { client::https(addr, "auth.test", roots, &req).await.unwrap() }
|
||||||
|
};
|
||||||
|
|
||||||
|
// No session: browser GET is redirected to the portal, with Authelia's headers and body.
|
||||||
|
let r = go(Req::get("auth.test", "/private?x=1")).await;
|
||||||
|
assert_eq!(r.status, 302);
|
||||||
|
assert_eq!(
|
||||||
|
r.header("location"),
|
||||||
|
Some("https://auth.test/?rd=https%3A%2F%2Fauth.test%2Fprivate%3Fx%3D1")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
r.header("set-cookie"),
|
||||||
|
Some("authelia_flow=1; Path=/; HttpOnly")
|
||||||
|
);
|
||||||
|
assert!(r.text().contains("302 Found"));
|
||||||
|
|
||||||
|
let r = go(Req::new("HEAD", "auth.test", "/")).await;
|
||||||
|
assert_eq!(r.status, 302);
|
||||||
|
|
||||||
|
let r = go(Req::new("POST", "auth.test", "/submit?x=1").body(b"do-not-forward")).await;
|
||||||
|
assert_eq!(r.status, 401);
|
||||||
|
assert_eq!(r.text(), "401 Unauthorized");
|
||||||
|
|
||||||
|
let r = go(Req::get("auth.test", "/").header("authorization", "Bearer wrong")).await;
|
||||||
|
assert_eq!(r.status, 401);
|
||||||
|
assert_eq!(
|
||||||
|
r.header("www-authenticate"),
|
||||||
|
Some("Basic realm=\"Authorization Required\"")
|
||||||
|
);
|
||||||
|
|
||||||
|
let r = go(Req::get("auth.test", "/").header("cookie", "authelia_session=forbidden")).await;
|
||||||
|
assert_eq!(r.status, 403);
|
||||||
|
|
||||||
|
// Spoofed identity and forwarding headers do not help.
|
||||||
|
let r = go(Req::get("auth.test", "/admin")
|
||||||
|
.header("remote-user", "admin")
|
||||||
|
.header("x-forwarded-method", "GET")
|
||||||
|
.header("x-forwarded-uri", "/public")
|
||||||
|
.header("x-forwarded-host", "public.test")
|
||||||
|
.header("x-forwarded-for", "10.0.0.1"))
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 302);
|
||||||
|
assert!(
|
||||||
|
r.header("location").unwrap().contains("auth.test%2Fadmin"),
|
||||||
|
"edge sends its own X-Forwarded-*"
|
||||||
|
);
|
||||||
|
|
||||||
|
// A websocket upgrade without a session is denied before any upgrade happens.
|
||||||
|
match client::websocket(
|
||||||
|
edge.https,
|
||||||
|
"wsauth.test",
|
||||||
|
roots.clone(),
|
||||||
|
"wsauth.test",
|
||||||
|
"/socket",
|
||||||
|
&[],
|
||||||
|
"hi",
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
{
|
||||||
|
WsOutcome::Refused(r) => assert_eq!(r.status, 302),
|
||||||
|
WsOutcome::Upgraded { .. } => panic!("unauthenticated websocket was upgraded"),
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
echo.proxied().is_empty(),
|
||||||
|
"a denied request reached the upstream: {:?}",
|
||||||
|
echo.proxied()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
ws.connections(),
|
||||||
|
0,
|
||||||
|
"a denied websocket reached the upstream"
|
||||||
|
);
|
||||||
|
|
||||||
|
// What Authelia was told, per its proxy-authorization guide.
|
||||||
|
let asked = authelia.requests();
|
||||||
|
assert!(asked.len() >= 7, "{asked:?}");
|
||||||
|
let post = asked
|
||||||
|
.iter()
|
||||||
|
.find(|r| r.header("x-forwarded-method") == Some(b"POST".as_slice()))
|
||||||
|
.expect("the POST was checked");
|
||||||
|
assert_eq!(post.method, "GET", "the auth subrequest is a GET");
|
||||||
|
assert_eq!(post.path, "/api/authz/forward-auth");
|
||||||
|
assert_eq!(post.header("x-forwarded-proto"), Some(b"https".as_slice()));
|
||||||
|
assert_eq!(
|
||||||
|
post.header("x-forwarded-host"),
|
||||||
|
Some(b"auth.test".as_slice())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
post.header("x-forwarded-uri"),
|
||||||
|
Some(b"/submit?x=1".as_slice())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
post.header("x-forwarded-for"),
|
||||||
|
Some(b"127.0.0.1".as_slice())
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
post.body.is_empty(),
|
||||||
|
"the request body is not sent to the auth server"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn allowed_request_carries_identity_from_the_auth_server_only() {
|
||||||
|
let authelia = MockAuthelia::start().await;
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let site = site(&authelia.url());
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
site: &site,
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"auth.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
)],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let roots = edge.roots();
|
||||||
|
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"auth.test",
|
||||||
|
roots.clone(),
|
||||||
|
&Req::new("POST", "auth.test", "/submit")
|
||||||
|
.header("cookie", "authelia_session=good")
|
||||||
|
.header("remote-user", "mallory")
|
||||||
|
.header("remote-groups", "root")
|
||||||
|
.body(b"form=data"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text());
|
||||||
|
let seen = echo.proxied();
|
||||||
|
assert_eq!(seen.len(), 1);
|
||||||
|
let up = &seen[0];
|
||||||
|
assert_eq!(up.header("remote-user"), Some(b"alice".as_slice()));
|
||||||
|
assert_eq!(up.header("remote-groups"), Some(b"admins,dev".as_slice()));
|
||||||
|
assert_eq!(
|
||||||
|
up.header("remote-email"),
|
||||||
|
Some(b"alice@example.org".as_slice())
|
||||||
|
);
|
||||||
|
assert_eq!(up.header("remote-name"), Some(b"Alice Example".as_slice()));
|
||||||
|
assert_eq!(up.body, b"form=data", "the body still reaches the upstream");
|
||||||
|
assert_eq!(
|
||||||
|
up.headers
|
||||||
|
.iter()
|
||||||
|
.filter(|(n, _)| n == "remote-user")
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
|
||||||
|
// Allowed without identity: the client's own Remote-* headers are removed, not passed on.
|
||||||
|
echo.clear();
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"auth.test",
|
||||||
|
roots.clone(),
|
||||||
|
&Req::get("auth.test", "/")
|
||||||
|
.header("cookie", "authelia_session=nameless")
|
||||||
|
.header("remote-user", "mallory"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
assert_eq!(echo.proxied()[0].header("remote-user"), None);
|
||||||
|
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"auth.test",
|
||||||
|
roots,
|
||||||
|
&Req::get("auth.test", "/").header("authorization", "Bearer good"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn unreachable_auth_server_fails_closed() {
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let site = site(&format!(
|
||||||
|
"http://127.0.0.1:{}/api/authz/forward-auth",
|
||||||
|
closed_port()
|
||||||
|
));
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
site: &site,
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"auth.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
)],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"auth.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("auth.test", "/").header("cookie", "authelia_session=good"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 502);
|
||||||
|
assert!(echo.proxied().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC B2a, B2b, m3: misbehaving auth servers. Edge fails closed and never crashes or hangs.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn misbehaving_auth_answers_fail_closed() {
|
||||||
|
let authelia = MockAuthelia::start().await;
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let site = site(&authelia.url());
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
site: &site,
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"auth.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
)],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let go = |session: &'static str| {
|
||||||
|
let roots = edge.roots();
|
||||||
|
let addr = edge.https;
|
||||||
|
async move {
|
||||||
|
let cookie = format!("authelia_session={session}");
|
||||||
|
client::https(
|
||||||
|
addr,
|
||||||
|
"auth.test",
|
||||||
|
roots,
|
||||||
|
&Req::get("auth.test", "/").header("cookie", &cookie),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 100 Continue before the real answer is skipped, like any HTTP client does.
|
||||||
|
let r = go("continue-ok")
|
||||||
|
.await
|
||||||
|
.expect("edge answers after a 1xx from the auth server");
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
assert_eq!(echo.proxied().len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
echo.proxied()[0].header("remote-user"),
|
||||||
|
Some(b"alice".as_slice())
|
||||||
|
);
|
||||||
|
echo.clear();
|
||||||
|
|
||||||
|
// 101 is a final answer but not an allow: denied with 502.
|
||||||
|
assert_eq!(go("switch").await.unwrap().status, 502);
|
||||||
|
// Oversized or truncated auth answers: 502, never forwarded.
|
||||||
|
assert_eq!(go("big-ok").await.unwrap().status, 502);
|
||||||
|
assert_eq!(go("big-deny").await.unwrap().status, 502);
|
||||||
|
assert_eq!(go("truncated-ok").await.unwrap().status, 502);
|
||||||
|
assert!(echo.proxied().is_empty(), "{:?}", echo.proxied());
|
||||||
|
|
||||||
|
// An auth server that never answers: 502 once the 10 s auth timeout passes.
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let r = go("hang")
|
||||||
|
.await
|
||||||
|
.expect("edge answers a hanging auth server");
|
||||||
|
assert_eq!(r.status, 502);
|
||||||
|
assert!(
|
||||||
|
t.elapsed() < std::time::Duration::from_secs(14),
|
||||||
|
"took {:?}",
|
||||||
|
t.elapsed()
|
||||||
|
);
|
||||||
|
assert!(echo.proxied().is_empty());
|
||||||
|
|
||||||
|
// Still serving afterwards.
|
||||||
|
assert_eq!(go("good").await.unwrap().status, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC m5: client-sent Remote-* headers never reach a forward-auth upstream, whatever
|
||||||
|
/// copy_headers says.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn remote_headers_are_stripped_even_with_a_custom_copy_list() {
|
||||||
|
let authelia = MockAuthelia::start().await;
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
for copy in ["[]", "[\"Remote-User\"]"] {
|
||||||
|
echo.clear();
|
||||||
|
let site = format!(
|
||||||
|
"[forward_auth]\nurl = \"{}\"\ncopy_headers = {copy}\n",
|
||||||
|
authelia.url()
|
||||||
|
);
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
site: &site,
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"auth.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
)],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"auth.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("auth.test", "/")
|
||||||
|
.header("cookie", "authelia_session=good")
|
||||||
|
.header("remote-user", "mallory")
|
||||||
|
.header("remote-groups", "root")
|
||||||
|
.header("remote-email", "m@evil.test")
|
||||||
|
.header("remote-name", "Mallory"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
let up = &echo.proxied()[0];
|
||||||
|
let user = up.header("remote-user");
|
||||||
|
if copy == "[]" {
|
||||||
|
assert_eq!(user, None, "copy_headers = []");
|
||||||
|
} else {
|
||||||
|
assert_eq!(user, Some(b"alice".as_slice()));
|
||||||
|
}
|
||||||
|
for h in ["remote-groups", "remote-email", "remote-name"] {
|
||||||
|
assert_eq!(up.header(h), None, "{h} with copy_headers = {copy}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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/.
|
||||||
|
|
||||||
|
//! Reload (ROADMAP §8.4, tests first): edge swaps its config in process, so a reload under
|
||||||
|
//! load drops no request and no keep-alive connection; an invalid config is refused and the
|
||||||
|
//! old one keeps serving; a trial config reverts by itself unless control confirms it; the
|
||||||
|
//! admin socket reports health per host and upstream.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::common::{Edge, EdgeSpec, host_file, start};
|
||||||
|
use ianitor_testkit::client::{self, Req};
|
||||||
|
use ianitor_testkit::more::KeepAlive;
|
||||||
|
use ianitor_testkit::upstream::Echo;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn gen_host(echo: &Echo, generation: &str) -> Vec<(String, String)> {
|
||||||
|
vec![host_file(
|
||||||
|
"app.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-Generation\"\nvalue = \"{generation}\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
)]
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn generation(edge: &Edge) -> String {
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"app.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("app.test", "/"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text());
|
||||||
|
r.header("x-generation").unwrap_or("none").to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha256(text: &str) -> String {
|
||||||
|
ring::digest::digest(&ring::digest::SHA256, text.as_bytes())
|
||||||
|
.as_ref()
|
||||||
|
.iter()
|
||||||
|
.map(|b| format!("{b:02x}"))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
|
||||||
|
async fn reload_under_load_drops_nothing() {
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: gen_host(&echo, "a"),
|
||||||
|
log_level: "warn",
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let config_a = edge.config_text.clone();
|
||||||
|
let config_b = edge.compile("", &gen_host(&echo, "b"));
|
||||||
|
|
||||||
|
let clients: usize = std::env::var("IANITOR_RELOAD_CLIENTS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(32);
|
||||||
|
let secs: u64 = std::env::var("IANITOR_RELOAD_SECS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(10);
|
||||||
|
|
||||||
|
let stop = Arc::new(AtomicBool::new(false));
|
||||||
|
let ok = Arc::new(AtomicU64::new(0));
|
||||||
|
let errors = Arc::new(AtomicU64::new(0));
|
||||||
|
let resets = Arc::new(AtomicU64::new(0));
|
||||||
|
let mut tasks = Vec::new();
|
||||||
|
for _ in 0..clients {
|
||||||
|
let (stop, ok, errors, resets) =
|
||||||
|
(stop.clone(), ok.clone(), errors.clone(), resets.clone());
|
||||||
|
let (addr, roots) = (edge.https, edge.roots());
|
||||||
|
tasks.push(tokio::spawn(async move {
|
||||||
|
let mut conn = KeepAlive::connect(addr, "app.test", roots).await.unwrap();
|
||||||
|
let mut seen = std::collections::BTreeSet::new();
|
||||||
|
let mut latencies = Vec::new();
|
||||||
|
while !stop.load(Ordering::Relaxed) {
|
||||||
|
let t = Instant::now();
|
||||||
|
match conn.send(&Req::get("app.test", "/load")).await {
|
||||||
|
Ok(r) if r.status == 200 => {
|
||||||
|
ok.fetch_add(1, Ordering::Relaxed);
|
||||||
|
seen.insert(r.header("x-generation").unwrap_or("none").to_owned());
|
||||||
|
latencies.push(t.elapsed());
|
||||||
|
}
|
||||||
|
Ok(_) => {
|
||||||
|
errors.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
// The keep-alive connection is gone.
|
||||||
|
resets.fetch_add(1, Ordering::Relaxed);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(seen, latencies)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
let started = Instant::now();
|
||||||
|
let mut reloads = 0u64;
|
||||||
|
let mut refused = 0u64;
|
||||||
|
while started.elapsed() < Duration::from_secs(secs) {
|
||||||
|
let text = if reloads.is_multiple_of(2) {
|
||||||
|
&config_b
|
||||||
|
} else {
|
||||||
|
&config_a
|
||||||
|
};
|
||||||
|
let tmp = edge.config_path().with_extension("tmp");
|
||||||
|
std::fs::write(&tmp, text).unwrap();
|
||||||
|
std::fs::rename(&tmp, edge.config_path()).unwrap();
|
||||||
|
let r = edge.admin("POST", "/v1/reload", None).await;
|
||||||
|
if r.status == 200 {
|
||||||
|
reloads += 1;
|
||||||
|
} else {
|
||||||
|
refused += 1;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
stop.store(true, Ordering::Relaxed);
|
||||||
|
let mut all_latencies = Vec::new();
|
||||||
|
let mut both = 0;
|
||||||
|
for t in tasks {
|
||||||
|
let (seen, lat) = t.await.unwrap();
|
||||||
|
if seen.contains("a") && seen.contains("b") {
|
||||||
|
both += 1;
|
||||||
|
}
|
||||||
|
all_latencies.extend(lat);
|
||||||
|
}
|
||||||
|
all_latencies.sort();
|
||||||
|
let pct = |p: f64| {
|
||||||
|
all_latencies
|
||||||
|
.get(((all_latencies.len() as f64 - 1.0) * p) as usize)
|
||||||
|
.copied()
|
||||||
|
.unwrap_or_default()
|
||||||
|
};
|
||||||
|
println!(
|
||||||
|
"RELOAD UNDER LOAD: {clients} keep-alive clients, {secs} s, {reloads} reloads ({refused} refused), \
|
||||||
|
{} requests ok, {} errors, {} connection resets, {both}/{clients} connections saw both configs, \
|
||||||
|
latency p50 {:?} p99 {:?} max {:?}",
|
||||||
|
ok.load(Ordering::Relaxed),
|
||||||
|
errors.load(Ordering::Relaxed),
|
||||||
|
resets.load(Ordering::Relaxed),
|
||||||
|
pct(0.5),
|
||||||
|
pct(0.99),
|
||||||
|
pct(1.0),
|
||||||
|
);
|
||||||
|
assert_eq!(refused, 0, "{}", edge.stderr());
|
||||||
|
assert!(reloads >= secs * 5, "only {reloads} reloads");
|
||||||
|
assert_eq!(errors.load(Ordering::Relaxed), 0);
|
||||||
|
assert_eq!(resets.load(Ordering::Relaxed), 0);
|
||||||
|
assert!(ok.load(Ordering::Relaxed) > 1000);
|
||||||
|
assert_eq!(
|
||||||
|
both, clients,
|
||||||
|
"every keep-alive connection must pick up new configs"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn an_invalid_config_is_refused_and_the_old_one_keeps_serving() {
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: gen_host(&echo, "a"),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let before = edge.admin("GET", "/v1/status", None).await;
|
||||||
|
assert_eq!(before.status, 200, "{}", before.text);
|
||||||
|
let sha = before.json["config_sha256"].as_str().unwrap().to_owned();
|
||||||
|
assert_eq!(sha, sha256(&edge.config_text));
|
||||||
|
|
||||||
|
let good_b = edge.compile("", &gen_host(&echo, "b"));
|
||||||
|
let mut broken_cert: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||||
|
broken_cert["hosts"][0]["tls"]["cert"] = json!("/nonexistent/app.test.crt");
|
||||||
|
let mut moved: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||||
|
moved["https_listen"] = json!("127.0.0.1:1");
|
||||||
|
let mut old_version: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||||
|
old_version["version"] = json!(1);
|
||||||
|
let mut share_without_key: serde_json::Value = serde_json::from_str(&good_b).unwrap();
|
||||||
|
share_without_key["hosts"][0]["share_links"] = json!(true);
|
||||||
|
std::fs::remove_file(edge.dir.join("creds/share-link-key")).unwrap();
|
||||||
|
|
||||||
|
for (what, text) in [
|
||||||
|
("not JSON", "{ not json".to_owned()),
|
||||||
|
("unknown field", good_b.replace("\"hosts\"", "\"hostz\"")),
|
||||||
|
("missing certificate", broken_cert.to_string()),
|
||||||
|
("listen address change", moved.to_string()),
|
||||||
|
("old version", old_version.to_string()),
|
||||||
|
("share links without key", share_without_key.to_string()),
|
||||||
|
] {
|
||||||
|
std::fs::write(edge.config_path(), &text).unwrap();
|
||||||
|
let r = edge.admin("POST", "/v1/reload", None).await;
|
||||||
|
assert_eq!(r.status, 422, "{what}: {}", r.text);
|
||||||
|
assert!(
|
||||||
|
r.json["error"].as_str().is_some_and(|e| !e.is_empty()),
|
||||||
|
"{what}: {}",
|
||||||
|
r.text
|
||||||
|
);
|
||||||
|
assert_eq!(generation(&edge).await, "a", "{what}");
|
||||||
|
let s = edge.admin("GET", "/v1/status", None).await;
|
||||||
|
assert_eq!(s.json["config_sha256"], sha, "{what}");
|
||||||
|
}
|
||||||
|
// A missing file is refused too.
|
||||||
|
std::fs::remove_file(edge.config_path()).unwrap();
|
||||||
|
assert_eq!(edge.admin("POST", "/v1/reload", None).await.status, 422);
|
||||||
|
assert_eq!(generation(&edge).await, "a");
|
||||||
|
|
||||||
|
// And a good one is taken.
|
||||||
|
std::fs::write(edge.config_path(), &good_b).unwrap();
|
||||||
|
let r = edge.admin("POST", "/v1/reload", None).await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
assert_eq!(r.json["config_sha256"], sha256(&good_b));
|
||||||
|
assert_eq!(generation(&edge).await, "b");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_trial_reverts_by_itself_unless_confirmed() {
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: gen_host(&echo, "a"),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let config_b = edge.compile("", &gen_host(&echo, "b"));
|
||||||
|
std::fs::write(edge.trial_path(), &config_b).unwrap();
|
||||||
|
|
||||||
|
// Not confirmed: back to "a" after the deadline, without anyone asking.
|
||||||
|
let r = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/trial",
|
||||||
|
Some(json!({ "confirm_within_secs": 2 })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
let trial_sha = r.json["config_sha256"].as_str().unwrap().to_owned();
|
||||||
|
assert_eq!(trial_sha, sha256(&config_b));
|
||||||
|
assert_eq!(generation(&edge).await, "b");
|
||||||
|
let s = edge.admin("GET", "/v1/status", None).await;
|
||||||
|
assert_eq!(s.json["trial"]["config_sha256"], trial_sha);
|
||||||
|
// No reload and no second trial while one runs.
|
||||||
|
assert_eq!(edge.admin("POST", "/v1/reload", None).await.status, 409);
|
||||||
|
assert_eq!(
|
||||||
|
edge.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/trial",
|
||||||
|
Some(json!({ "confirm_within_secs": 2 }))
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.status,
|
||||||
|
409
|
||||||
|
);
|
||||||
|
tokio::time::sleep(Duration::from_millis(3500)).await;
|
||||||
|
assert_eq!(generation(&edge).await, "a");
|
||||||
|
let s = edge.admin("GET", "/v1/status", None).await;
|
||||||
|
assert!(s.json["trial"].is_null(), "{}", s.text);
|
||||||
|
assert_eq!(s.json["config_sha256"], sha256(&edge.config_text));
|
||||||
|
// Confirming a trial that already reverted fails.
|
||||||
|
let r = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/confirm",
|
||||||
|
Some(json!({ "config_sha256": trial_sha })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 409, "{}", r.text);
|
||||||
|
|
||||||
|
// Confirmed: stays.
|
||||||
|
let r = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/trial",
|
||||||
|
Some(json!({ "confirm_within_secs": 2 })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
let wrong = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/confirm",
|
||||||
|
Some(json!({ "config_sha256": "00" })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(wrong.status, 409);
|
||||||
|
let r = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/confirm",
|
||||||
|
Some(json!({ "config_sha256": trial_sha })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||||
|
assert_eq!(generation(&edge).await, "b");
|
||||||
|
|
||||||
|
// Aborted: back at once. Abort is idempotent.
|
||||||
|
std::fs::write(edge.trial_path(), &edge.config_text).unwrap();
|
||||||
|
let r = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/trial",
|
||||||
|
Some(json!({ "confirm_within_secs": 30 })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
assert_eq!(generation(&edge).await, "a");
|
||||||
|
let r = edge.admin("POST", "/v1/abort", None).await;
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
assert_eq!(r.json["reverted"], true);
|
||||||
|
assert_eq!(generation(&edge).await, "b");
|
||||||
|
let r = edge.admin("POST", "/v1/abort", None).await;
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
assert_eq!(r.json["reverted"], false);
|
||||||
|
|
||||||
|
// A broken trial is refused and nothing changes.
|
||||||
|
std::fs::write(edge.trial_path(), "{}").unwrap();
|
||||||
|
let r = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/trial",
|
||||||
|
Some(json!({ "confirm_within_secs": 30 })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422);
|
||||||
|
assert_eq!(generation(&edge).await, "b");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn status_reports_health_per_host_and_upstream() {
|
||||||
|
let good = Echo::start("good").await;
|
||||||
|
let sick = Echo::start("sick").await;
|
||||||
|
sick.health.store(503, Ordering::SeqCst);
|
||||||
|
let closed = ianitor_testkit::upstream::closed_port();
|
||||||
|
let plain = Echo::start("plain").await;
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: vec![
|
||||||
|
host_file(
|
||||||
|
"mixed.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\", \"{}\", \"http://127.0.0.1:{closed}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n",
|
||||||
|
good.url(),
|
||||||
|
sick.url()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
host_file(
|
||||||
|
"plain.test",
|
||||||
|
&format!("upstreams = [\"{}\"]\n", plain.url()),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||||
|
let s = edge.admin("GET", "/v1/status", None).await;
|
||||||
|
assert_eq!(s.status, 200, "{}", s.text);
|
||||||
|
let hosts = s.json["hosts"].as_array().unwrap();
|
||||||
|
let mixed = hosts
|
||||||
|
.iter()
|
||||||
|
.find(|h| h["hostname"] == "mixed.test")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(mixed["health_check"], true);
|
||||||
|
let ups = mixed["upstreams"].as_array().unwrap();
|
||||||
|
assert_eq!(ups.len(), 3);
|
||||||
|
assert_eq!(ups[0]["healthy"], true, "{}", s.text);
|
||||||
|
assert_eq!(ups[1]["healthy"], false);
|
||||||
|
assert_eq!(ups[2]["healthy"], false);
|
||||||
|
let last = |u: &serde_json::Value| u["checks"].as_array().unwrap().last().unwrap().clone();
|
||||||
|
assert_eq!(last(&ups[0])["ok"], true);
|
||||||
|
assert!(last(&ups[0])["latency_ms"].is_u64());
|
||||||
|
assert_eq!(last(&ups[1])["kind"], "server_error");
|
||||||
|
assert_eq!(last(&ups[1])["status"], 503);
|
||||||
|
assert_eq!(last(&ups[2])["kind"], "refused");
|
||||||
|
assert!(ups[0]["checks"].as_array().unwrap().len() <= 5);
|
||||||
|
assert!(mixed["certificate"]["state"] == "ok");
|
||||||
|
let plain_h = hosts
|
||||||
|
.iter()
|
||||||
|
.find(|h| h["hostname"] == "plain.test")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(plain_h["health_check"], false);
|
||||||
|
assert!(
|
||||||
|
plain_h["upstreams"][0]["checks"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
|
||||||
|
// During a trial, watched hosts without a health check get `GET /` probes; any answer
|
||||||
|
// below 500 counts as alive. Hosts with one are checked at least every `every_secs`.
|
||||||
|
std::fs::write(edge.trial_path(), &edge.config_text).unwrap();
|
||||||
|
let r = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/trial",
|
||||||
|
Some(json!({ "confirm_within_secs": 30, "watch_hosts": ["plain.test"], "watch_every_secs": 1 })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||||
|
let s = edge.admin("GET", "/v1/status", None).await;
|
||||||
|
let plain_h = s.json["hosts"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|h| h["hostname"] == "plain.test")
|
||||||
|
.unwrap()
|
||||||
|
.clone();
|
||||||
|
let checks = plain_h["upstreams"][0]["checks"].as_array().unwrap();
|
||||||
|
assert!(!checks.is_empty(), "{}", s.text);
|
||||||
|
assert_eq!(checks.last().unwrap()["ok"], true);
|
||||||
|
assert_eq!(checks.last().unwrap()["source"], "watch");
|
||||||
|
assert!(
|
||||||
|
plain
|
||||||
|
.requests()
|
||||||
|
.iter()
|
||||||
|
.any(|r| r.path == "/" && r.header("host") == Some(b"plain.test".as_slice()))
|
||||||
|
);
|
||||||
|
edge.admin("POST", "/v1/abort", None).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn the_admin_socket_is_private() {
|
||||||
|
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: gen_host(&echo, "a"),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let meta = std::fs::metadata(edge.admin_socket()).unwrap();
|
||||||
|
assert!(meta.file_type().is_socket());
|
||||||
|
assert_eq!(meta.permissions().mode() & 0o007, 0, "no access for others");
|
||||||
|
// Unknown paths and bad bodies get typed errors, not a crash.
|
||||||
|
assert_eq!(edge.admin("GET", "/v1/nope", None).await.status, 404);
|
||||||
|
let r = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/trial",
|
||||||
|
Some(json!({ "confirm_within_secs": 2, "extra": 1 })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 400, "{}", r.text);
|
||||||
|
let r = edge
|
||||||
|
.admin(
|
||||||
|
"POST",
|
||||||
|
"/v1/trial",
|
||||||
|
Some(json!({ "confirm_within_secs": 0 })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 400, "{}", r.text);
|
||||||
|
assert_eq!(generation(&edge).await, "a");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! An injected secret reaches the upstream and never appears in a response, a log line, the
|
||||||
|
//! access log or the compiled config, even with the most verbose log level.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
|
||||||
|
use crate::common::{EdgeSpec, host_file, spawn, start};
|
||||||
|
use ianitor_testkit::client::{self, Req, Resp, WsOutcome};
|
||||||
|
use ianitor_testkit::upstream::{Echo, WsEcho, closed_port};
|
||||||
|
|
||||||
|
fn unique_secret() -> String {
|
||||||
|
let nanos = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_nanos();
|
||||||
|
format!("sekret-{}-{nanos:x}-tail", std::process::id())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_clean(what: &str, haystack: &[u8], secret: &str) {
|
||||||
|
let hay = String::from_utf8_lossy(haystack);
|
||||||
|
assert!(!hay.contains(secret), "secret leaked into {what}:\n{hay}");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_resp_clean(what: &str, r: &Resp, secret: &str) {
|
||||||
|
for (n, v) in &r.headers {
|
||||||
|
assert_clean(
|
||||||
|
&format!("{what}: response header {n}"),
|
||||||
|
v.as_bytes(),
|
||||||
|
secret,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_clean(&format!("{what}: response body"), &r.body, secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn injected_secret_never_appears_in_a_response_or_log() {
|
||||||
|
let secret = unique_secret();
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let ws = WsEcho::start().await;
|
||||||
|
let rule =
|
||||||
|
"[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"api_key\"\n";
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
site: "secrets = [\"api_key\"]\n",
|
||||||
|
hosts: vec![
|
||||||
|
host_file(
|
||||||
|
"app.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
host_file(
|
||||||
|
"down.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"http://127.0.0.1:{}\"]\naccess_log = \"truncated\"\n{rule}",
|
||||||
|
closed_port()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
host_file(
|
||||||
|
"ws.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}",
|
||||||
|
ws.url()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
// systemd credentials usually end with a newline; it is not part of the value.
|
||||||
|
secrets: vec![("api_key".into(), format!("{secret}\n").into_bytes())],
|
||||||
|
log_level: "trace",
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let roots = edge.roots();
|
||||||
|
let go = |sni: &'static str, req: Req| {
|
||||||
|
let roots = roots.clone();
|
||||||
|
let addr = edge.https;
|
||||||
|
async move { client::https(addr, sni, roots, &req).await.unwrap() }
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut responses = Vec::new();
|
||||||
|
responses.push((
|
||||||
|
"plain GET",
|
||||||
|
go("app.test", Req::get("app.test", "/hello?token=abc")).await,
|
||||||
|
));
|
||||||
|
responses.push((
|
||||||
|
"POST",
|
||||||
|
go(
|
||||||
|
"app.test",
|
||||||
|
Req::new("POST", "app.test", "/submit").body(b"payload"),
|
||||||
|
)
|
||||||
|
.await,
|
||||||
|
));
|
||||||
|
responses.push((
|
||||||
|
"client tries to set the header",
|
||||||
|
go(
|
||||||
|
"app.test",
|
||||||
|
Req::get("app.test", "/").header("x-api-key", "attacker"),
|
||||||
|
)
|
||||||
|
.await,
|
||||||
|
));
|
||||||
|
responses.push((
|
||||||
|
"upstream error status",
|
||||||
|
go("app.test", Req::get("app.test", "/status/500")).await,
|
||||||
|
));
|
||||||
|
responses.push((
|
||||||
|
"upstream reflects the secret in a header",
|
||||||
|
go("app.test", Req::get("app.test", "/reflect?h=x-api-key")).await,
|
||||||
|
));
|
||||||
|
responses.push((
|
||||||
|
"upstream down",
|
||||||
|
go("down.test", Req::get("down.test", "/")).await,
|
||||||
|
));
|
||||||
|
responses.push((
|
||||||
|
"unknown host",
|
||||||
|
go("app.test", Req::get("nope.test", "/")).await,
|
||||||
|
));
|
||||||
|
let plain = client::http(edge.http, &Req::get("app.test", "/x?y=1"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
responses.push(("plain HTTP redirect", plain));
|
||||||
|
|
||||||
|
for (what, r) in &responses {
|
||||||
|
assert_resp_clean(what, r, &secret);
|
||||||
|
}
|
||||||
|
assert_eq!(responses[0].1.status, 200);
|
||||||
|
assert_eq!(responses[4].1.status, 200);
|
||||||
|
assert!(
|
||||||
|
responses[4].1.header("x-reflected").is_none(),
|
||||||
|
"edge strips a response header carrying a secret"
|
||||||
|
);
|
||||||
|
assert_eq!(responses[5].1.status, 502);
|
||||||
|
|
||||||
|
match client::websocket(
|
||||||
|
edge.https,
|
||||||
|
"ws.test",
|
||||||
|
roots.clone(),
|
||||||
|
"ws.test",
|
||||||
|
"/socket",
|
||||||
|
&[],
|
||||||
|
"ping",
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
{
|
||||||
|
WsOutcome::Upgraded { status, echo, .. } => {
|
||||||
|
assert_eq!(status, 101);
|
||||||
|
assert_eq!(echo, "ping");
|
||||||
|
}
|
||||||
|
WsOutcome::Refused(r) => panic!("websocket refused: {r:?}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
// The secret did reach the upstream, without the trailing newline, replacing the client's value.
|
||||||
|
let seen = echo.proxied();
|
||||||
|
assert!(seen.len() >= 5, "{seen:?}");
|
||||||
|
for r in &seen {
|
||||||
|
assert_eq!(
|
||||||
|
r.header("x-api-key"),
|
||||||
|
Some(secret.as_bytes()),
|
||||||
|
"upstream request {}",
|
||||||
|
r.path
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Give the access log a moment to flush, then check every output channel.
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
||||||
|
let access = edge.access_log();
|
||||||
|
assert!(
|
||||||
|
access.lines().count() >= 7,
|
||||||
|
"access log has the requests:\n{access}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
access.contains("\"127.0.0.0\""),
|
||||||
|
"IPv4 truncated to /24:\n{access}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!access.contains("127.0.0.1"),
|
||||||
|
"full client IP must not be logged:\n{access}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!access.contains("token=abc"),
|
||||||
|
"query strings are not logged:\n{access}"
|
||||||
|
);
|
||||||
|
let stderr = edge.stderr();
|
||||||
|
assert!(
|
||||||
|
stderr.len() > 100,
|
||||||
|
"trace logging produced output:\n{stderr}"
|
||||||
|
);
|
||||||
|
assert_clean("stderr (trace level)", stderr.as_bytes(), &secret);
|
||||||
|
assert_clean("access log", access.as_bytes(), &secret);
|
||||||
|
assert_clean("compiled edge config", edge.config_text.as_bytes(), &secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn missing_secret_stops_startup_without_leaking_others() {
|
||||||
|
let secret = unique_secret();
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let mut edge = spawn(EdgeSpec {
|
||||||
|
site: "secrets = [\"present\", \"absent\"]\n",
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"app.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"present\"\n\
|
||||||
|
[[request_headers]]\naction = \"set\"\nname = \"X-B\"\nsecret = \"absent\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
)],
|
||||||
|
secrets: vec![("present".into(), secret.clone().into_bytes())],
|
||||||
|
log_level: "trace",
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let status = wait_exit(&mut edge);
|
||||||
|
assert!(!status.success(), "edge must refuse to start");
|
||||||
|
let err = edge.stderr();
|
||||||
|
assert!(err.contains("absent"), "names the missing secret:\n{err}");
|
||||||
|
assert_clean("stderr", err.as_bytes(), &secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn malformed_secret_is_rejected_without_echoing_it() {
|
||||||
|
let secret = unique_secret();
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let mut edge = spawn(EdgeSpec {
|
||||||
|
site: "secrets = [\"api_key\"]\n",
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"app.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
)],
|
||||||
|
// A newline inside the value would split the header: refused.
|
||||||
|
secrets: vec![(
|
||||||
|
"api_key".into(),
|
||||||
|
format!("{secret}\ninjected: yes\n").into_bytes(),
|
||||||
|
)],
|
||||||
|
log_level: "trace",
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let status = wait_exit(&mut edge);
|
||||||
|
assert!(
|
||||||
|
!status.success(),
|
||||||
|
"edge must refuse a secret that is not a valid header value"
|
||||||
|
);
|
||||||
|
assert_clean("stderr", edge.stderr().as_bytes(), &secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait_exit(edge: &mut crate::common::Edge) -> std::process::ExitStatus {
|
||||||
|
for _ in 0..200 {
|
||||||
|
if let Some(s) = edge.exited() {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
panic!("edge kept running:\n{}", edge.stderr());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,559 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Share links in edge (ROADMAP §6 phase 2, tests first): a valid link lets the visitor in on
|
||||||
|
//! its host and prefix only, without forward-auth; the token travels in the URL once and is
|
||||||
|
//! then a path-scoped cookie; it never reaches the upstream or a log; expired, altered,
|
||||||
|
//! wrong-host, wrong-path, stopped and password-less tokens are refused; wrong passwords are
|
||||||
|
//! throttled; no path trick escapes the prefix.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use crate::common::{Edge, EdgeSpec, SHARE_KEY, host_file, start};
|
||||||
|
use ianitor_core::share::{LinkSpec, ShareId, ShareKey, mint};
|
||||||
|
use ianitor_testkit::authelia::MockAuthelia;
|
||||||
|
use ianitor_testkit::client::{self, Req, Resp};
|
||||||
|
use ianitor_testkit::more::https_raw;
|
||||||
|
use ianitor_testkit::upstream::Echo;
|
||||||
|
|
||||||
|
const HOST: &str = "share.test";
|
||||||
|
|
||||||
|
fn now() -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_secs()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key() -> ShareKey {
|
||||||
|
ShareKey::new(SHARE_KEY).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn link(host: &str, id: u8, prefix: &str, expires_at: u64, password: Option<&str>) -> String {
|
||||||
|
mint(
|
||||||
|
&key(),
|
||||||
|
host,
|
||||||
|
&LinkSpec {
|
||||||
|
id: ShareId([id; 16]),
|
||||||
|
epoch: 0,
|
||||||
|
expires_at,
|
||||||
|
prefix,
|
||||||
|
password,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Env {
|
||||||
|
edge: Edge,
|
||||||
|
echo: Echo,
|
||||||
|
auth: MockAuthelia,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn env() -> Env {
|
||||||
|
let auth = MockAuthelia::start().await;
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url());
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
site: &site,
|
||||||
|
hosts: vec![
|
||||||
|
host_file(
|
||||||
|
HOST,
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = true\naccess_log = \"truncated\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
host_file(
|
||||||
|
"closed.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = false\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
log_level: "debug",
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
Env { edge, echo, auth }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Env {
|
||||||
|
async fn get(&self, host: &str, path: &str, cookie: Option<&str>) -> Resp {
|
||||||
|
let mut req = Req::get(host, path);
|
||||||
|
if let Some(c) = cookie {
|
||||||
|
req = req.header("cookie", c);
|
||||||
|
}
|
||||||
|
client::https(self.edge.https, host, self.edge.roots(), &req)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn post_password(&self, token: &str, password: &str) -> Resp {
|
||||||
|
let body = format!("t={}&password={}", urlencode(token), urlencode(password));
|
||||||
|
let req = Req::new("POST", HOST, "/.well-known/ianitor/share")
|
||||||
|
.header("content-type", "application/x-www-form-urlencoded")
|
||||||
|
.body(body.as_bytes());
|
||||||
|
client::https(self.edge.https, HOST, self.edge.roots(), &req)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Requests the upstream saw (health checks excluded).
|
||||||
|
fn upstream_paths(&self) -> Vec<String> {
|
||||||
|
self.echo.proxied().iter().map(|r| r.path.clone()).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn urlencode(s: &str) -> String {
|
||||||
|
s.bytes()
|
||||||
|
.map(|b| {
|
||||||
|
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
|
||||||
|
(b as char).to_string()
|
||||||
|
} else {
|
||||||
|
format!("%{b:02X}")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `name=value` part of the share cookie a response sets.
|
||||||
|
fn share_cookie(r: &Resp) -> String {
|
||||||
|
let sc = r
|
||||||
|
.header_all("set-cookie")
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.starts_with("__Secure-ianitor-share="))
|
||||||
|
.unwrap_or_else(|| panic!("no share cookie in {:?}", r.headers));
|
||||||
|
sc.split(';').next().unwrap().to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_visitor_page(r: &Resp, status: u16, heading: &str) {
|
||||||
|
assert_eq!(r.status, status, "{}", r.text());
|
||||||
|
assert!(r.text().contains(heading), "{heading}: {}", r.text());
|
||||||
|
assert_eq!(r.header("cache-control"), Some("no-store"));
|
||||||
|
assert_eq!(r.header("referrer-policy"), Some("no-referrer"));
|
||||||
|
assert!(
|
||||||
|
r.header("content-security-policy")
|
||||||
|
.is_some_and(|c| c.contains("default-src 'none'"))
|
||||||
|
);
|
||||||
|
assert!(r.header("content-type").unwrap().starts_with("text/html"));
|
||||||
|
assert!(!r.text().contains("<script"), "no JavaScript");
|
||||||
|
assert!(
|
||||||
|
!r.text().contains("http://") && !r.text().contains("https://"),
|
||||||
|
"no external requests"
|
||||||
|
);
|
||||||
|
assert!(r.body.len() < 8 * 1024);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_valid_link_lets_the_visitor_in_without_forward_auth() {
|
||||||
|
let e = env().await;
|
||||||
|
let t = link(HOST, 1, "/albums", now() + 3600, None);
|
||||||
|
|
||||||
|
let r = e
|
||||||
|
.get(HOST, &format!("/albums/summer?x=1&share={t}&y=2"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 303, "{}", r.text());
|
||||||
|
assert_eq!(r.header("location"), Some("/albums/summer?x=1&y=2"));
|
||||||
|
assert_eq!(r.header("referrer-policy"), Some("no-referrer"));
|
||||||
|
let set = r
|
||||||
|
.header_all("set-cookie")
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.starts_with("__Secure-ianitor-share="))
|
||||||
|
.unwrap()
|
||||||
|
.to_owned();
|
||||||
|
for attr in [
|
||||||
|
"Path=/albums",
|
||||||
|
"HttpOnly",
|
||||||
|
"Secure",
|
||||||
|
"SameSite=Lax",
|
||||||
|
"Max-Age=",
|
||||||
|
] {
|
||||||
|
assert!(set.contains(attr), "{attr} missing in {set}");
|
||||||
|
}
|
||||||
|
assert!(!set.contains(&t), "the cookie is not the link token");
|
||||||
|
assert!(
|
||||||
|
e.upstream_paths().is_empty(),
|
||||||
|
"the token request never reached the upstream"
|
||||||
|
);
|
||||||
|
let auth_calls = e.auth.requests().len();
|
||||||
|
|
||||||
|
let cookie = share_cookie(&r);
|
||||||
|
let r = e
|
||||||
|
.get(
|
||||||
|
HOST,
|
||||||
|
"/albums/summer?x=1&y=2",
|
||||||
|
Some(&format!("{cookie}; other=1")),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text());
|
||||||
|
assert_eq!(
|
||||||
|
e.auth.requests().len(),
|
||||||
|
auth_calls,
|
||||||
|
"no forward-auth for a share visitor"
|
||||||
|
);
|
||||||
|
let seen = e.echo.proxied();
|
||||||
|
let last = seen.last().unwrap();
|
||||||
|
assert_eq!(last.path, "/albums/summer");
|
||||||
|
let cookie_sent = last
|
||||||
|
.header("cookie")
|
||||||
|
.map(|c| String::from_utf8_lossy(c).into_owned())
|
||||||
|
.unwrap_or_default();
|
||||||
|
assert!(
|
||||||
|
!cookie_sent.contains("ianitor-share"),
|
||||||
|
"share cookie stripped: {cookie_sent}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
cookie_sent.contains("other=1"),
|
||||||
|
"other cookies kept: {cookie_sent}"
|
||||||
|
);
|
||||||
|
assert!(last.header("referer").is_none());
|
||||||
|
|
||||||
|
// The prefix itself and deeper paths are covered.
|
||||||
|
assert_eq!(e.get(HOST, "/albums", Some(&cookie)).await.status, 200);
|
||||||
|
assert_eq!(
|
||||||
|
e.get(HOST, "/albums/a/b/c.jpg", Some(&cookie)).await.status,
|
||||||
|
200
|
||||||
|
);
|
||||||
|
|
||||||
|
// Neither the token nor the cookie appears in any log.
|
||||||
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||||
|
let logs = e.edge.all_output();
|
||||||
|
assert!(!logs.contains(&t[5..40]), "token in logs");
|
||||||
|
assert!(!logs.contains(&cookie[30..60]), "cookie in logs");
|
||||||
|
assert!(
|
||||||
|
!e.edge.access_log().contains("share="),
|
||||||
|
"query in access log"
|
||||||
|
);
|
||||||
|
for r in e.echo.requests() {
|
||||||
|
for (_, v) in &r.headers {
|
||||||
|
assert!(!String::from_utf8_lossy(v).contains(&t[5..40]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn bad_tokens_get_plain_english_pages() {
|
||||||
|
let e = env().await;
|
||||||
|
// Expired: the signature proves the date.
|
||||||
|
let t = link(HOST, 2, "/", now() - 10, None);
|
||||||
|
let r = e.get(HOST, &format!("/?share={t}"), None).await;
|
||||||
|
assert_visitor_page(&r, 410, "This link has expired");
|
||||||
|
// Another host's token, an altered token, a token made with another key.
|
||||||
|
let other = link("closed.test", 3, "/", now() + 3600, None);
|
||||||
|
let mut altered = link(HOST, 4, "/", now() + 3600, None);
|
||||||
|
let last = altered.pop().unwrap();
|
||||||
|
altered.push(if last == 'A' { 'B' } else { 'A' });
|
||||||
|
let foreign = mint(
|
||||||
|
&ShareKey::new(b"another-key-another-key-another-key-0000").unwrap(),
|
||||||
|
HOST,
|
||||||
|
&LinkSpec {
|
||||||
|
id: ShareId([5; 16]),
|
||||||
|
epoch: 0,
|
||||||
|
expires_at: now() + 3600,
|
||||||
|
prefix: "/",
|
||||||
|
password: None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
for bad in [other, altered, foreign, "ish1.garbage".to_owned()] {
|
||||||
|
let r = e.get(HOST, &format!("/?share={bad}"), None).await;
|
||||||
|
assert_visitor_page(&r, 403, "This link no longer works");
|
||||||
|
}
|
||||||
|
// Escaping: only the hostname and the date come from the request.
|
||||||
|
let r = e.get(HOST, "/?share=ish1.%3Cscript%3E", None).await;
|
||||||
|
assert!(!r.text().contains("<script>"));
|
||||||
|
assert!(e.upstream_paths().is_empty());
|
||||||
|
|
||||||
|
// A `share` parameter that is not ours is left alone (goes to the normal sign-in).
|
||||||
|
let r = e.get(HOST, "/?share=holiday", None).await;
|
||||||
|
assert_eq!(r.status, 302, "forward-auth portal redirect");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_link_outside_its_prefix_falls_back_to_sign_in_and_never_leaks() {
|
||||||
|
let e = env().await;
|
||||||
|
let t = link(HOST, 6, "/albums", now() + 3600, None);
|
||||||
|
let r = e.get(HOST, &format!("/private?share={t}"), None).await;
|
||||||
|
assert_eq!(r.status, 302, "normal sign-in: {}", r.text());
|
||||||
|
// Signed in, the request goes through, but the token is not passed on.
|
||||||
|
let r = e
|
||||||
|
.get(
|
||||||
|
HOST,
|
||||||
|
&format!("/private?a=1&share={t}"),
|
||||||
|
Some("authelia_session=good"),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap();
|
||||||
|
assert_eq!(body["query"], "a=1", "token stripped before the upstream");
|
||||||
|
|
||||||
|
// On a host without share links the token gives nothing.
|
||||||
|
let t2 = link("closed.test", 7, "/", now() + 3600, None);
|
||||||
|
let r = e.get("closed.test", &format!("/?share={t2}"), None).await;
|
||||||
|
assert_eq!(r.status, 302);
|
||||||
|
// ...and is not passed on to the auth server or the upstream either.
|
||||||
|
let r = e
|
||||||
|
.get(
|
||||||
|
"closed.test",
|
||||||
|
&format!("/x?b=2&share={t2}"),
|
||||||
|
Some("authelia_session=good"),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap();
|
||||||
|
assert_eq!(body["query"], "b=2");
|
||||||
|
for req in e.auth.requests() {
|
||||||
|
for (_, v) in &req.headers {
|
||||||
|
assert!(
|
||||||
|
!String::from_utf8_lossy(v).contains("ish1."),
|
||||||
|
"token sent to the auth server"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_password_link_asks_checks_and_throttles() {
|
||||||
|
let e = env().await;
|
||||||
|
let t = link(HOST, 8, "/docs", now() + 3600, Some("correct horse"));
|
||||||
|
|
||||||
|
let r = e.get(HOST, &format!("/docs/a?share={t}"), None).await;
|
||||||
|
assert_visitor_page(&r, 401, "This link is protected");
|
||||||
|
assert!(r.text().contains("share.test"));
|
||||||
|
assert!(r.text().contains("action=\"/.well-known/ianitor/share\""));
|
||||||
|
assert!(r.text().contains("name=\"password\""));
|
||||||
|
assert!(r.text().contains("The link works until"));
|
||||||
|
assert!(share_cookie_absent(&r));
|
||||||
|
|
||||||
|
let r = e.post_password(&t, "wrong password").await;
|
||||||
|
assert_visitor_page(&r, 401, "That password is not right");
|
||||||
|
assert!(share_cookie_absent(&r));
|
||||||
|
|
||||||
|
let r = e.post_password(&t, "correct horse").await;
|
||||||
|
assert_eq!(r.status, 303, "{}", r.text());
|
||||||
|
assert_eq!(r.header("location"), Some("/docs"));
|
||||||
|
let cookie = share_cookie(&r);
|
||||||
|
assert_eq!(e.get(HOST, "/docs/a", Some(&cookie)).await.status, 200);
|
||||||
|
|
||||||
|
// The cookie of a password link cannot be turned into a link that skips the password.
|
||||||
|
let v = cookie.split_once('=').unwrap().1.to_owned();
|
||||||
|
let r = e
|
||||||
|
.get(
|
||||||
|
HOST,
|
||||||
|
&format!("/docs?share={}", v.replacen("iss1.", "ish1.", 1)),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_ne!(r.status, 303);
|
||||||
|
|
||||||
|
// Five wrong tries a minute, then a pause (the right password too).
|
||||||
|
let t2 = link(HOST, 9, "/docs", now() + 3600, Some("correct horse"));
|
||||||
|
for _ in 0..5 {
|
||||||
|
assert_eq!(e.post_password(&t2, "nope nope").await.status, 401);
|
||||||
|
}
|
||||||
|
let r = e.post_password(&t2, "nope nope").await;
|
||||||
|
assert_visitor_page(&r, 429, "Too many tries");
|
||||||
|
let r = e.post_password(&t2, "correct horse").await;
|
||||||
|
assert_eq!(r.status, 429);
|
||||||
|
// Other links are not affected.
|
||||||
|
let t3 = link(HOST, 10, "/docs", now() + 3600, Some("correct horse"));
|
||||||
|
assert_eq!(e.post_password(&t3, "correct horse").await.status, 303);
|
||||||
|
// The password never reaches a log.
|
||||||
|
assert!(!e.edge.all_output().contains("correct horse"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn share_cookie_absent(r: &Resp) -> bool {
|
||||||
|
!r.header_all("set-cookie")
|
||||||
|
.iter()
|
||||||
|
.any(|c| c.starts_with("__Secure-ianitor-share="))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn no_path_trick_escapes_the_cookie_prefix() {
|
||||||
|
let e = env().await;
|
||||||
|
let t = link(HOST, 11, "/a", now() + 3600, None);
|
||||||
|
let r = e.get(HOST, &format!("/a?share={t}"), None).await;
|
||||||
|
let cookie = share_cookie(&r);
|
||||||
|
let before = e.upstream_paths().len();
|
||||||
|
for path in [
|
||||||
|
"/ab",
|
||||||
|
"/A",
|
||||||
|
"/A/x",
|
||||||
|
"/b",
|
||||||
|
"/a/../b",
|
||||||
|
"/a/%2e%2e/b",
|
||||||
|
"/a/%2E%2E/b",
|
||||||
|
"/a/%252e%252e/b",
|
||||||
|
"/a%2f..%2fb",
|
||||||
|
"/a//b",
|
||||||
|
"//a/b",
|
||||||
|
"/a/..;/b",
|
||||||
|
"/a/\\..\\b",
|
||||||
|
"/a\\..\\b",
|
||||||
|
] {
|
||||||
|
let raw = format!(
|
||||||
|
"GET {path} HTTP/1.1\r\nHost: {HOST}\r\nCookie: {cookie}\r\nConnection: close\r\n\r\n"
|
||||||
|
);
|
||||||
|
let r = https_raw(e.edge.https, HOST, e.edge.roots(), raw.as_bytes())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_ne!(r.status, 200, "{path} got through: {}", r.text());
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
e.upstream_paths().len(),
|
||||||
|
before,
|
||||||
|
"no escaped request reached the upstream: {:?}",
|
||||||
|
e.upstream_paths()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn stopped_links_and_stop_all_take_effect_at_once() {
|
||||||
|
let e = env().await;
|
||||||
|
let t = link(HOST, 12, "/", now() + 3600, None);
|
||||||
|
let keep = link(HOST, 13, "/", now() + 3600, None);
|
||||||
|
let cookie = share_cookie(&e.get(HOST, &format!("/?share={t}"), None).await);
|
||||||
|
let keep_cookie = share_cookie(&e.get(HOST, &format!("/?share={keep}"), None).await);
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
|
||||||
|
|
||||||
|
e.edge.write_revocations(0, &[ShareId([12; 16]).to_hex()]);
|
||||||
|
let r = e
|
||||||
|
.edge
|
||||||
|
.admin("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 200, "{}", r.text);
|
||||||
|
assert_eq!(
|
||||||
|
e.get(HOST, "/", Some(&cookie)).await.status,
|
||||||
|
302,
|
||||||
|
"back to sign-in"
|
||||||
|
);
|
||||||
|
let r = e.get(HOST, &format!("/?share={t}"), None).await;
|
||||||
|
assert_visitor_page(&r, 403, "This link no longer works");
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200);
|
||||||
|
|
||||||
|
// Stop all: a new epoch ends every older link.
|
||||||
|
e.edge.write_revocations(1, &[]);
|
||||||
|
e.edge
|
||||||
|
.admin("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302);
|
||||||
|
|
||||||
|
// The epoch never goes back: a lower one is refused and the old state kept, so a
|
||||||
|
// control that lost its records cannot revive stopped links.
|
||||||
|
let fresh = mint(
|
||||||
|
&key(),
|
||||||
|
HOST,
|
||||||
|
&LinkSpec {
|
||||||
|
id: ShareId([14; 16]),
|
||||||
|
epoch: 1,
|
||||||
|
expires_at: now() + 3600,
|
||||||
|
prefix: "/",
|
||||||
|
password: None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let fresh_cookie = share_cookie(&e.get(HOST, &format!("/?share={fresh}"), None).await);
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200);
|
||||||
|
e.edge.write_revocations(0, &[]);
|
||||||
|
let r = e
|
||||||
|
.edge
|
||||||
|
.admin("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
assert!(r.text.contains("epoch"), "{}", r.text);
|
||||||
|
assert_eq!(
|
||||||
|
e.get(HOST, "/", Some(&keep_cookie)).await.status,
|
||||||
|
302,
|
||||||
|
"still stopped"
|
||||||
|
);
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200);
|
||||||
|
|
||||||
|
// Without the admin call, edge notices a changed file within 5 s.
|
||||||
|
e.edge.write_revocations(1, &[ShareId([14; 16]).to_hex()]);
|
||||||
|
tokio::time::sleep(Duration::from_secs(6)).await;
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302);
|
||||||
|
// ...and a lower epoch written behind its back is refused there too.
|
||||||
|
e.edge.write_revocations(0, &[]);
|
||||||
|
tokio::time::sleep(Duration::from_secs(6)).await;
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302);
|
||||||
|
assert!(e.edge.stderr().contains("epoch"), "the refusal is logged");
|
||||||
|
|
||||||
|
// Edge remembers the highest epoch in its own state: after a restart a lower one
|
||||||
|
// (control's files rolled back) is still refused.
|
||||||
|
e.edge.write_revocations(1, &[]);
|
||||||
|
e.edge
|
||||||
|
.admin("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await;
|
||||||
|
let mut e = e;
|
||||||
|
e.edge.restart();
|
||||||
|
e.edge.write_revocations(0, &[]);
|
||||||
|
let r = e
|
||||||
|
.edge
|
||||||
|
.admin("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302);
|
||||||
|
|
||||||
|
// A broken file keeps the last good state; a missing one stops all share access.
|
||||||
|
e.edge.write_revocations(1, &[]);
|
||||||
|
e.edge
|
||||||
|
.admin("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200);
|
||||||
|
std::fs::write(e.edge.revocations_path(), "{ broken").unwrap();
|
||||||
|
let r = e
|
||||||
|
.edge
|
||||||
|
.admin("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422);
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200);
|
||||||
|
std::fs::remove_file(e.edge.revocations_path()).unwrap();
|
||||||
|
e.edge
|
||||||
|
.admin("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn an_unreadable_epoch_floor_refuses_share_links() {
|
||||||
|
let mut e = env().await;
|
||||||
|
let t = link(HOST, 15, "/", now() + 3600, None);
|
||||||
|
let cookie = share_cookie(&e.get(HOST, &format!("/?share={t}"), None).await);
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
|
||||||
|
std::fs::write(e.edge.dir.join("state/share-epoch-floor"), "garbage").unwrap();
|
||||||
|
e.edge.restart();
|
||||||
|
assert_eq!(
|
||||||
|
e.get(HOST, "/", Some(&cookie)).await.status,
|
||||||
|
302,
|
||||||
|
"fails closed"
|
||||||
|
);
|
||||||
|
let r = e
|
||||||
|
.edge
|
||||||
|
.admin("POST", "/v1/share-revocations/reload", None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
|
assert!(e.edge.stderr().contains("share-epoch-floor"));
|
||||||
|
// A missing floor is simply 0.
|
||||||
|
std::fs::remove_file(e.edge.dir.join("state/share-epoch-floor")).unwrap();
|
||||||
|
e.edge.restart();
|
||||||
|
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// 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 wrong-password throttle (QC fix round 1, M1): the id it keys on is unproven (anyone can
|
||||||
|
//! forge a token with any id), so it must not be possible to reset a real link's counter by
|
||||||
|
//! flooding it with made-up ids, and a full table refuses instead of forgetting.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
use std::net::IpAddr;
|
||||||
|
|
||||||
|
use ianitor_core::share::ShareId;
|
||||||
|
use ianitor_edge::share::Throttle;
|
||||||
|
|
||||||
|
fn junk(n: u32) -> ShareId {
|
||||||
|
let mut id = [0u8; 16];
|
||||||
|
id[..4].copy_from_slice(&n.to_be_bytes());
|
||||||
|
id[15] = 1;
|
||||||
|
ShareId(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn junk_ids_from_the_same_network_cannot_flush_a_link_counter() {
|
||||||
|
let t = Throttle::default();
|
||||||
|
let victim = ShareId([7; 16]);
|
||||||
|
let ip: IpAddr = "192.0.2.10".parse().unwrap();
|
||||||
|
for _ in 0..5 {
|
||||||
|
t.failed(victim, Some(ip));
|
||||||
|
}
|
||||||
|
assert!(!t.allowed(victim, Some(ip)), "locked after 5 failures");
|
||||||
|
for n in 0u32..10_000 {
|
||||||
|
t.failed(junk(n), Some(ip));
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
!t.allowed(victim, Some(ip)),
|
||||||
|
"10,000 junk failures reset the victim's counter"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_network_is_limited_across_all_links() {
|
||||||
|
let t = Throttle::default();
|
||||||
|
let ip: IpAddr = "192.0.2.10".parse().unwrap();
|
||||||
|
let neighbour: IpAddr = "192.0.2.77".parse().unwrap();
|
||||||
|
let elsewhere: IpAddr = "198.51.100.1".parse().unwrap();
|
||||||
|
let mut n = 0;
|
||||||
|
while t.allowed(junk(n), Some(ip)) {
|
||||||
|
t.failed(junk(n), Some(ip));
|
||||||
|
n += 1;
|
||||||
|
assert!(n < 1000, "no limit per network");
|
||||||
|
}
|
||||||
|
assert!(n <= 20, "{n} wrong passwords a minute from one network");
|
||||||
|
// The same /24 is limited for a link it never tried; other networks are not.
|
||||||
|
assert!(!t.allowed(ShareId([9; 16]), Some(neighbour)));
|
||||||
|
assert!(t.allowed(ShareId([9; 16]), Some(elsewhere)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_full_table_refuses_new_visitors_instead_of_forgetting_old_ones() {
|
||||||
|
let t = Throttle::default();
|
||||||
|
let victim = ShareId([7; 16]);
|
||||||
|
let ip: IpAddr = "192.0.2.10".parse().unwrap();
|
||||||
|
for _ in 0..5 {
|
||||||
|
t.failed(victim, Some(ip));
|
||||||
|
}
|
||||||
|
// Fill the table from many networks, one failure each.
|
||||||
|
for n in 0u32..20_000 {
|
||||||
|
let other = IpAddr::from([10, (n >> 16) as u8, (n >> 8) as u8, n as u8]);
|
||||||
|
t.failed(junk(n), Some(other));
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
!t.allowed(victim, Some(ip)),
|
||||||
|
"the victim's counter survived"
|
||||||
|
);
|
||||||
|
let newcomer = IpAddr::from([203, 0, 113, 5]);
|
||||||
|
assert!(
|
||||||
|
!t.allowed(ShareId([3; 16]), Some(newcomer)),
|
||||||
|
"full table: refuse, don't forget"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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/.
|
||||||
|
|
||||||
|
//! Upstream handling: name resolution at connect time, health checks that survive odd
|
||||||
|
//! answers, websocket refusal on every Upgrade token, absolute-form requests.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::common::{EdgeSpec, host_file, start};
|
||||||
|
use ianitor_testkit::client::{self, Req};
|
||||||
|
use ianitor_testkit::raw::{RawServer, Reply, response};
|
||||||
|
use ianitor_testkit::upstream::Echo;
|
||||||
|
|
||||||
|
/// QC M1: `localhost` may resolve to ::1 first while the service listens on 127.0.0.1 only.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn upstream_names_are_resolved_at_connect_time_trying_every_address() {
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: vec![
|
||||||
|
host_file(
|
||||||
|
"local.test",
|
||||||
|
&format!("upstreams = [\"http://localhost:{}\"]\n", echo.addr.port()),
|
||||||
|
),
|
||||||
|
host_file(
|
||||||
|
"gone.test",
|
||||||
|
"upstreams = [\"http://no-such-host.invalid:8080\"]\n",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"local.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("local.test", "/"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200, "{}", edge.stderr());
|
||||||
|
// An upstream that does not resolve is a 502 for that host, not a startup failure.
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"gone.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("gone.test", "/"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 502);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC B2a: a health endpoint that sends a 1xx must not kill health checking.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn health_checks_survive_informational_answers() {
|
||||||
|
let started = Instant::now();
|
||||||
|
let up = RawServer::start(move |req| {
|
||||||
|
if req.path == "/healthz" && started.elapsed() < Duration::from_secs(3) {
|
||||||
|
let mut b = b"HTTP/1.1 102 Processing\r\n\r\n".to_vec();
|
||||||
|
b.extend(response(200, "OK", &[], b"ok"));
|
||||||
|
Reply::Bytes(b)
|
||||||
|
} else {
|
||||||
|
Reply::Bytes(response(500, "Internal Server Error", &[], b"broken"))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"hc.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n",
|
||||||
|
up.url()
|
||||||
|
),
|
||||||
|
)],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
tokio::time::sleep(Duration::from_millis(5500)).await;
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"hc.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("hc.test", "/"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
r.status,
|
||||||
|
503,
|
||||||
|
"health checks kept running and marked the upstream down\n{}",
|
||||||
|
edge.stderr()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
up.requests()
|
||||||
|
.iter()
|
||||||
|
.filter(|r| r.path == "/healthz")
|
||||||
|
.count()
|
||||||
|
>= 4
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC m4: every Upgrade header and every comma-separated token counts.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn websocket_refusal_checks_every_upgrade_token() {
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"nows.test",
|
||||||
|
&format!("upstreams = [\"{}\"]\nwebsockets = false\n", echo.url()),
|
||||||
|
)],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let cases = [
|
||||||
|
Req::get("nows.test", "/")
|
||||||
|
.header("connection", "upgrade")
|
||||||
|
.header("upgrade", "h2c")
|
||||||
|
.header("upgrade", "websocket"),
|
||||||
|
Req::get("nows.test", "/")
|
||||||
|
.header("connection", "upgrade")
|
||||||
|
.header("upgrade", "websocket, h2c"),
|
||||||
|
Req::get("nows.test", "/")
|
||||||
|
.header("connection", "upgrade")
|
||||||
|
.header("upgrade", "h2c , WebSocket"),
|
||||||
|
];
|
||||||
|
for req in &cases {
|
||||||
|
let r = client::https(edge.https, "nows.test", edge.roots(), req)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 403, "{req:?}");
|
||||||
|
}
|
||||||
|
assert!(echo.proxied().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// QC nit: absolute-form request targets are answered, never dropped. Pingora refuses a target
|
||||||
|
/// whose authority differs from Host (400, on both listeners); a consistent one is routed and
|
||||||
|
/// sent upstream in origin form.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn absolute_form_requests_are_answered() {
|
||||||
|
let echo = Echo::start("app").await;
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"plain.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]
|
||||||
|
",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
)],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let r = client::http(edge.http, &Req::get("plain.test", "http://evil.test/x"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 400, "plain HTTP, Host differs from the target");
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"plain.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("plain.test", "https://evil.test/x"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 400, "HTTPS, Host differs from the target");
|
||||||
|
assert!(echo.proxied().is_empty());
|
||||||
|
|
||||||
|
let r = client::http(edge.http, &Req::get("plain.test", "http://plain.test/x?y"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 308);
|
||||||
|
assert_eq!(
|
||||||
|
r.header("location"),
|
||||||
|
Some(format!("https://plain.test:{}/x?y", edge.https.port()).as_str())
|
||||||
|
);
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"plain.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("plain.test", "https://plain.test/abs?q=1"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
assert!(r.text().contains("\"path\":\"/abs\""), "{}", r.text());
|
||||||
|
}
|
||||||
|
}
|
||||||
+90
-7
@@ -9,7 +9,7 @@ Legend: [S] sourced · [J] judgment · [M] decided by Mark.
|
|||||||
3. Own proxy on Pingora (Rust, Apache 2.0; HTTP/1, HTTP/2, gRPC, websockets; a library, not a binary). [M] [S blog.cloudflare.com/pingora-open-source]
|
3. Own proxy on Pingora (Rust, Apache 2.0; HTTP/1, HTTP/2, gRPC, websockets; a library, not a binary). [M] [S blog.cloudflare.com/pingora-open-source]
|
||||||
4. Caddy is the fallback: one config model compiled to the Pingora runtime and to Caddy JSON, kept honest by differential tests on every build. [M]
|
4. Caddy is the fallback: one config model compiled to the Pingora runtime and to Caddy JSON, kept honest by differential tests on every build. [M]
|
||||||
5. Web UI only, on the server behind Authelia. API tokens are saved by Mark in Custos; control stores only hashes. [M]
|
5. Web UI only, on the server behind Authelia. API tokens are saved by Mark in Custos; control stores only hashes. [M]
|
||||||
6. Routes live in a git repo (private: ianitor-routes), one TOML file per host, schema-validated. Every change is a commit, applied live without nixos-rebuild. Rebuild only for service-level changes (engine, ports, version). [M]
|
6. Routes live in a git repo (private: ianitor-routes), one TOML file per host, schema-validated. Every change is a commit, applied live without nixos-rebuild. Rebuild only for service-level changes (ports, version). The engine is switched at runtime by control (§3, §4); decided 2026-11-07, replacing "engine" in the rebuild list. [M]
|
||||||
7. Two processes: ianitor-edge (data plane) and ianitor-control (API + UI). Traffic keeps flowing if control crashes. [M]
|
7. Two processes: ianitor-edge (data plane) and ianitor-control (API + UI). Traffic keeps flowing if control crashes. [M]
|
||||||
8. Own small CA in crates/core using rcgen. No internal ACME server in v1. [M]
|
8. Own small CA in crates/core using rcgen. No internal ACME server in v1. [M]
|
||||||
9. One public MPL-2.0 monorepo on Gitea; read-only GitHub mirror for discovery. Mark's server deployment stays in his NixOS flake. [M]
|
9. One public MPL-2.0 monorepo on Gitea; read-only GitHub mirror for discovery. Mark's server deployment stays in his NixOS flake. [M]
|
||||||
@@ -37,8 +37,10 @@ Legend: [S] sourced · [J] judgment · [M] decided by Mark.
|
|||||||
- Apply: validate → compile → write edge config + Caddy JSON → reload edge → watch health checks 60 s →
|
- Apply: validate → compile → write edge config + Caddy JSON → reload edge → watch health checks 60 s →
|
||||||
on failure git-revert, reload, report "reverted" with the reason; otherwise "kept". Concurrent applies are serialised.
|
on failure git-revert, reload, report "reverted" with the reason; otherwise "kept". Concurrent applies are serialised.
|
||||||
Undo = revert the last kept commit through the same path. Restore = apply an older tree as a new commit. Push to Gitea after a kept apply.
|
Undo = revert the last kept commit through the same path. Restore = apply an older tree as a new commit. Push to Gitea after a kept apply.
|
||||||
- Share links: HMAC token bound to host + path prefix + expiry (+ optional password hash), validated statelessly by edge;
|
- Share links: HMAC token bound to host + path prefix + expiry (+ optional password, mixed into the MAC; no hash in the token,
|
||||||
key from systemd credentials; revocation by key rotation or a small deny list.
|
so it cannot be guessed offline; edge rate-limits tries), validated statelessly by edge; key from systemd credentials;
|
||||||
|
revocation by key rotation, an epoch ("stop all") or a small deny list kept in a file outside git that control writes and edge
|
||||||
|
re-reads at once, so a Stop never waits for an apply; neither the epoch nor the list ever goes backwards. [M 2026-11-07]
|
||||||
- API: REST + JSON on loopback, OpenAPI generated from code.
|
- API: REST + JSON on loopback, OpenAPI generated from code.
|
||||||
- CA: root created offline, ~10 years, pathLenConstraint ≥ 1, never on the server. Intermediate ~1 year, key encrypted on the server,
|
- CA: root created offline, ~10 years, pathLenConstraint ≥ 1, never on the server. Intermediate ~1 year, key encrypted on the server,
|
||||||
password via systemd credentials. Leaf and device mTLS certs issued by control (lifetimes decided and justified in phase 3).
|
password via systemd credentials. Leaf and device mTLS certs issued by control (lifetimes decided and justified in phase 3).
|
||||||
@@ -61,6 +63,9 @@ Main screen: host list with health dots, engine chip, intermediate-expiry banner
|
|||||||
| Renew intermediate: banner Renew (approve in Custos) | 1 |
|
| Renew intermediate: banner Renew (approve in Custos) | 1 |
|
||||||
| API token: ⚙ → API → New token | 3 |
|
| API token: ⚙ → API → New token | 3 |
|
||||||
|
|
||||||
|
Accepted exceptions [M 2026-11-07]: copying a new API token and installing a device certificate may take a 4th click
|
||||||
|
(deliberate secret-handling steps).
|
||||||
|
|
||||||
## 5. Test layers (all run in an Artifex pipeline by phase 4)
|
## 5. Test layers (all run in an Artifex pipeline by phase 4)
|
||||||
1. Differential: the same request corpus against Ianitor and Caddy; status, selected headers and body compared.
|
1. Differential: the same request corpus against Ianitor and Caddy; status, selected headers and body compared.
|
||||||
2. Protocol conformance: h2spec, testssl.sh.
|
2. Protocol conformance: h2spec, testssl.sh.
|
||||||
@@ -85,6 +90,8 @@ on the last good config; share token rejected when expired, wrong path, wrong ho
|
|||||||
requests without a valid token rejected and tokens never logged; concurrent applies serialised.
|
requests without a valid token rejected and tokens never logged; concurrent applies serialised.
|
||||||
Done: add host, undo, restore and share link work end to end via the API on loopback; curl examples in docs/api.md;
|
Done: add host, undo, restore and share link work end to end via the API on loopback; curl examples in docs/api.md;
|
||||||
diff suite green after every apply.
|
diff suite green after every apply.
|
||||||
|
Also includes the UI API contract (docs/ui-api.md: overview, error codes, idempotency, health classes, watch probes,
|
||||||
|
history grouping, restore previews), accepted by Mark 2026-11-07.
|
||||||
|
|
||||||
### Phase 3 — Web UI, PKI, NixOS
|
### Phase 3 — Web UI, PKI, NixOS
|
||||||
Goal: the UI from section 4, the CA flows, the NixOS module with VM tests; Ianitor runs beside Caddy on two low-risk hosts.
|
Goal: the UI from section 4, the CA flows, the NixOS module with VM tests; Ianitor runs beside Caddy on two low-risk hosts.
|
||||||
@@ -107,20 +114,96 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit
|
|||||||
|
|
||||||
## 8. Open points (resolve at the start of the phase that needs them; record the answer here)
|
## 8. Open points (resolve at the start of the phase that needs them; record the answer here)
|
||||||
1. Pingora TLS backend: rustls vs BoringSSL/OpenSSL — maturity and NixOS packaging. (phase 1)
|
1. Pingora TLS backend: rustls vs BoringSSL/OpenSSL — maturity and NixOS packaging. (phase 1)
|
||||||
|
**Answer: rustls (ring), pingora 0.9.1 feature `rustls`.** Pure Rust, so no system TLS library, Perl, Go or clang in the Nix build. `TlsSettings::set_cert_resolver` gives SNI selection and lets ACME renewals swap certificates live; tested in crates/edge. Risk: the Pingora README labels it "rustls(experimental)", and the cert callback API is not available on rustls. Mitigation: the diff suite now, then testssl.sh/h2spec in phase 4. Fallback: the `openssl` feature, a change local to crates/edge/src/lib.rs and tls.rs. [S github.com/cloudflare/pingora README; pingora-core 0.9.1 src/listeners/tls/rustls] [J]
|
||||||
2. Rust ACME crate for Let's Encrypt — maintenance status; pick and justify. (phase 1)
|
2. Rust ACME crate for Let's Encrypt — maintenance status; pick and justify. (phase 1)
|
||||||
|
**Answer: instant-acme 0.8.5** (djc/instant-acme; release 2026-02-24, ~1.5 M recent downloads). It is a plain RFC 8555 client with rustls/ring and rcgen, and edge keeps control of HTTP-01, storage and renewal. rustls-acme and tokio-rustls-acme (also maintained) own the TLS acceptor, which conflicts with Pingora's listener. acme2 (last release 2022) and acme-lib (2024) are stale. Verified end to end against Pebble 2.6 only, not against LE staging. [S crates.io API 2026-11-07] [J]
|
||||||
3. Does Pingora build on Windows? If not, develop in WSL2 and note it in CLAUDE.md. (phase 1)
|
3. Does Pingora build on Windows? If not, develop in WSL2 and note it in CLAUDE.md. (phase 1)
|
||||||
|
**Answer: it compiles and the unit tests run on Windows (MSVC, Rust 1.99), but the README calls Windows support "preliminary by community's best effort only".** Unix-only parts include graceful upgrade, the in-process runner and the integration tests. Caddy and Pebble are not on this Windows box. So the edge integration tests, the diff suite and the ACME test run in WSL2 Debian, as noted in CLAUDE.md. One gotcha: libz-ng-sys's CMake build fails under a very deep CARGO_TARGET_DIR (MSBuild path length). [S github.com/cloudflare/pingora README; local builds 2026-11-07]
|
||||||
4. Pingora graceful reload behaviour under load. (phase 2)
|
4. Pingora graceful reload behaviour under load. (phase 2)
|
||||||
|
**Answer: no Pingora graceful upgrade for config changes; edge swaps its config in process.** A reload builds a complete new runtime from the config file (secrets, certificates, share-link key) and installs it with one atomic pointer swap (`arc-swap`); listeners, TLS sessions and keep-alive connections are untouched, each request keeps the runtime it started with, and the next request on the same connection uses the new one. A config that fails to build is refused and the old one keeps serving; listen addresses change only with a restart. Control triggers it through edge's admin Unix socket (mode 0660, never a TCP port) as a *trial* that edge reverts by itself unless control confirms it in time, so a control crash mid-apply cannot strand edge on an unverified config. Pingora's graceful upgrade (new process takes the listening sockets, old one drains for the grace period) stays for binary upgrades only: it needs a second process and fd passing, and idle keep-alive connections on the old process are closed after the drain, which clients see as a reset on their next request; it was not measured. [J]
|
||||||
|
Measured (`crates/edge/tests/reload.rs`, debug build, WSL2 Debian, 16 cores, one local upstream; alternating two configs that differ in a response header, `POST /v1/reload` every 100 ms, each client one TLS keep-alive connection sending requests back to back):
|
||||||
|
|
||||||
|
| Clients | Duration | Reloads | Requests | Errors | Connection resets | Connections that saw both configs | p50 / p99 / max latency |
|
||||||
|
|--:|--:|--:|--:|--:|--:|--:|:--|
|
||||||
|
| 32 | 10 s | 98 | 30,198 | 0 | 0 | 32/32 | 10.5 / 17.2 / 132 ms |
|
||||||
|
| 64 | 30 s | 294 | 95,229 | 0 | 0 | 64/64 | 20.0 / 31.9 / 190 ms |
|
||||||
|
| 128 | 30 s | 292 | 87,796 | 0 | 0 | 128/128 | 43.1 / 69.1 / 215 ms |
|
||||||
|
|
||||||
|
Reproduce: `IANITOR_RELOAD_CLIENTS=64 IANITOR_RELOAD_SECS=30 cargo test -p ianitor-edge --test reload -- --exact unix::reload_under_load_drops_nothing --nocapture`. Not measured: a release build, HTTP/2 clients, long-lived websockets across reloads (they keep the runtime they started with until they close), and Pingora graceful upgrade for comparison. [S local runs 2026-11-07]
|
||||||
5. Authelia forward-auth endpoint and headers to mirror exactly. (phase 1)
|
5. Authelia forward-auth endpoint and headers to mirror exactly. (phase 1)
|
||||||
|
**Answer: `GET /api/authz/forward-auth` (ForwardAuth implementation; legacy `/api/verify` not used).** Edge sends X-Forwarded-Method, -Proto, -Host, -URI (required) and X-Forwarded-For, and always sets them itself. It also forwards the client's headers (Cookie, Authorization) without hop-by-hop headers or body. A 2xx answer copies Remote-User, Remote-Groups, Remote-Email and Remote-Name onto the request (client copies removed). Any other answer (302 portal, 401 + WWW-Authenticate, 403) goes back to the client verbatim. An unreachable, silent (10 s deadline), oversized (>1 MiB), broken or `101` auth answer fails closed with 502; 1xx heads are skipped. Client-sent Remote-* headers are always stripped on forward-auth hosts, whatever copy_headers says. This mirrors `caddy adapt` output for Authelia's documented `forward_auth` snippet; tested against a mock, not a real Authelia. [S authelia.com/reference/guides/proxy-authorization, authelia.com/integration/proxies/caddy]
|
||||||
6. Custos CSR-signing operation with match-code approval. (phase 3)
|
6. Custos CSR-signing operation with match-code approval. (phase 3)
|
||||||
7. Red Panda Network donation route for a non-US individual and the receipt they issue. (phase 4, Mark)
|
7. Red Panda Network donation route for a non-US individual and the receipt they issue. (phase 4, Mark)
|
||||||
|
|
||||||
## 9. Status
|
## 9. Status
|
||||||
| Phase | State | Notes |
|
| Phase | State | Notes |
|
||||||
|:--|:--|:--|
|
|:--|:--|:--|
|
||||||
| 1 Core and engine | Not started | |
|
| 1 Core and engine | Done | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. The Let's Encrypt staging check moved to phase 3 (Mark, 2026-11-07). |
|
||||||
| 2 Control plane | Not started | |
|
| 2 Control plane | Done | Merged to main 2026-11-07 (PR 3): routes repo, journaled apply with trial/watch/revert, undo, restore, share links, API tokens, REST API + OpenAPI, `--dev`. Four QC rounds; every finding fixed or listed in Handover. Real Gitea, systemd credentials and Authelia not exercised. |
|
||||||
| 3 Web UI, PKI, NixOS | Not started | |
|
| 3 Web UI, PKI, NixOS | Not started | UI design drafted: claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u ("murex" palette on the Domi system, approved). Carries the Let's Encrypt staging check, on the first low-risk host beside Caddy. |
|
||||||
| 4 Hardening and release | Not started | |
|
| 4 Hardening and release | Not started | Known gaps carried here: see Handover. |
|
||||||
|
|
||||||
## 10. Handover
|
## 10. Handover
|
||||||
(Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.)
|
(Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.)
|
||||||
|
|
||||||
|
**2026-11-07: Phase 2, control plane.**
|
||||||
|
- **Changed:**
|
||||||
|
- Phase 2 on branch control/phase-2: crates/control (routes repo through the `git` binary, journaled apply with edge trial reloads, 60 s watch and revert, undo/redo, restore, push with retry, share links, API tokens, REST API with OpenAPI, `--dev`), edge in-process reload over an admin Unix socket, share-link checks and visitor pages in edge, share tokens and the exact `hosts/<hostname>.toml` loader in core.
|
||||||
|
- docs/api.md (curl examples, run end to end against `--dev`) and docs/ui-api.md (the designer's contract for phase 3, with the deviations listed at its end).
|
||||||
|
- §8.4 answered with load numbers. Tests: core 86, edge 43, control 42, diff 3 (diff after each of six applies: 0 new differences), testkit 1; hook self-test 55.
|
||||||
|
- Four QC rounds. Fixed along the way: password-throttle flush, CLI revoke lost to a server write, a pause lost on a full disk (three variants), revocation epoch rollback, Unicode and encoded `..` escapes in share paths, credentials echoed in errors, a port race in the test harness.
|
||||||
|
- **Deployed:** nothing. The server is unchanged and no nixos-rebuild is needed.
|
||||||
|
- **Not verified:**
|
||||||
|
- Push to the real Gitea over HTTPS (askpass) — a local bare repo stood in.
|
||||||
|
- systemd LoadCredential (a credentials-dir override stood in); a real Authelia (mock only).
|
||||||
|
- A release build, HTTP/2 clients and websockets across reloads; Pingora graceful upgrade (kept for binary upgrades only, not measured).
|
||||||
|
- A lost confirm answer from edge is tested only indirectly (edge stopped during the watch, not a late answer).
|
||||||
|
- Everything from the phase 1 list below that is still open.
|
||||||
|
- **Known gaps for later phases:**
|
||||||
|
- Share links work only on Pingora; under the Caddy fallback a visitor gets the normal sign-in (G7, phase 3).
|
||||||
|
- The "site not reachable" visitor page is not built: it needs a matching Caddy `handle_errors` to keep the diff suite equal.
|
||||||
|
- The crash and write-failure test hooks (`IANITOR_TEST_CRASH_AT`, `IANITOR_TEST_FAIL_WRITE`) are in the release binary, gated only by environment; move them behind a default feature that the Nix release build turns off. (phase 3)
|
||||||
|
- Control trusts only API tokens; forwarded `Remote-User` headers get 401 until the UI sign-in is designed (G14, phase 3).
|
||||||
|
- Edge config is version 2; a phase-1 edge refuses it.
|
||||||
|
- Workspace `rust-version` is now 1.89 (`File::lock`).
|
||||||
|
- One open flake: in one full run `apply_sequence` timed out waiting for Caddy on the chunked-body case (Ianitor answered 200). The diff suite alone passed 5/5 afterwards; cause not found.
|
||||||
|
- **Decided by Mark (2026-11-07):**
|
||||||
|
- (a) Let's Encrypt staging moves to phase 3, run on the first low-risk host beside Caddy.
|
||||||
|
- (b) The engine is switched at runtime by control (§3, §4); §1.6 corrected.
|
||||||
|
- (c) The 4th click for copying an API token and for installing a device certificate is accepted (§4).
|
||||||
|
- (d) The murex palette is approved; CLAUDE.md now says "dark Domi theme, murex palette".
|
||||||
|
- (f) The share-link deny list stays a separate file outside git (§3 updated).
|
||||||
|
- (g) §3 now describes the password as mixed into the MAC, with no hash in the token.
|
||||||
|
- (h) Phase 2's growth to the UI API contract is accepted (§6 Phase 2 note).
|
||||||
|
- **Still open:**
|
||||||
|
- The phase 1 click note also listed "share link on a host with links off" as needing a 4th click; not yet decided.
|
||||||
|
- (e) Delete the stray build folder F:\pwt, and the merged remote branches docs/bootstrap, core/phase-1 and control/phase-2.
|
||||||
|
- **Next step:** Phase 3, starting with §8.6 (Custos CSR signing) and the Let's Encrypt staging check.
|
||||||
|
|
||||||
|
**2026-11-07: Phase 1, design draft** (kept for its open items).
|
||||||
|
- **Changed:**
|
||||||
|
- Phase 1 on branch core/phase-1: workspace, `.githooks/pre-commit`, crates/core (schema and both compilers), crates/edge (Pingora with rustls), tests/diff (60 cases against Caddy 2.11.7), tests/support.
|
||||||
|
- Reviewed by a separate QC pass, two rounds; every finding fixed or listed below.
|
||||||
|
- §8 answers 1, 2, 3 and 5 recorded.
|
||||||
|
- **Deployed:** nothing. The server is unchanged and no nixos-rebuild is needed.
|
||||||
|
- **Not verified:**
|
||||||
|
- Let's Encrypt staging; ACME renewal; Caddy's ACME config.
|
||||||
|
- A real Authelia (mock only).
|
||||||
|
- HTTPS upstreams against the system roots.
|
||||||
|
- HTTP/2 client paths; a DNS change while edge runs.
|
||||||
|
- The hook on bash 3.2 (it refuses to run there).
|
||||||
|
- **Known gaps for later phases:**
|
||||||
|
- Slowloris: the header read has no overall deadline; Caddy closes the connection at 60 s, edge keeps it past 90 s. (phase 4)
|
||||||
|
- Timed-out DNS lookups keep a blocking-pool thread busy until glibc gives up. (phase 4)
|
||||||
|
- Divergences KD-4 to KD-10 compare status only.
|
||||||
|
- The plain-HTTP listener answers only the first of pipelined requests.
|
||||||
|
- The `<hostname>.toml` check looks at the base name only. (phase 2 loader)
|
||||||
|
- On Windows the Linux-only test targets show "1 passed" (a skip test).
|
||||||
|
- CLAUDE.md lists packages/ui, tests/fuzz, deploy/nixos, the flake and deploy/test-access.sh, which do not exist yet. (phase 3/4)
|
||||||
|
- **Needs Mark:**
|
||||||
|
- (a) Let's Encrypt staging: defer or give a domain.
|
||||||
|
- (b) §1.6 says an engine change needs a rebuild, but §3 and §4 let control switch engines at runtime. Which one holds?
|
||||||
|
- (c) §4 click counts: share link with links off, device-cert install and saving an API token each need a 4th click.
|
||||||
|
- (d) Approve the "murex" palette, and whether CLAUDE.md's "dark Domi theme" wording should change.
|
||||||
|
- (e) Delete the stray build folder F:\pwt.
|
||||||
|
- **Next step:** Phase 2, control plane. Resolve §8.4 (graceful reload under load) first.
|
||||||
|
|||||||
+251
@@ -0,0 +1,251 @@
|
|||||||
|
# Ianitor control API
|
||||||
|
|
||||||
|
`ianitor-control` serves a REST + JSON API on loopback only (`127.0.0.1:7878` by default),
|
||||||
|
under `/api/v1`. The OpenAPI document is generated from the code: `GET /api/v1/openapi.json`,
|
||||||
|
or `ianitor-control openapi` without a running server. The web UI's contract is
|
||||||
|
[docs/ui-api.md](ui-api.md); its last section lists where this API differs.
|
||||||
|
|
||||||
|
Everything below was run end to end on loopback against `--dev` with a real edge
|
||||||
|
(2026-11-07, WSL2 Debian); the outputs are trimmed with `jq`, never edited.
|
||||||
|
|
||||||
|
## Ground rules
|
||||||
|
|
||||||
|
- **Token.** Every call needs `Authorization: Bearer <API token>`. Nothing else identifies a
|
||||||
|
caller (no `Remote-User`). Without a valid token: `401` with `token.missing`,
|
||||||
|
`token.unknown`, `token.expired` or `token.revoked`. 120 calls a minute per token.
|
||||||
|
- **Host header.** Only `127.0.0.1:<port>`, `localhost:<port>`, `[::1]:<port>` and the
|
||||||
|
configured `allowed_hosts` are answered (DNS rebinding). A browser write (`Origin` or
|
||||||
|
`Sec-Fetch-Site` present) also needs `X-Ianitor-UI: 1` (CSRF).
|
||||||
|
- **Bodies** are JSON, at most 64 KiB, with no unknown fields. Errors about the request
|
||||||
|
itself (bad JSON, a wrong type, an odd field name, a path that is no hostname) never repeat
|
||||||
|
what you sent. Errors about a host can repeat its values (hostname, upstream, header name)
|
||||||
|
in `params` and `detail`, but never a URL's user name and password (shown as `…@`), a secret
|
||||||
|
value or a token.
|
||||||
|
- **Errors** have one shape; `code` is stable, `message` is plain English, `field` points at
|
||||||
|
the form field, `params` holds the values in the message, `detail` is the technical text:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "error": { "code": "host.hostname.uppercase", "message": "Use lowercase letters only: wiki.dev.test.",
|
||||||
|
"field": "hostname", "params": { "hostname": "Wiki.dev.test", "suggestion": "wiki.dev.test" },
|
||||||
|
"retry_after_s": null, "detail": "hosts/Wiki.dev.test.toml: `Wiki.dev.test` is not a valid hostname: it must be lowercase" },
|
||||||
|
"errors": [ ... one per field problem ... ], "request_id": "9c1f…", "server_time": "2026-11-07T17:19:40Z" }
|
||||||
|
```
|
||||||
|
- **`server_time`** is in every JSON object answer. Times are RFC 3339 UTC.
|
||||||
|
- **Changes are applies.** Adding, changing, removing a host, Undo and Restore answer
|
||||||
|
`202 {"apply": {...}}` at once; poll `GET /applies/{id}` (every second) until `state` is
|
||||||
|
`kept`, `reverted`, `failed` or `needs_attention`. Applies run one at a time, in order;
|
||||||
|
the others are `queued`.
|
||||||
|
- **`Idempotency-Key`** on a write: a retry with the same key gets the same apply back. While
|
||||||
|
the first request with a key is still being handled, a retry gets `409 request.in_progress`
|
||||||
|
(retry after 1 s). Keys are held in memory for 24 h (at most 2,000; then `429`).
|
||||||
|
- **`base_rev`** (from `GET /hosts/{h}` or the overview's `rev`): the change is refused with
|
||||||
|
`409 change.conflict` only if the same host file changed since.
|
||||||
|
|
||||||
|
## Start
|
||||||
|
|
||||||
|
Development, everything temporary on 127.0.0.1 (removed on Ctrl-C):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build -p ianitor-edge -p ianitor-control # so --dev finds ianitor-edge next to it
|
||||||
|
cargo run -p ianitor-control -- --dev
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Ianitor control (dev) on http://127.0.0.1:7878/api/v1
|
||||||
|
Routes repository: /tmp/ianitor-dev-1523/routes.git
|
||||||
|
Dev proxy: …/ianitor-edge on https://127.0.0.1:18443 (HTTP 18080). tls = "domi" works for app.dev.test, wiki.dev.test, photos.dev.test; CA: /tmp/ianitor-dev-1523/certs/dev-ca.crt
|
||||||
|
API token (shown once): ian_06484a2c0a6ec73b_vceenNC…
|
||||||
|
Press Ctrl-C to stop and remove /tmp/ianitor-dev-1523
|
||||||
|
```
|
||||||
|
|
||||||
|
Without `ianitor-edge` (or with `--edge-bin` pointing nowhere) applies are only validated,
|
||||||
|
compiled and written. In dev mode the health watch lasts 10 s (`--watch-secs`); in
|
||||||
|
production 60 s.
|
||||||
|
|
||||||
|
Production: the first token comes from the CLI on the server, never over the network:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ianitor-control token create --name mark-laptop --config /etc/ianitor/control.toml
|
||||||
|
```
|
||||||
|
|
||||||
|
The examples use:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
TOKEN=ian_… # from the line above
|
||||||
|
API=http://127.0.0.1:7878/api/v1
|
||||||
|
H="Authorization: Bearer $TOKEN"
|
||||||
|
CA=/tmp/ianitor-dev-1523/certs/dev-ca.crt
|
||||||
|
visit() { curl -s -o /dev/null -w '%{http_code}\n' --cacert "$CA" --resolve "$1:18443:127.0.0.1" "${@:2}"; }
|
||||||
|
python3 -m http.server 3000 --bind 127.0.0.1 & # a test upstream
|
||||||
|
```
|
||||||
|
|
||||||
|
## Add a host
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s -H "$H" -H 'Content-Type: application/json' -H 'Idempotency-Key: add-app-1' \
|
||||||
|
-X POST "$API/hosts" -d '{"host": {"hostname": "app.dev.test",
|
||||||
|
"upstreams": ["http://127.0.0.1:3000"], "tls": "domi", "auth": "none",
|
||||||
|
"health_check": {"path": "/", "interval_secs": 5}}}' | jq '{state: .apply.state, id: .apply.id}'
|
||||||
|
```
|
||||||
|
```json
|
||||||
|
{ "state": "queued", "id": "ch_b720484831a9" }
|
||||||
|
```
|
||||||
|
```sh
|
||||||
|
curl -s -H "$H" "$API/applies/ch_b720484831a9" | jq '{state, summary, reason: .reason.message, steps: [.steps[] | "\(.key)=\(.state)"]}'
|
||||||
|
```
|
||||||
|
```json
|
||||||
|
{ "state": "kept", "summary": "Added app.dev.test",
|
||||||
|
"reason": "app.dev.test is live. Health checks passed for 10 s.",
|
||||||
|
"steps": ["validate=done", "compile=done", "write=done", "reload=done", "watch=done", "push=skipped"] }
|
||||||
|
```
|
||||||
|
```sh
|
||||||
|
visit app.dev.test https://app.dev.test:18443/ # 200
|
||||||
|
```
|
||||||
|
|
||||||
|
The same request with the same `Idempotency-Key` returns `ch_b720484831a9` again and changes
|
||||||
|
nothing. A host that fails its health check during the watch is reverted: `state:
|
||||||
|
"reverted"`, and `reason` says why, e.g. `"a.test was not changed. 127.0.0.1:41999 answered
|
||||||
|
with an error page on 3 of 3 checks. Ianitor undid the change."` The routes repository then
|
||||||
|
holds the change and its revert commit; edge and the files never left the last good config.
|
||||||
|
|
||||||
|
A form error comes back at once, field by field:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts" \
|
||||||
|
-d '{"host": {"hostname": "Wiki.dev.test", "upstreams": ["http://10.0.0.23"]}}' \
|
||||||
|
| jq '{code: .error.code, errors: [.errors[] | {code, field, message}]}'
|
||||||
|
```
|
||||||
|
```json
|
||||||
|
{ "code": "apply.failed.validation",
|
||||||
|
"errors": [{ "code": "host.hostname.uppercase", "field": "hostname", "message": "Use lowercase letters only: wiki.dev.test." }] }
|
||||||
|
```
|
||||||
|
|
||||||
|
`POST /hosts/validate?mode=create` checks a body without applying it; `PUT /hosts/{h}` with
|
||||||
|
`{"host": …, "base_rev": …}` changes a host; `PATCH /hosts/{h}` with `{"share_links": true}`
|
||||||
|
turns share links on; `DELETE /hosts/{h}` removes one.
|
||||||
|
|
||||||
|
## Undo
|
||||||
|
|
||||||
|
Undo always names what it will undo; the POST must name the same change, or it is refused
|
||||||
|
with `409 undo.target_moved`. Undo right after an Undo is a redo, and `effect` says so.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s -H "$H" "$API/undo" | jq '{available, target: .target.summary, effect}'
|
||||||
|
```
|
||||||
|
```json
|
||||||
|
{ "available": true, "target": "Added app.dev.test", "effect": "Removes app.dev.test" }
|
||||||
|
```
|
||||||
|
```sh
|
||||||
|
TARGET=$(curl -s -H "$H" "$API/undo" | jq -r .target.change_id)
|
||||||
|
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/undo" \
|
||||||
|
-d "{\"target_change_id\": \"$TARGET\"}" | jq -r .apply.id
|
||||||
|
# then poll /applies/{id}:
|
||||||
|
```
|
||||||
|
```json
|
||||||
|
{ "state": "kept", "summary": "Undid: Added app.dev.test", "reason": "app.dev.test is removed.",
|
||||||
|
"steps": ["validate=done", "compile=done", "write=done", "reload=done", "watch=skipped", "push=skipped"] }
|
||||||
|
```
|
||||||
|
```sh
|
||||||
|
visit app.dev.test https://app.dev.test:18443/ # 000: no certificate is served for a removed host
|
||||||
|
```
|
||||||
|
|
||||||
|
## History and Restore
|
||||||
|
|
||||||
|
One entry per action (a reverted attempt is one `reverted` entry):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s -H "$H" "$API/history?limit=5" | jq '[.entries[] | {change_id, summary, state}]'
|
||||||
|
```
|
||||||
|
```json
|
||||||
|
[ { "change_id": "ch_cf0b434ecb4c", "summary": "Undid: Added app.dev.test", "state": "kept" },
|
||||||
|
{ "change_id": "ch_b720484831a9", "summary": "Added app.dev.test", "state": "kept" } ]
|
||||||
|
```
|
||||||
|
```sh
|
||||||
|
curl -s -H "$H" "$API/history/ch_b720484831a9/restore-preview" | jq '{restorable, changes}'
|
||||||
|
```
|
||||||
|
```json
|
||||||
|
{ "restorable": true, "changes": [{ "effect": "added", "fields": [], "hostname": "app.dev.test" }] }
|
||||||
|
```
|
||||||
|
```sh
|
||||||
|
REV=$(curl -s -H "$H" "$API/overview" | jq -r .rev)
|
||||||
|
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/restore" \
|
||||||
|
-d "{\"change_id\": \"ch_b720484831a9\", \"base_rev\": \"$REV\"}" | jq -r .apply.id
|
||||||
|
# then poll /applies/{id}:
|
||||||
|
```
|
||||||
|
```json
|
||||||
|
{ "state": "kept", "summary": "Restored the version of 7 November 2026",
|
||||||
|
"reason": "app.dev.test is live. Health checks passed for 10 s." }
|
||||||
|
```
|
||||||
|
```sh
|
||||||
|
visit app.dev.test https://app.dev.test:18443/ # 200
|
||||||
|
```
|
||||||
|
|
||||||
|
## Share link
|
||||||
|
|
||||||
|
A host with `auth = "forward-auth"` and `share_links = true` (dev mode points sign-in at an
|
||||||
|
Authelia on 127.0.0.1:9091 that is not running, so without a link the request fails closed):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts" \
|
||||||
|
-d '{"host": {"hostname": "wiki.dev.test", "upstreams": ["http://127.0.0.1:3000"],
|
||||||
|
"tls": "domi", "auth": "forward-auth", "share_links": true}}' # poll until kept
|
||||||
|
visit wiki.dev.test https://wiki.dev.test:18443/ # 502: sign-in unreachable, fails closed
|
||||||
|
|
||||||
|
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/hosts/wiki.dev.test/share-links" \
|
||||||
|
-d '{"path_prefix": "/", "expires_in_s": 86400}'
|
||||||
|
```
|
||||||
|
```json
|
||||||
|
{ "id": "ec724bb1420da0d8d81ee897e1e5344b", "expires_at": "2026-11-08T17:20:05Z", "path_prefix": "/",
|
||||||
|
"has_password": false, "url": "https://wiki.dev.test:18443/?share=ish1.…", "warning": null }
|
||||||
|
```
|
||||||
|
|
||||||
|
The URL is shown once: control never stores the token on disk; only an `Idempotency-Key`
|
||||||
|
retry of this request gets the same answer again, from memory, for 24 h. The first visit trades the token for a
|
||||||
|
path-scoped `HttpOnly; Secure; SameSite=Lax` cookie and redirects to the same URL without it:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s -o /dev/null -w '%{http_code} -> %{redirect_url}\n' --cacert "$CA" \
|
||||||
|
--resolve wiki.dev.test:18443:127.0.0.1 -c jar "$URL" # 303 -> https://wiki.dev.test:18443/
|
||||||
|
visit wiki.dev.test -b jar https://wiki.dev.test:18443/ # 200, no sign-in
|
||||||
|
```
|
||||||
|
|
||||||
|
Stop it; edge refuses it at once (and within 5 s even if control's nudge is lost):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s -H "$H" -X DELETE -o /dev/null -w '%{http_code}\n' "$API/share-links/ec724bb1420da0d8d81ee897e1e5344b" # 204
|
||||||
|
visit wiki.dev.test -b jar https://wiki.dev.test:18443/ # 502: back to sign-in
|
||||||
|
visit wiki.dev.test "$URL" # 403: "This link no longer works"
|
||||||
|
```
|
||||||
|
|
||||||
|
Options: `"password": "at least 8 characters"` (the visitor gets a password page; 5 wrong
|
||||||
|
tries a minute per link and network), `"replaces": "<id>"` stops an earlier link,
|
||||||
|
`POST /share-links/stop-all` stops every link made so far, `GET /share-links` lists them
|
||||||
|
(without tokens).
|
||||||
|
|
||||||
|
## Tokens
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/tokens" -d '{"name": "backup script"}'
|
||||||
|
# 201 {"id": "…", "name": "backup script", "token": "ian_…", "expires_at": "2027-11-07T…"} (shown once)
|
||||||
|
curl -s -H "$H" "$API/tokens" # ids, names, dates; never a value or hash
|
||||||
|
curl -s -H "$H" -X DELETE "$API/tokens/<id>" # 204; anything using it stops now
|
||||||
|
curl -s "$API/overview" | jq .error.code # "token.missing"
|
||||||
|
```
|
||||||
|
|
||||||
|
## All calls
|
||||||
|
|
||||||
|
| Call | Does |
|
||||||
|
|:--|:--|
|
||||||
|
| `GET /overview` | the main screen in one call (hosts with health, engine, last apply, undo, active apply, repo, site); `ETag`/`304` |
|
||||||
|
| `GET /hosts`, `GET /hosts/{h}` | hosts; one host with `rev`, its TOML, health and certificate |
|
||||||
|
| `POST /hosts/validate?mode=create\|edit` | check a host body |
|
||||||
|
| `POST /hosts`, `PUT /hosts/{h}`, `PATCH /hosts/{h}`, `DELETE /hosts/{h}?base_rev=` | applies |
|
||||||
|
| `POST /hosts/{h}/certificate/retry` | try Let's Encrypt again now |
|
||||||
|
| `GET /applies`, `GET /applies/{id}`, `DELETE /applies/{id}` | apply records; cancel a queued one |
|
||||||
|
| `GET /history`, `GET /history/{id}`, `GET /history/{id}/restore-preview` | history, one entry, restore preview |
|
||||||
|
| `GET /undo`, `POST /undo`, `POST /restore` | undo and restore |
|
||||||
|
| `POST /repo/push`, `GET /settings` | push now; settings |
|
||||||
|
| `GET/POST /tokens`, `PATCH/DELETE /tokens/{id}` | API tokens |
|
||||||
|
| `POST /hosts/{h}/share-links`, `GET /share-links`, `DELETE /share-links/{id}`, `POST /share-links/stop-all` | share links |
|
||||||
|
| `GET /health` | edge reachability, config hash, trial, paused state, hosts |
|
||||||
|
| `GET /openapi.json` | the OpenAPI document |
|
||||||
+510
@@ -0,0 +1,510 @@
|
|||||||
|
> This file is the web UI's contract with the control API for Phase 3 (from the designer; deviations are listed at the end).
|
||||||
|
|
||||||
|
# Ianitor Domi: what the web UI needs from the Phase 2 API
|
||||||
|
|
||||||
|
From the UI design (claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u, 9 boards) and ROADMAP §3, §4, §6, §10.
|
||||||
|
Shapes are resource + method + fields, not OpenAPI. Sources: [D] drawn on a board, [R] ROADMAP, [C] current code, [J] my call.
|
||||||
|
|
||||||
|
## 0. Ground rules for every call
|
||||||
|
|
||||||
|
- Base path `/api/v1`, JSON, times RFC 3339 UTC. The UI formats times in the browser's zone ("Today 14:02").
|
||||||
|
- Every response carries `server_time`. The UI counts down from `ends_at - server_time`, never from the browser clock.
|
||||||
|
- Errors use one envelope:
|
||||||
|
```
|
||||||
|
{ "error": { "code": "host.hostname.taken", "message": "<plain English, shown as is>",
|
||||||
|
"field": "hostname" | null, "params": { ... }, "retry_after_s": null },
|
||||||
|
"errors": [ ...same shape, for several field errors... ], "request_id": "01J..." }
|
||||||
|
```
|
||||||
|
`code` is stable and is what the UI switches on. `message` is the §3 text, filled by the server, so curl users get the same words.
|
||||||
|
`params` holds the values in the message (hostname, address, counts, dates) so the UI can bold them.
|
||||||
|
A technical detail (core's own error text, log lines) goes only in `detail`, shown behind "Show details". It never holds a secret value or a token.
|
||||||
|
- Writes take an `Idempotency-Key` header, one per click. An apply can reload the proxy the UI talks through, so a dropped POST gets retried, and the retry must not apply twice.
|
||||||
|
- Writes that change routes take `base_rev`: the routes-tree commit the form was loaded from. The server refuses only if *the same host file* changed since then (§3 `change.conflict`). A change elsewhere in the tree is fine, so queued applies don't refuse each other.
|
||||||
|
- The UI sends `X-Ianitor-UI: 1` on every request, as a CSRF guard: control refuses browser-origin writes without it. Who the user is comes from the Authelia `Remote-User` that edge forwards (see gap G14).
|
||||||
|
|
||||||
|
## 1. Per flow
|
||||||
|
|
||||||
|
### 1.1 Main screen (desktop and phone boards) [D]
|
||||||
|
|
||||||
|
**One call: `GET /overview`.** Yes, one call is possible, as long as control keeps a cached copy of health (edge pushes it or control pulls every 2 s; see G1). The request must never wait on a live probe.
|
||||||
|
|
||||||
|
| Block | Fields | Shown as |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| `counts` | `hosts, healthy, degraded, down, unknown` | "7 hosts · 5 healthy, 1 degraded, 1 down" |
|
||||||
|
| `hosts[]` | `hostname, upstreams[] (url), tls ("domi"\|"letsencrypt"), auth ("none"\|"forward-auth"), websockets, share_links, added_at` | row, chips, "Added today" |
|
||||||
|
| `hosts[].health` | `state ("healthy"\|"degraded"\|"down"\|"unknown"\|"pending"), last_check_at, latency_ms (nullable), since, failure {kind, upstream, count, of} \| null, upstreams[] {url, state, last_check_at, latency_ms, failure_kind}` | dot + word, "Checked 8 s ago · 42 ms", "Connection refused for 6 minutes" |
|
||||||
|
| `hosts[].certificate` | `state ("ok"\|"pending"\|"failed"), not_after, error_code` | extra line only when not `ok` |
|
||||||
|
| `engine` | `running ("pingora"\|"caddy"), state ("running"\|"switching"\|"stopped"), since, fallback_ready {built_at, compared, matched} \| null` | engine chip; popover (switch flow) |
|
||||||
|
| `last_apply` | the most recent apply record (§2), any outcome, or null | last-change bar: state word, summary, sub-line |
|
||||||
|
| `undo` | see §2.3 | the Undo button and its name |
|
||||||
|
| `active_apply` | `{id, state, summary, seconds_left}` \| null, plus `queued` (count) | "Applying wiki.home.example: 41 s left" when the user comes back to the main screen |
|
||||||
|
| `repo` | `name, last_push_at, unpushed (count), push_error_code` \| null | footer "Last pushed to Gitea at 14:03" |
|
||||||
|
| `intermediate` | `not_after, days_left, renewal {request_id, state, match_code, expires_at} \| null`; **null until Phase 3** | banner when `days_left <= 30` or `renewal` is open |
|
||||||
|
| `site` | `forward_auth_configured, acme_configured, secrets[] (names only), watch_seconds (60)` | add-host form: disables "Sign in first" if Authelia is not set up; secret picker in headers |
|
||||||
|
| `paused` | `{code, message}` \| null | full-width notice; disables + Host, Undo, Restore |
|
||||||
|
|
||||||
|
Health `state` rules for the UI [J]: `healthy` = every upstream passed its last check. `degraded` = some passed, some failed, or the last 5 checks were mixed. `down` = no upstream passed the last check. `unknown` = no health check set. `pending` = added but not yet checked. The drawn "slow: 2.8 s, limit is 2 s" has no basis in the schema (see G2).
|
||||||
|
|
||||||
|
Polling: every 5 s while the tab is visible, every 30 s when hidden. Send `If-None-Match` with the ETag and expect `304` when nothing changed.
|
||||||
|
|
||||||
|
Clicks on the main screen:
|
||||||
|
|
||||||
|
| Click | Call |
|
||||||
|
|:--|:--|
|
||||||
|
| + Host | none (opens the panel) |
|
||||||
|
| Undo | `POST /undo` (§1.3) |
|
||||||
|
| Renew (banner) | `POST /certs/intermediate/renewal` (Phase 3, §1.8) |
|
||||||
|
| ⋯ on a row | none (menu) |
|
||||||
|
| ⋯ → Edit host | `GET /hosts/{hostname}` → returns the full host (all §3 ROADMAP fields) + `rev` |
|
||||||
|
| ⋯ → Show in history | `GET /history?host={hostname}` |
|
||||||
|
| ⋯ → Remove host | `DELETE /hosts/{hostname}?base_rev=` → `202` apply. No confirmation dialog: Undo restores the host in 1 click [J] |
|
||||||
|
| Engine chip | none (popover from `engine`) |
|
||||||
|
|
||||||
|
### 1.2 Add host: + Host → fill → Apply = 2 clicks [D][R]
|
||||||
|
|
||||||
|
| State | Call | Shows |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| Panel open | none; values come from `overview.site` | hostname focused; form defaults Domi certificate, Sign in first [D] (the UI always sends explicit values; schema defaults are letsencrypt and none [C]) |
|
||||||
|
| Typing (field blur, not a click) | `POST /hosts/validate` body = host, `?mode=create` | inline field errors (§3.1), including a taken hostname, before Apply |
|
||||||
|
| **Apply (click 2)** | `POST /hosts` body = `{host, base_rev}` | `422` with `errors[]` → keep the panel, mark the fields. `202 {apply}` → the panel shows the apply steps (§2) |
|
||||||
|
| Watching | `GET /applies/{id}` every 1 s (§2.2) | checklist + "41 s left" + progress bar |
|
||||||
|
| Kept | (final poll) | panel closes; the row appears; the bar shows `kept` + Undo |
|
||||||
|
| Reverted | (final poll) | panel stays open with the user's values; banner with the reason; "Edit and try again" focuses the field the reason names (`reason.field`, e.g. `upstreams[0]`) |
|
||||||
|
|
||||||
|
Host body (mirrors the TOML [C]):
|
||||||
|
`hostname, upstreams[] (strings), tls, auth, websockets, share_links, access_log ("off"|"truncated"), health_check {path, interval_secs} | null, request_headers[] / response_headers[] {action ("set"|"remove"), name, value | secret}`.
|
||||||
|
|
||||||
|
### 1.3 Undo last change = 1 click [D][R]
|
||||||
|
|
||||||
|
- Data: `overview.undo` (§2.3). The button reads **Undo** with the target's name beside it in the bar.
|
||||||
|
- Click: `POST /undo {target_change_id}` → `202 {apply}`, with the same states as any apply. The server refuses with `409 undo.target_moved` if the target is no longer the latest kept change, so Undo never undoes something it did not name.
|
||||||
|
- During its own watch, Undo is disabled with "Wait for the check to finish (41 s)". If a *different* apply is running, Undo is queued like any change.
|
||||||
|
|
||||||
|
### 1.4 Restore: History → pick → Restore = 3 clicks [D][R]
|
||||||
|
|
||||||
|
| Click | Call | Fields shown |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| 1 History | `GET /history?limit=50` (`before=` for more) | `entries[] {change_id, summary, kind ("add"\|"edit"\|"remove"\|"undo"\|"restore"\|"share_links"), state ("kept"\|"reverted"\|"failed"\|"queued"\|"running"), at, commit_short, hosts[], reason_short}` ("port refused") |
|
||||||
|
| 2 pick | `GET /history/{change_id}/restore-preview` | `restorable` (false for reverted or failed entries, which instead offer "Edit and try again" using `GET /history/{id}` → `attempted_host`), `same_as_current`, `changes[] {hostname, effect ("added"\|"removed"\|"changed"), fields[] {field, from, to}}` |
|
||||||
|
| 3 Restore this version | `POST /restore {change_id, base_rev}` | `202 {apply}` → bar: "Restored the version of 3 Nov, 09:30" |
|
||||||
|
|
||||||
|
- History must show one entry per user action. An attempt that was reverted is one `reverted` entry, not a commit row plus a revert row. Control groups them.
|
||||||
|
- The UI writes the preview sentences from `fields[]` with this label map, so the wording is the same everywhere: hostname "address", upstreams "sends traffic to", tls "certificate", auth "who can open it", health_check.path "health check address", health_check.interval_secs "checks every", share_links "share links", access_log "visit log", websockets "websockets", headers "header rules".
|
||||||
|
- Drop the drawn line "wiki.home.example is not affected (never kept)". The preview lists only real differences.
|
||||||
|
|
||||||
|
### 1.5 Share link: ⋯ → Share link → Copy = 3 clicks [D][R]
|
||||||
|
|
||||||
|
| Click | Call | Fields |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| 1 ⋯ | none | menu; "Share link" is enabled when the host's `share_links` is true (from overview) |
|
||||||
|
| 2 Share link | `POST /hosts/{hostname}/share-links {path_prefix: "/", expires_in_s: 604800}` → `201` | `id, url, expires_at, path_prefix, has_password` |
|
||||||
|
| 3 Copy link | none (client clipboard only, so the copy happens inside the click) | "Copied. Expires on 14 November 2026 at 14:20." |
|
||||||
|
| Change expiry or prefix, add a password (extra clicks) | `POST /hosts/{h}/share-links {..., replaces: <previous id>}` | the new link; the server stops the one it replaces. A link minted on open and never copied doesn't stay valid |
|
||||||
|
|
||||||
|
- Expiry options in the UI: 1, 7, 30 days. The server accepts 1 hour to 90 days [J].
|
||||||
|
- Password: `password` in the POST body; at least 8 characters [J]; never returned.
|
||||||
|
- Links off for this host: the dialog shows "Turn on share links and apply". Clicking it calls `PATCH /hosts/{h} {share_links: true, base_rev}` → `202 {apply}`. After `kept`, the UI auto-calls the mint POST and shows the link; Copy is click 4 (G10).
|
||||||
|
- Host with `auth = none`: the dialog says anyone can already open it. Mint anyway if asked; the UI does not block it.
|
||||||
|
- Settings → Share links: `GET /share-links` → `items[] {id, hostname, path_prefix, created_at, expires_at, has_password, state ("active"|"expired"|"stopped")}`. "Stop this link" calls `DELETE /share-links/{id}` → `204`. "Stop all share links" calls `POST /share-links/stop-all` (G8).
|
||||||
|
|
||||||
|
### 1.6 API token: ⚙ → API → New token = 3 clicks [D][R]
|
||||||
|
|
||||||
|
| Click | Call | Fields |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| 1 Settings | `GET /settings` | `repo {name, last_push_at}, watch_seconds` (read-only in v1) |
|
||||||
|
| 2 API tab | `GET /tokens` | `items[] {id, name, created_at, last_used_at, expires_at \| null}`; never a hash or a prefix |
|
||||||
|
| 3 New token | `POST /tokens {name?}` → `201 {id, name, token, expires_at}` | the token is shown once and returned only in this response. The UI drops it from memory when the dialog closes |
|
||||||
|
| Rename (optional) | `PATCH /tokens/{id} {name}` | |
|
||||||
|
| Revoke | `DELETE /tokens/{id}` → `204` | the row goes to "Revoked today 14:40" until the next reload |
|
||||||
|
|
||||||
|
- Recommendation that removes the 4th click (G12): click 3 is **Make and copy token**. The UI calls `navigator.clipboard.write([new ClipboardItem({"text/plain": tokenPromise})])` inside the click, so the copy belongs to that click even though the POST is async. The POST must answer in under 1 s. The dialog then says "Copied. Paste it into Custos now." and keeps a Copy again button.
|
||||||
|
- Default lifetime 365 days, or "Never expires" as an option [J]. Expiry is needed for the expired-token message in §3.
|
||||||
|
|
||||||
|
### 1.7 Device certificate (Phase 3): Certificates → + Device → Issue = 3 clicks [D][R]
|
||||||
|
|
||||||
|
| State | Call | Fields |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| 1 Certificates | `GET /certs` | `intermediate {subject, not_after, days_left}`, `root {offline: true}`, `devices[] {id, name, kind ("phone"\|"computer"\|"app"), not_after, state ("valid"\|"revoked"\|"expired")}`, `device_lifetime_days` |
|
||||||
|
| 2 + Device | none | form |
|
||||||
|
| 3 Issue | `POST /certs/devices {name, kind}` → `202 {request_id, match_code, expires_at}` | "47 19 83", "The request stays open for 10 minutes" |
|
||||||
|
| Waiting | `GET /pki-requests/{id}` every 2 s | `state ("waiting"\|"approved"\|"denied"\|"expired"\|"cancelled"\|"failed"), approved_at, device_id` |
|
||||||
|
| Cancel request | `DELETE /pki-requests/{id}` | |
|
||||||
|
| Issued, install (click 4) | `POST /certs/devices/{id}/bundle {format: "p12"\|"qr"}` → `{download_url, one_time_password, expires_at}` | one download only, then deleted; QR encodes `download_url` (G15) |
|
||||||
|
| Revoke a device | `DELETE /certs/devices/{id}` | |
|
||||||
|
|
||||||
|
### 1.8 Renew intermediate (Phase 3): banner Renew = 1 click [D][R]
|
||||||
|
|
||||||
|
- Click: `POST /certs/intermediate/renewal` → `202 {request_id, match_code, expires_at}`. The banner turns into the match code and "Approve it in Custos".
|
||||||
|
- Then `GET /pki-requests/{id}` every 2 s. Once `approved`, `overview.intermediate.not_after` moves on and the banner says "Renewed. The Domi intermediate certificate is now valid until 30 November 2027." for this session.
|
||||||
|
- Banner states the UI needs: `due` (≤ 30 days), `urgent` (≤ 7 days, uses the `down` colour), `waiting` (match code), `expired`, `failed` (§3.6).
|
||||||
|
|
||||||
|
### 1.9 Switch engine (not in this brief's scope, but on the main screen)
|
||||||
|
|
||||||
|
`overview.engine` is enough to draw the chip and the popover. The switch call (`POST /engine {target}` → `202`, polled like an apply) waits on Mark's decision (b) in §10.
|
||||||
|
|
||||||
|
## 2. Apply outcomes
|
||||||
|
|
||||||
|
### 2.1 The apply record
|
||||||
|
|
||||||
|
`GET /applies/{id}` (also embedded as `last_apply` and in every `202`):
|
||||||
|
|
||||||
|
```
|
||||||
|
id, change_id, kind, summary ("Added wiki.home.example"), hosts[], state, created_at, finished_at,
|
||||||
|
steps[] { key ("validate"|"compile"|"write"|"reload"|"watch"|"push"), state ("pending"|"running"|"done"|"failed"|"skipped") },
|
||||||
|
queue { position, waiting_for { apply_id, summary, seconds_left } } | null,
|
||||||
|
watch { ends_at, seconds_left, hosts[] { hostname, passed, failed, total } } | null,
|
||||||
|
reason { code, message, hostname, upstream, field, count, of } | null,
|
||||||
|
commit_short | null, push { state ("pushed"|"pending"|"failed"), at, error_code, next_try_at } | null,
|
||||||
|
undo_of | null, restore_of | null
|
||||||
|
```
|
||||||
|
|
||||||
|
| `state` | When | The UI shows (copy in §3.2) |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| `queued` | another apply is running | "Waiting for 'Added recipes.home.example' to finish (about 40 s)." + Cancel (`DELETE /applies/{id}`, allowed only while queued) |
|
||||||
|
| `validating` | checking the files again in the queue | step 1 running |
|
||||||
|
| `applying` | compile, write, reload | steps 2–3 running |
|
||||||
|
| `watching` | the 60 s health watch | step 4, "41 s left", progress `60 - seconds_left` of 60 |
|
||||||
|
| `kept` | passed; committed | bar `kept`; push sub-state below |
|
||||||
|
| `kept` + `push.state = failed` | kept, but Gitea refused or did not answer | bar `kept` + "Not yet saved to Gitea" + Try now (`POST /repo/push`) |
|
||||||
|
| `reverted` | failed the watch; undone | banner `reverted` + `reason.message` + Edit and try again |
|
||||||
|
| `failed` | never went live (validation in the queue, compile, reload refused) | banner + reason; nothing changed |
|
||||||
|
| `interrupted` → `reverted` | control restarted mid-apply | reason `apply.interrupted` |
|
||||||
|
| `needs_attention` | the revert itself failed | red banner, Restore last kept version (§3.2) |
|
||||||
|
|
||||||
|
Watch rule recommendation [J]: watch only the hosts this change touches. A host that was already down before the change is no reason to revert. A touched host fails if it has no healthy upstream for 3 checks in a row, or none at the end of the 60 s. During the watch, edge checks touched hosts every 5 s whatever their interval, so a watch has about 12 checks, not 6. Removing a host has nothing to watch: `watch` is `skipped` and the result is `kept`. Hosts without a health check: see G3.
|
||||||
|
|
||||||
|
### 2.2 How the UI learns progress: polling, 1 s
|
||||||
|
|
||||||
|
**Pick: polling `GET /applies/{id}` every 1 s while the state is queued, validating, applying or watching; then stop.**
|
||||||
|
|
||||||
|
Why not SSE:
|
||||||
|
1. The browser reaches control *through the proxy the apply reloads*: edge with forward-auth, or Caddy after a switch. A graceful reload either holds the old process open for a long-lived stream or cuts it at the drain timeout. A revert reloads a second time. Every apply would break the SSE stream at its most important moment. A 1 s poll just retries.
|
||||||
|
2. Engine switches and control restarts drop every connection too. Polling needs no resume logic; SSE needs `Last-Event-ID` replay.
|
||||||
|
3. Cost is trivial: one small JSON per second on loopback, 60 per apply, one apply at a time.
|
||||||
|
4. Smoothness: the UI counts down locally from `watch.ends_at - server_time` between polls, so the seconds tick evenly even if a poll is late.
|
||||||
|
|
||||||
|
Errors while polling: retry quietly for 10 s (a reload takes about 2 s), then show `ui.lost_contact` and keep polling every 5 s.
|
||||||
|
|
||||||
|
### 2.3 What the Undo bar needs
|
||||||
|
|
||||||
|
`overview.undo`:
|
||||||
|
```
|
||||||
|
available, target { change_id, summary, kept_at, commit_short } | null,
|
||||||
|
effect ("Removes recipes.home.example"), blocked { code, message } | null
|
||||||
|
```
|
||||||
|
- The target is always the latest **kept** change, never a reverted or failed one.
|
||||||
|
- Right after a reverted apply, the bar has two lines. Line 1 is `last_apply`: "`reverted` wiki.home.example was not added. Reason: …". Line 2 is the Undo button labelled with `undo.target.summary`: "Undo: Added recipes.home.example". The two lines come from two fields, so the bar always names what Undo will touch.
|
||||||
|
- After an Undo is kept, the latest kept change *is* the undo, so Undo again redoes it. `summary` for an undo reads "Undid: Added recipes.home.example", and `effect` reads "Adds recipes.home.example back". The button then says "Undo: Undid Added recipes.home.example", with the effect line under it.
|
||||||
|
- `blocked` codes: `undo.nothing` (no kept change yet), `undo.watching` (its own apply is still running), `undo.paused` (§3.2 needs_attention or repo paused).
|
||||||
|
|
||||||
|
## 3. Every user-facing message
|
||||||
|
|
||||||
|
`{x}` are `params`. Bold in the UI: hostnames and addresses. Tone: say what happened, what still works, and what to do. No "error", "failed to", "invalid", status codes, or protocol names.
|
||||||
|
|
||||||
|
### 3.1 Host form validation (one row per core error [C]; `field` in brackets)
|
||||||
|
|
||||||
|
| Code | Field | Message | UI offers |
|
||||||
|
|:--|:--|:--|:--|
|
||||||
|
| `host.hostname.missing` | hostname | Enter the address people will type, like wiki.home.example. | focus |
|
||||||
|
| `host.hostname.uppercase` | hostname | Use lowercase letters only: {suggestion}. | "Use {suggestion}" (fills it) |
|
||||||
|
| `host.hostname.characters` | hostname | Use only letters a–z, digits, dots and dashes. | focus |
|
||||||
|
| `host.hostname.spaces` | hostname | Remove the spaces from the address. | focus |
|
||||||
|
| `host.hostname.wildcard` | hostname | Addresses with * are not supported yet. Add each name as its own host. | focus |
|
||||||
|
| `host.hostname.trailing_dot` | hostname | Remove the dot at the end. | "Use {suggestion}" |
|
||||||
|
| `host.hostname.empty_label` | hostname | There are two dots in a row. Remove one. | focus |
|
||||||
|
| `host.hostname.label_dash` | hostname | A part of the address cannot start or end with a dash. | focus |
|
||||||
|
| `host.hostname.label_long` | hostname | Each part between dots can be at most 63 characters. | focus |
|
||||||
|
| `host.hostname.too_long` | hostname | The address can be at most 253 characters. | focus |
|
||||||
|
| `host.hostname.numeric` | hostname | That looks like an IP address. Use a name, like wiki.home.example. | focus |
|
||||||
|
| `host.hostname.taken` | hostname | {hostname} is already a host. | "Open {hostname}" (edit form) |
|
||||||
|
| `host.upstreams.missing` | upstreams | Enter where Ianitor should send traffic, like http://10.0.0.23:3000. | focus |
|
||||||
|
| `host.upstream.not_url` | upstreams[i] | Write it as a full address, like http://10.0.0.23:3000. | focus |
|
||||||
|
| `host.upstream.scheme` | upstreams[i] | Start the address with http:// or https://. | focus |
|
||||||
|
| `host.upstream.no_host` | upstreams[i] | Add the server's name or IP address after http://. | focus |
|
||||||
|
| `host.upstream.no_port` | upstreams[i] | Add the port at the end, like :3000. | focus |
|
||||||
|
| `host.upstream.port_zero` | upstreams[i] | Port 0 cannot be used. Enter the port the service listens on. | focus |
|
||||||
|
| `host.upstream.path` | upstreams[i] | Leave out the path after the port. Visitors keep their own path. | "Use {suggestion}" |
|
||||||
|
| `host.upstream.query` / `.fragment` | upstreams[i] | Leave out everything after ? or #. | "Use {suggestion}" |
|
||||||
|
| `host.upstream.credentials` | upstreams[i] | Leave out the user name and password. Put them in a header rule with a secret instead. | open More options → Headers |
|
||||||
|
| `host.upstream.duplicate` | upstreams[i] | This address is listed twice. | "Remove it" |
|
||||||
|
| `host.upstream.mixed_schemes` | upstreams | All addresses for one host must start the same way: all http:// or all https://. | focus |
|
||||||
|
| `host.upstream.too_many` | upstreams | One host can send traffic to at most {max} addresses. | — |
|
||||||
|
| `host.auth.not_configured` | auth | Sign-in is not set up on this server yet, so choose Anyone for now. To set it up, add the Authelia address to ianitor.toml in the routes repository. | the option is disabled up front when `site.forward_auth_configured` is false; the hint says why |
|
||||||
|
| `host.header.name` | {list}[i].name | "{name}" cannot be a header name. Use letters, digits and dashes. | focus |
|
||||||
|
| `host.header.value` | {list}[i].value | This value has characters a header cannot carry. Use visible characters and spaces only. | focus |
|
||||||
|
| `host.header.empty` | {list}[i].value | Enter a value, or choose Remove to drop the header. | switch to Remove |
|
||||||
|
| `host.header.protected` | {list}[i].name | Ianitor sets {name} itself, so a rule cannot change it. | — |
|
||||||
|
| `host.header.duplicate` | {list}[i].name | {name} already has a rule in this list. | jump to that rule |
|
||||||
|
| `host.header.both` | {list}[i] | Choose a fixed value or a secret, not both. | — |
|
||||||
|
| `host.header.remove_value` | {list}[i] | Remove needs only the header name. | clear the value |
|
||||||
|
| `host.header.secret_unknown` | {list}[i].secret | There is no secret named {secret}. Secrets are listed in ianitor.toml and loaded from the server's credentials. | picker shows `site.secrets` |
|
||||||
|
| `host.header.secret_response` | response_headers[i] | Secrets can only be sent to your service, never back to visitors. | move to request headers |
|
||||||
|
| `host.health.path` | health_check.path | Start with / and use plain characters, like /health. | focus |
|
||||||
|
| `host.health.interval` | health_check.interval_secs | Check every 1 to 3600 seconds. | focus |
|
||||||
|
| `host.field.unknown` | {field} | Ianitor does not know the setting "{field}". | (API clients only) |
|
||||||
|
| `change.conflict` | — | {hostname} was changed at {time} ("{summary}") after you opened it. Your edits are still here. Check them, then Apply again. | "Show the new version" |
|
||||||
|
| `host.not_found` | — | {hostname} is no longer a host. It was removed at {time}. | back to the list |
|
||||||
|
|
||||||
|
Warning, not an error: `host.share.no_signin`: "Anyone can already open {hostname}, so a share link changes nothing." It appears in the share dialog and the form; it doesn't block anything.
|
||||||
|
|
||||||
|
### 3.2 Apply, undo, restore, repository
|
||||||
|
|
||||||
|
| Code | Message | UI offers |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| `apply.queued` | Waiting for "{summary}" to finish, about {seconds} s. | Cancel |
|
||||||
|
| `apply.kept` | {hostname} is live. Health checks passed for 60 s. Saved and sent to Gitea. | Undo |
|
||||||
|
| `apply.kept.no_watch` | {hostname} is live. It has no health check, so Ianitor only checked that it answers. | Add a health check (edit form) |
|
||||||
|
| `apply.reverted.refused` | {hostname} was not {verb}. {upstream} refused the connection on {count} of {of} checks. Ianitor undid the change; every other host kept running. | Edit and try again |
|
||||||
|
| `apply.reverted.timeout` | {hostname} was not {verb}. {upstream} did not answer within 5 seconds on {count} of {of} checks. Ianitor undid the change. | Edit and try again |
|
||||||
|
| `apply.reverted.not_found` | {hostname} was not {verb}. {upstream} says {path} does not exist. Check the health check address. Ianitor undid the change. | Edit health check |
|
||||||
|
| `apply.reverted.server_error` | {hostname} was not {verb}. {upstream} answered with an error page on {count} of {of} checks. Ianitor undid the change. | Edit and try again |
|
||||||
|
| `apply.reverted.redirect` | {hostname} was not {verb}. {upstream} sent visitors elsewhere instead of answering {path}. Use an address that answers directly, like /health. | Edit health check |
|
||||||
|
| `apply.reverted.sign_in` | {hostname} was not {verb}. {upstream} asked for a sign-in on {path}. Use an address that answers without signing in. | Edit health check |
|
||||||
|
| `apply.reverted.name` | {hostname} was not {verb}. The name {upstream_host} could not be found on this network. | Edit and try again |
|
||||||
|
| `apply.reverted.tls` | {hostname} was not {verb}. {upstream} uses https://, but its certificate could not be checked. | Edit and try again |
|
||||||
|
| `apply.failed.reload` | {engine} did not take the new settings, so nothing changed. Every host kept running. | Show details |
|
||||||
|
| `apply.failed.build` | Ianitor could not build the settings for this change, so nothing changed. | Show details |
|
||||||
|
| `apply.failed.validation` | This change no longer fits with the routes: {first_error}. Nothing changed. | Edit and try again |
|
||||||
|
| `apply.interrupted` | Ianitor restarted during the check, so it undid the change to be safe. | Try again |
|
||||||
|
| `apply.needs_attention` | The change failed its check, and Ianitor could not undo it by itself. Visitors are served the last good settings, but the routes repository still has the change. | Restore last kept version (1 click, `POST /restore` with `undo.target`) |
|
||||||
|
| `push.failed.unreachable` | Kept, but not yet saved to Gitea: Gitea did not answer. Ianitor tries again at {time}. | Try now |
|
||||||
|
| `push.failed.rejected` | Kept, but Gitea has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server. | Show details |
|
||||||
|
| `push.failed.auth` | Kept, but Gitea refused Ianitor's access key. Check the key in Custos. | Try now |
|
||||||
|
| `undo.nothing` | Nothing to undo yet. | — |
|
||||||
|
| `undo.watching` | Wait for the check to finish ({seconds} s). | — |
|
||||||
|
| `undo.target_moved` | The last change is now "{summary}", so Undo did nothing. Look again and choose. | bar refreshes |
|
||||||
|
| `restore.same` | This version is the same as the current one. Nothing to restore. | Close |
|
||||||
|
| `restore.not_kept` | This change was undone at the time, so there is nothing to go back to. | Edit and try again |
|
||||||
|
| `repo.unreadable` | {file} in the routes repository cannot be read (line {line}). Changes are paused until it is fixed. | Show details |
|
||||||
|
|
||||||
|
`{verb}` is "added", "changed" or "removed", from the change kind. `{engine}` is "Pingora" or "Caddy"; product names are allowed.
|
||||||
|
|
||||||
|
### 3.3 Host health lines (main screen) and visitor errors
|
||||||
|
|
||||||
|
| `failure.kind` | Row line |
|
||||||
|
|:--|:--|
|
||||||
|
| `refused` | Connection refused for {duration}. Visitors see a "not reachable" page. |
|
||||||
|
| `timeout` | Not answering for {duration}. Visitors see a "not reachable" page. |
|
||||||
|
| `name` | The name {upstream_host} cannot be found. Visitors see a "not reachable" page. |
|
||||||
|
| `tls` | The certificate of {upstream} cannot be checked. |
|
||||||
|
| `bad_answer` | Answering with an error page for {duration}. |
|
||||||
|
| partial (degraded) | {n} of {m} addresses answer. Visitors are sent to the ones that do. |
|
||||||
|
| `unknown` | No health check set for this host. |
|
||||||
|
| `pending` | Waiting for the first check. |
|
||||||
|
| cert `pending` | Waiting for Let's Encrypt to issue the certificate. |
|
||||||
|
| cert `failed` | Let's Encrypt could not confirm {hostname}. The name must point to this server, and port 80 must be open from the internet. — offers Try again |
|
||||||
|
| `health.unavailable` (global) | Ianitor cannot read health from {engine} right now. Traffic is not affected. |
|
||||||
|
|
||||||
|
### 3.4 Share links
|
||||||
|
|
||||||
|
Admin side:
|
||||||
|
|
||||||
|
| Code | Message | UI offers |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| `share.disabled` | Share links are off for {hostname}. Turning them on is a change to the host, checked like any other. | Turn on share links and apply |
|
||||||
|
| `share.prefix` | Start with /, like /share/summer-2026. / shares the whole site. | focus |
|
||||||
|
| `share.expiry` | Choose between 1 hour and 90 days. | — |
|
||||||
|
| `share.password_short` | Use at least 8 characters. | focus |
|
||||||
|
| `share.stopped` | Stopped. The link stops working within a few seconds. | — |
|
||||||
|
| `share.stopped_all` | All share links are stopped. New ones work as usual. | — |
|
||||||
|
| `share.engine_caddy` | Share links are paused while Caddy serves. They work again after switching back. (Only if G7 is not solved.) | — |
|
||||||
|
|
||||||
|
Visitor side (pages in §4):
|
||||||
|
|
||||||
|
| Code | Heading | Text | Offers |
|
||||||
|
|:--|:--|:--|:--|
|
||||||
|
| `share.visit.password` | This link is protected | Someone shared {hostname} with you. Enter the password they gave you. | Password field, Open |
|
||||||
|
| `share.visit.wrong_password` | (same page) | That password is not right. Check it with the person who sent the link. | field cleared and focused |
|
||||||
|
| `share.visit.too_many` | (same page) | Too many tries. Wait a minute, then try again. | button disabled |
|
||||||
|
| `share.visit.expired` | This link has expired | It worked until {date}. Ask the person who sent it for a new one. | Have an account? Sign in |
|
||||||
|
| `share.visit.invalid` (stopped, altered, other host, share links turned off) | This link no longer works | It may have been stopped, or not copied in full. Ask the person who sent it for a new one. | Have an account? Sign in |
|
||||||
|
| outside the prefix | — (no page) | the request goes to the normal sign-in, as if there were no link | — |
|
||||||
|
| `visit.unreachable` | This site is not reachable right now | The service behind this address is not answering. It is not your connection. Try again in a few minutes. | Try again |
|
||||||
|
|
||||||
|
Don't tell "stopped" apart from "altered": both use `invalid`. "Expired" is told apart because the signature proves the date.
|
||||||
|
|
||||||
|
### 3.5 API tokens, sign-in, limits, connection
|
||||||
|
|
||||||
|
| Code | Message | Who sees it | Offers |
|
||||||
|
|:--|:--|:--|:--|
|
||||||
|
| `token.missing` | This request needs an API token. Make one in Settings, API. | script | — |
|
||||||
|
| `token.unknown` | This API token is not one Ianitor issued, or it was copied incompletely. | script | — |
|
||||||
|
| `token.expired` | This API token expired on {date}. Make a new one in Settings, API, then revoke this one. | script | — |
|
||||||
|
| `token.revoked` | This API token was revoked on {date}. | script | — |
|
||||||
|
| `token.created` | Copied. Paste it into Custos now. Ianitor cannot show it again. | UI | Copy again, I have saved it |
|
||||||
|
| `token.revoke_done` | Revoked. Anything using "{name}" stops working now. | UI | — |
|
||||||
|
| `rate.limited` | Too many requests in a short time. Try again in {seconds} s. | both; UI retries once by itself first | — |
|
||||||
|
| `ui.signed_out` | Your sign-in has ended. Sign in again; this page keeps what you typed. | UI | Sign in |
|
||||||
|
| `ui.lost_contact` | Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back. | UI | retries every 5 s |
|
||||||
|
| `control.paused` | Changes are paused: {reason}. Traffic keeps flowing. | UI | per reason |
|
||||||
|
|
||||||
|
Detecting sign-out: when Authelia's session ends, edge returns its portal redirect as is. The UI uses `fetch(..., {redirect: "manual"})` and treats an `opaqueredirect` or a `401` as `ui.signed_out`. Nothing from control is needed.
|
||||||
|
|
||||||
|
Rate limits [J]: 120 requests a minute per signed-in user or token; share-link mint 30 a minute; token creation 10 an hour. Wrong share passwords: 5 a minute per link and visitor /24. Answers carry `retry_after_s`.
|
||||||
|
|
||||||
|
### 3.6 PKI (Phase 3)
|
||||||
|
|
||||||
|
| Code | Message | Offers |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| `pki.waiting` | Open Custos on your phone. Approve only if it shows the same code: {code}. | Cancel request |
|
||||||
|
| `pki.denied` | The request was turned down in Custos. Nothing was issued. | Try again |
|
||||||
|
| `pki.expired` | Nobody approved it within 10 minutes, so the request closed. Nothing was issued. | Try again |
|
||||||
|
| `pki.custos_unreachable` | Custos is not answering, so the request could not be sent. | Try again |
|
||||||
|
| `pki.device_name_taken` | A device named "{name}" already has a certificate. Use another name, or revoke the old one first. | Show it |
|
||||||
|
| `pki.issued` | {name} has a certificate. Approved in Custos at {time}. | Show QR code, Download file |
|
||||||
|
| `pki.bundle_used` | This download was already used. Make a new one from the device's row. | — |
|
||||||
|
| `pki.renew_due` | The Domi intermediate certificate expires in {days} days, on {date}. | Renew |
|
||||||
|
| `pki.renew_urgent` | The Domi intermediate certificate expires in {days} days. After that, Domi certificates stop working. | Renew |
|
||||||
|
| `pki.intermediate_expired` | The Domi intermediate certificate expired on {date}. Hosts with a Domi certificate are not trusted until it is renewed. | Renew |
|
||||||
|
| `pki.renewed` | Renewed. The Domi intermediate certificate is now valid until {date}. | — |
|
||||||
|
|
||||||
|
## 4. Share-link visitor pages (served by edge)
|
||||||
|
|
||||||
|
These are four pages: password prompt (with its wrong-password and too-many states), link expired, link no longer works, and service not reachable.
|
||||||
|
|
||||||
|
**Build constraints**
|
||||||
|
- One self-contained HTML file per page with inline CSS, under 8 KB. No JavaScript, no external requests, no web fonts. These pages must work on a visitor's phone with nothing else loaded. System font stack: `system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`.
|
||||||
|
- Headers: `Cache-Control: no-store`, `Referrer-Policy: no-referrer`, `X-Robots-Tag: noindex`, `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; form-action 'self'`. `lang="en"`. Status codes are not visible to visitors: prompt 401, expired 410, invalid 403, not reachable 502.
|
||||||
|
- Password form: `POST` to a reserved path `/.well-known/ianitor/share` with hidden `t` (the token) and `password`. On success, edge sets an HttpOnly, Secure, SameSite=Lax cookie scoped to the host and `path_prefix` until the link's expiry. It then redirects to the prefix *without* `?share=` so the token never sits in the address bar or a referrer. A link without a password takes the same redirect at once.
|
||||||
|
- Only the hostname and the expiry date come from the request. Escape both. Nothing else from the request is echoed.
|
||||||
|
|
||||||
|
**Layout** (murex palette, same on all four)
|
||||||
|
- `body`: background `#0c0b0f` (ground), text `#f1edf3`, margin 0. Centre one card vertically and horizontally; on a phone it sits 16 px from each edge.
|
||||||
|
- Card: max-width 420 px, padding 32 px (24 px under 480 px wide), background `#18151d` (surface), border 1 px `#3c3445`, radius 18 px.
|
||||||
|
- Top of the card: the hostname in `#cfc6d4`, 0.95 rem, weight 600, the only line that changes per host. Then the heading, 1.5 rem, weight 700, `#f1edf3`. Then body text, 1 rem, line-height 1.5, `#cfc6d4`.
|
||||||
|
- A 40 px stroke icon above the heading: a lock for the prompt, a clock for expired, a broken link for invalid, a cloud with a slash for not reachable. Expired and invalid icons in `#d99a35`; not reachable in `#e2683a`; the lock in `#e0a3dc`.
|
||||||
|
- Password field: label "Password" above it, `#cfc6d4` 0.9 rem. Field height 48 px, background `#0c0b0f`, border 1 px `#7d7189`, radius 10 px, text `#f1edf3`. Focus: border `#e0a3dc` plus a 4 px ring `rgba(224,163,220,0.16)`. `autocomplete="current-password"`, `autofocus`.
|
||||||
|
- Primary button "Open": full width, 48 px high, radius 12 px. Fill: gradient top to bottom `#8d3b89` → `#76306f` 55% → `#5c2257`. Edge 1 px `#c77cc1`; label `#ffffff`, weight 700. Focus ring `#f2c9ee`.
|
||||||
|
- Error line under the field (wrong password, too many tries): `#e2683a`, 0.92 rem, with a small ring icon, announced with `role="alert"`. Never colour alone; the words carry it.
|
||||||
|
- Secondary link "Have an account? Sign in": `#e0a3dc`, underlined, 44 px tall hit area. It points to the host root without `?share=`.
|
||||||
|
- "Try again" on the not-reachable page: an outline button (border `#7d7189`, text `#f1edf3`), as a plain link to the same URL.
|
||||||
|
- Footer under the card, outside it: "IANITOR DOMI" in `#a99eb1`, 0.72 rem, letter-spacing 0.2em, uppercase. Small and plain; no other branding.
|
||||||
|
|
||||||
|
**Copy, exactly**
|
||||||
|
|
||||||
|
Password prompt:
|
||||||
|
> photos.home.example
|
||||||
|
> **This link is protected**
|
||||||
|
> Someone shared photos.home.example with you. Enter the password they gave you.
|
||||||
|
> Password [__________]
|
||||||
|
> [ Open ]
|
||||||
|
> The link works until 14 November 2026.
|
||||||
|
|
||||||
|
Wrong password: the same page, with "That password is not right. Check it with the person who sent the link." under the field, which comes back empty.
|
||||||
|
Too many tries: the same page, with "Too many tries. Wait a minute, then try again." The Open button is disabled for that response.
|
||||||
|
|
||||||
|
Link expired:
|
||||||
|
> photos.home.example
|
||||||
|
> **This link has expired**
|
||||||
|
> It worked until 14 November 2026. Ask the person who sent it for a new one.
|
||||||
|
> Have an account? Sign in
|
||||||
|
|
||||||
|
Link no longer works:
|
||||||
|
> photos.home.example
|
||||||
|
> **This link no longer works**
|
||||||
|
> It may have been stopped, or not copied in full. Ask the person who sent it for a new one.
|
||||||
|
> Have an account? Sign in
|
||||||
|
|
||||||
|
Not reachable (any host, shared or not; the main screen points to it):
|
||||||
|
> photos.home.example
|
||||||
|
> **This site is not reachable right now**
|
||||||
|
> The service behind this address is not answering. It is not your connection. Try again in a few minutes.
|
||||||
|
> [ Try again ]
|
||||||
|
|
||||||
|
## 5. Gaps, and what I recommend
|
||||||
|
|
||||||
|
| # | Gap | Recommendation |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| G1 | Edge keeps health in memory with no way out [C: edge/src/health.rs keeps one healthy bit per upstream, no latency, no failure kind, no history]. The main screen, the watch and the revert reasons all need it. | Edge exposes a read-only status endpoint on a Unix socket only control can read. Per upstream: state, last check time, latency, failure kind, the last 5 results. Control caches it for `/overview`. Under Caddy, map the admin API's `/reverse_proxy/upstreams`; latency and failure kind are null there, and the UI hides them. |
|
||||||
|
| G2 | The boards show "degraded: slow, 2.8 s, limit is 2 s" and a history entry "health limit 2 s", but the schema has no latency limit (fixed 5 s timeout [C]). | No limit in v1. Degraded = some upstreams fail, or mixed results in the last 5 checks. I will correct the boards in Phase 3. |
|
||||||
|
| G3 | A host without a health check gives the 60 s watch nothing to judge, so "auto-kept or auto-reverted" is empty. A default check on / would revert apps that redirect to a login page (edge counts only 2xx as healthy [C]). | During the watch only, test each touched host without a health check by connecting and sending `GET /`; any answer below 500 counts as alive. Message `apply.kept.no_watch`. Don't add a default health check to new hosts. |
|
||||||
|
| G4 | ROADMAP doesn't say which hosts the watch judges. | Only the hosts the change touches; a host that was already down never triggers a revert. Check every 5 s during the watch. |
|
||||||
|
| G5 | Let's Encrypt issuance can take longer than 60 s and is not part of keep or revert. | Keep it out of the watch; report it as `hosts[].certificate` with its own messages and Try again. |
|
||||||
|
| G6 | Core validation errors are written per file in schema words (`{file}: upstream \`x\` is not usable: …`, "TOML") and carry no field path or stable code [C: core/src/error.rs]. | Add `code()`, `field()` and `params()` to `ValidationError`, using §3.1's codes and field paths. Keep the existing text as `detail`. The API maps code to the §3.1 message. |
|
||||||
|
| G7 | Under the Caddy fallback no one checks share tokens. Caddy cannot verify them, yet the engine popover promises "share links stay the same". | Compile share-link hosts for Caddy with `forward_auth` to a small validator on loopback, from the same core code. If that is too much for v1, show `share.engine_caddy` and change the popover copy. |
|
||||||
|
| G8 | ROADMAP revokes share links "by key rotation or a small deny list", but the key comes from systemd credentials, which control cannot rotate at runtime. A deny list that goes through the routes repo would make Stop wait 60 s and add a git commit. | Stop one link: a deny-list file outside git that edge reloads within 5 s, with no watch. Stop all: an `epoch` number inside every token and in the edge config; raising it ends every old link without changing the key. |
|
||||||
|
| G9 | "Optional password hash" inside a stateless token lets anyone holding the link guess the password offline. | The token carries only a "needs a password" flag. Edge checks `HMAC(key, link_id ‖ password)`, so guessing needs the server. Rate-limit in edge (§3.5). |
|
||||||
|
| G10 | Share link when links are off for the host: 4 clicks (handover c). Turning them on is an apply with a 60 s watch, and the clipboard needs a click after it. | Accept 4 for that path and say so in §4: "3 clicks, 4 if share links are off". The common path stays 3. |
|
||||||
|
| G11 | The link is minted when the dialog opens, so changing expiry or prefix would leave unused valid links behind. | `replaces` on the mint call stops the previous one (§1.5). |
|
||||||
|
| G12 | API token: copying is a 4th click (handover c). | Click 3 "Make and copy token" uses an async `ClipboardItem`; that needs the POST to answer in under 1 s. If Mark rejects writing a secret to the clipboard in the same click, accept 4. |
|
||||||
|
| G13 | Device cert: install is a 4th click (handover c), because approval in Custos is asynchronous. | Accept "3 to issue, +1 to install" in §4. No API change removes it. |
|
||||||
|
| G14 | The UI is identified by `Remote-User` from edge, but any local process can send that header to control on loopback. | The admin host's file sets a request header from a systemd-credential secret (an existing feature), and control requires it on every request. Alternatively, control listens on a Unix socket that only edge can reach. Plus the `X-Ianitor-UI` header against CSRF. |
|
||||||
|
| G15 | A device QR code must point to a download the tablet can reach, and control is loopback only. | A one-time download route on the admin host, served by edge to control, valid for 10 minutes and one use. Phase 3. |
|
||||||
|
| G16 | ROADMAP doesn't define Undo after an Undo. | "Revert the last kept commit" means a redo. Name it with `effect` (§2.3), so the button never surprises. |
|
||||||
|
| G17 | A reverted attempt is a commit plus a revert in git, but the UI shows one entry, and "Edit and try again" needs what was tried. | Control groups them into one history entry and keeps `attempted_host` for each reverted or failed change. |
|
||||||
|
| G18 | Engine switch: §1.6 and §3/§4 disagree (handover b). | `overview.engine` now, read only. The switch call waits on Mark's answer. |
|
||||||
|
| G19 | `websockets` defaults to true [C], so a "Websockets" chip would show on almost every row. | The UI shows a chip only when websockets are off ("No websockets"); the API needs no change. |
|
||||||
|
|
||||||
|
## 6. Where the Phase 2 API differs from this contract
|
||||||
|
|
||||||
|
Recorded by the Phase 2 implementation (branch `control/phase-2`). docs/api.md has curl
|
||||||
|
examples; `GET /api/v1/openapi.json` has every shape. Everything not listed here is built as
|
||||||
|
written above.
|
||||||
|
|
||||||
|
**Not built in Phase 2 (Phase 3 items):**
|
||||||
|
- G7: share links work only while Pingora serves. The Caddy JSON ignores `share_links`, so
|
||||||
|
under the fallback a share visitor gets the normal sign-in (fails closed). `share.engine_caddy`
|
||||||
|
is not emitted yet.
|
||||||
|
- G12, G13, G15 (clicks, device certificates and their downloads); §1.7, §1.8 and §3.6 (PKI).
|
||||||
|
- G14: control authenticates with API tokens only and trusts no `Remote-*` header; the UI in
|
||||||
|
Phase 3 needs the G14 mechanism (or a token) to call it.
|
||||||
|
- G18: `overview.engine` is read-only (`running: "pingora"`, `state: "running" | "stopped"`,
|
||||||
|
`fallback_ready: null`); no `POST /engine`.
|
||||||
|
- The "This site is not reachable right now" page (§4): edge still answers an unreachable
|
||||||
|
upstream with an empty `502`, exactly like Caddy, so the differential suite stays exact.
|
||||||
|
Serving the page needs the same page from Caddy's `handle_errors`.
|
||||||
|
- `overview.intermediate` is always `null`.
|
||||||
|
|
||||||
|
**Shapes and behaviour that differ:**
|
||||||
|
- Apply states: there is no `interrupted` state. An apply cut off by a control restart ends as
|
||||||
|
`reverted` with `reason.code = "apply.interrupted"`; one that was still queued ends as
|
||||||
|
`failed` with `apply.interrupted.queued`; a cancelled one as `failed` with `apply.cancelled`.
|
||||||
|
- A change identical to what is live is refused with `409 change.unchanged` instead of
|
||||||
|
becoming a no-op apply.
|
||||||
|
- `reason` is `{code, message, hostname, upstream, field, count, of, detail, params}`; an
|
||||||
|
apply also carries `errors[]`, the full `commit`, `effect` (undo), `actor` (token name) and
|
||||||
|
`attempted_host`. `push` is present only on kept applies; with no remote configured the
|
||||||
|
`push` step is `skipped`.
|
||||||
|
- `apply.kept` says "Health checks passed for {seconds} s." only; the push result is in
|
||||||
|
`push` / `repo`, not in that sentence. Extra codes: `apply.kept.no_watch` (host without a
|
||||||
|
health check), `apply.kept.removed`, `apply.kept.no_edge` (dev mode without a proxy),
|
||||||
|
`apply.reverted.no_answer`, `apply.reverted.edge_lost` (edge restarted or vanished during
|
||||||
|
the watch), `apply.failed.edge_unreachable`.
|
||||||
|
- The watch: touched hosts are probed every `watch_every_secs` (5 s by default). A touched host
|
||||||
|
is reverted when every one of its upstreams failed its last 3 checks, or none passed its
|
||||||
|
last check at the end; hosts that were already `down` before the change are not judged.
|
||||||
|
- `undo.blocked = undo.watching` only while an Undo itself is running; any other running apply
|
||||||
|
just queues the Undo.
|
||||||
|
- `GET /tokens` lists `id`; the id is the non-secret first part of the token
|
||||||
|
(`ian_<id>_<secret>`), so it is a prefix of the token string, but reveals nothing of the
|
||||||
|
secret. `POST /tokens` takes `{name?, expires_in_days?, never_expires?}`.
|
||||||
|
- `GET /history` entries have `reason_short` as the last word of the reason code (e.g.
|
||||||
|
"server error"), and paging uses `before=<change_id>` with `next_before` in the answer.
|
||||||
|
`GET /history/{id}` returns the full apply.
|
||||||
|
- `GET /history/{id}/restore-preview` field keys are `hostname`, `upstreams`, `tls`, `auth`,
|
||||||
|
`websockets`, `share_links`, `access_log`, `health_check.path`,
|
||||||
|
`health_check.interval_secs` and `headers`; it also has `blocked` (`restore.same`,
|
||||||
|
`restore.not_kept`).
|
||||||
|
- Share-link mint answers include `warning` (`host.share.no_signin`) for a host without
|
||||||
|
sign-in. The token is in `?share=`; edge only takes values starting `ish1.`, so an
|
||||||
|
upstream's own `share` parameter still works. The password page's "too many tries" answer
|
||||||
|
is `429`. For a password link the expired page is decided from the token's (unproven) date,
|
||||||
|
because nothing in the token can be proven before the password is given.
|
||||||
|
- `overview.site.acme_configured` is always `true` (Let's Encrypt is the default issuer);
|
||||||
|
extra fields `overview.rev`, `overview.health_error` and `site.share_links_available`.
|
||||||
|
- Health: one admin Unix socket (mode 0660) carries both the read-only `GET /v1/status` and
|
||||||
|
control's reload/trial calls, instead of a separate read-only socket. Edge keeps the last 5
|
||||||
|
results per upstream; `health.since` is tracked by control and restarts with it.
|
||||||
|
- `Idempotency-Key`s are remembered in memory for 24 h; a control restart forgets them. A
|
||||||
|
retry while the first request is still running gets `409 request.in_progress`; with 2,000
|
||||||
|
keys held, a new key gets `429 rate.limited`.
|
||||||
|
- Share links: at most 2,000 active links (`409 share.too_many`). A token in `?share=` on a
|
||||||
|
host without share links is removed before the request goes on.
|
||||||
|
- Wrong share passwords are also limited to 20 a minute per visitor network, whatever the
|
||||||
|
link; when the throttle's table is full, new visitors wait a minute rather than anyone's
|
||||||
|
count being forgotten.
|
||||||
|
- Extra error codes: `change.unchanged`, `host.hostname.mismatch`, `host.upstream.host_name`,
|
||||||
|
`request.*`, `repo.unexpected_file`, `repo.no_remote`, `share.unavailable`,
|
||||||
|
`share.not_found`, `share.replaces`, `share.password_long`, `share.too_many`,
|
||||||
|
`request.in_progress`, `control.files_unwritten`, `token.not_found`, `token.name`,
|
||||||
|
`token.expiry`, `file.*`, `site.*` (problems in `ianitor.toml`).
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"name": "ianitor-domi",
|
||||||
|
"private": true,
|
||||||
|
"license": "MPL-2.0"
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
packages:
|
||||||
|
- "apps/*"
|
||||||
|
- "packages/*"
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[package]
|
||||||
|
name = "ianitor-diff"
|
||||||
|
description = "Differential tests: the same request corpus against Ianitor and Caddy."
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
ianitor-core.workspace = true
|
||||||
|
ianitor-edge.workspace = true
|
||||||
|
ianitor-testkit.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
rustls.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
ianitor-control = { path = "../../crates/control" }
|
||||||
|
|
||||||
|
[lints.rust]
|
||||||
|
unsafe_code = "forbid"
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,238 @@
|
|||||||
|
// 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 differential suite after every apply (ROADMAP §6 phase 2, "Done"): control applies a
|
||||||
|
//! sequence of changes to a routes repository; after each one, Ianitor runs the edge config
|
||||||
|
//! control wrote and Caddy runs the Caddy JSON control wrote, and the corpus (the cases for
|
||||||
|
//! hosts that exist at that point) must get the same answers from both.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy); run it in WSL2",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes};
|
||||||
|
use ianitor_control::engine::{Change, Control};
|
||||||
|
use ianitor_control::hostspec::HostSpec;
|
||||||
|
use ianitor_control::repo::{Repo, RouteTree};
|
||||||
|
use ianitor_diff::{Env, case_host, run_cases, settle, start_caddy, start_edge};
|
||||||
|
use ianitor_testkit::proc::require_binary;
|
||||||
|
|
||||||
|
fn compile_of(o: &ianitor_core::compile::CompileOptions) -> Compile {
|
||||||
|
Compile {
|
||||||
|
http_listen: o.http_listen,
|
||||||
|
https_listen: o.https_listen,
|
||||||
|
cert_dir: o.cert_dir.clone(),
|
||||||
|
state_dir: o.state_dir.clone(),
|
||||||
|
access_log: o.access_log.clone(),
|
||||||
|
caddy_credentials_dir: o.caddy_credentials_dir.clone(),
|
||||||
|
caddy_admin: o.caddy_admin,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait_free(addrs: &[SocketAddr]) {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(15);
|
||||||
|
while addrs
|
||||||
|
.iter()
|
||||||
|
.any(|a| std::net::TcpStream::connect(a).is_ok())
|
||||||
|
&& Instant::now() < deadline
|
||||||
|
{
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn apply(ctl: &Control, change: Change) {
|
||||||
|
let rec = ctl
|
||||||
|
.submit(change, None, "diff")
|
||||||
|
.unwrap_or_else(|f| panic!("{f:?}"));
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(30);
|
||||||
|
loop {
|
||||||
|
let r = ctl.record(&rec.id).unwrap();
|
||||||
|
if !r.is_active() {
|
||||||
|
assert_eq!(r.state, "kept", "{} : {:?}", r.summary, r.reason);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
assert!(Instant::now() < deadline, "apply did not finish");
|
||||||
|
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spec(env: &Env, name: &str) -> HostSpec {
|
||||||
|
let (_, text) = env
|
||||||
|
.hosts
|
||||||
|
.iter()
|
||||||
|
.find(|(p, _)| p == &format!("hosts/{name}.toml"))
|
||||||
|
.unwrap();
|
||||||
|
HostSpec::from_toml(text).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn the_diff_suite_is_green_after_every_apply() {
|
||||||
|
let Some(caddy_bin) = require_binary("caddy") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let env = Env::start().await;
|
||||||
|
let edge_opts = env.options("edge");
|
||||||
|
let caddy_opts = env.options("caddy");
|
||||||
|
let d = |p: &str| env.dir.join(p);
|
||||||
|
for p in ["ctl-state", "ctl-edge", "ctl-caddy"] {
|
||||||
|
std::fs::create_dir_all(d(p)).unwrap();
|
||||||
|
}
|
||||||
|
let cfg = Config {
|
||||||
|
listen: "127.0.0.1:1".parse().unwrap(),
|
||||||
|
allowed_hosts: Vec::new(),
|
||||||
|
state_dir: d("ctl-state"),
|
||||||
|
credentials_dir: Some(d("creds")),
|
||||||
|
git: PathBuf::from("git"),
|
||||||
|
watch_secs: 1,
|
||||||
|
watch_every_secs: 1,
|
||||||
|
trial_margin_secs: 1,
|
||||||
|
health_poll_secs: 1,
|
||||||
|
routes: Routes {
|
||||||
|
repo: d("routes.git"),
|
||||||
|
branch: "main".into(),
|
||||||
|
remote: None,
|
||||||
|
remote_name: "Gitea".into(),
|
||||||
|
push_username: "ianitor".into(),
|
||||||
|
push_credential: None,
|
||||||
|
},
|
||||||
|
// No edge attached: control writes both files, and each file is tested below.
|
||||||
|
edge: Edge {
|
||||||
|
config: d("ctl-edge/edge.json"),
|
||||||
|
trial: None,
|
||||||
|
admin_socket: None,
|
||||||
|
share_revocations: d("ctl-edge/share-revocations.json"),
|
||||||
|
},
|
||||||
|
caddy: Caddy {
|
||||||
|
config: d("ctl-caddy/caddy.json"),
|
||||||
|
},
|
||||||
|
compile: compile_of(&edge_opts),
|
||||||
|
compile_caddy: Some(compile_of(&caddy_opts)),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Start from the site file and every host except three; then a sequence of applies
|
||||||
|
// ends at the full diff routes.
|
||||||
|
let later = ["hc.test", "hcdown.test", "rr.test"];
|
||||||
|
let repo = Repo::open_seeded(
|
||||||
|
&cfg.git,
|
||||||
|
&cfg.routes.repo,
|
||||||
|
&cfg.state_dir,
|
||||||
|
"main",
|
||||||
|
&env.site,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let head = repo.head_required().unwrap();
|
||||||
|
let mut tree: RouteTree = (*repo.tree(&head).unwrap()).clone();
|
||||||
|
for (p, c) in &env.hosts {
|
||||||
|
if !later.iter().any(|l| p == &format!("hosts/{l}.toml")) {
|
||||||
|
tree.files.insert(p.clone(), c.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let t = repo.write_tree(&tree, None).unwrap();
|
||||||
|
let c = repo.commit(&t, &[&head], "Diff routes", "test").unwrap();
|
||||||
|
repo.update_ref(&c, Some(&head)).unwrap();
|
||||||
|
drop(repo);
|
||||||
|
|
||||||
|
let ctl = Control::open(cfg.clone()).await.unwrap();
|
||||||
|
tokio::spawn(ctl.clone().worker());
|
||||||
|
|
||||||
|
let steps: Vec<(&str, Option<Change>)> = vec![
|
||||||
|
("start", None),
|
||||||
|
(
|
||||||
|
"add hc.test",
|
||||||
|
Some(Change::Put {
|
||||||
|
spec: spec(&env, "hc.test"),
|
||||||
|
create: true,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"add hcdown.test",
|
||||||
|
Some(Change::Put {
|
||||||
|
spec: spec(&env, "hcdown.test"),
|
||||||
|
create: true,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"remove nows.test",
|
||||||
|
Some(Change::Delete {
|
||||||
|
hostname: "nows.test".into(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"add rr.test",
|
||||||
|
Some(Change::Put {
|
||||||
|
spec: spec(&env, "rr.test"),
|
||||||
|
create: true,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"restore nows.test",
|
||||||
|
Some(Change::Put {
|
||||||
|
spec: spec(&env, "nows.test"),
|
||||||
|
create: true,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let all_hosts: Vec<String> = env
|
||||||
|
.model
|
||||||
|
.hosts()
|
||||||
|
.iter()
|
||||||
|
.map(|h| h.hostname.to_string())
|
||||||
|
.collect();
|
||||||
|
let mut ran = 0;
|
||||||
|
for (label, change) in steps {
|
||||||
|
if let Some(ch) = change {
|
||||||
|
apply(&ctl, ch).await;
|
||||||
|
}
|
||||||
|
let edge_text = std::fs::read_to_string(&cfg.edge.config).unwrap();
|
||||||
|
let caddy_text = std::fs::read_to_string(&cfg.caddy.config).unwrap();
|
||||||
|
let present: Vec<String> = {
|
||||||
|
let v: serde_json::Value = serde_json::from_str(&edge_text).unwrap();
|
||||||
|
v["hosts"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|h| h["hostname"].as_str().unwrap().to_owned())
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
{
|
||||||
|
let ianitor = start_edge(&env, "ianitor", &edge_text);
|
||||||
|
let caddy = start_caddy(&env, "caddy", &caddy_bin, &caddy_text);
|
||||||
|
settle().await;
|
||||||
|
// Cases for hosts that exist now, plus the ones about unknown hosts.
|
||||||
|
let report = run_cases(&ianitor, &caddy, env.roots(), |c| {
|
||||||
|
let h = case_host(c);
|
||||||
|
present.contains(&h) || !all_hosts.contains(&h)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
println!("{}", report.render(&format!("after: {label}")));
|
||||||
|
assert!(report.outcomes.len() >= 5, "{label}: too few cases");
|
||||||
|
assert!(report.mismatches().is_empty(), "{}", report.render(label));
|
||||||
|
ran += report.outcomes.len();
|
||||||
|
}
|
||||||
|
wait_free(&[
|
||||||
|
edge_opts.https_listen,
|
||||||
|
edge_opts.http_listen,
|
||||||
|
caddy_opts.https_listen,
|
||||||
|
caddy_opts.http_listen,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
// The last step is the full routes: every corpus case ran there.
|
||||||
|
assert!(ran > ianitor_diff::corpus().len());
|
||||||
|
let records = ctl.records();
|
||||||
|
assert_eq!(records.iter().filter(|r| r.state == "kept").count(), 5);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
// 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 differential suite (ROADMAP §5 layer 1). Needs the `caddy` binary on PATH (or
|
||||||
|
//! `$IANITOR_CADDY_BIN`); without it the tests fail unless `IANITOR_ALLOW_SKIP=1`.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
#[test]
|
||||||
|
fn skipped_on_windows() {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
|
||||||
|
file!()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod unix {
|
||||||
|
use ianitor_diff::{
|
||||||
|
Env, break_caddy, break_edge, compile_pair, corpus, run_corpus, settle, start_caddy,
|
||||||
|
start_edge,
|
||||||
|
};
|
||||||
|
use ianitor_testkit::proc::require_binary;
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn ianitor_and_caddy_answer_the_corpus_identically() {
|
||||||
|
let Some(caddy_bin) = require_binary("caddy") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
corpus().len() >= 20,
|
||||||
|
"the seed corpus has at least 20 requests"
|
||||||
|
);
|
||||||
|
let env = Env::start().await;
|
||||||
|
let (edge_cfg, caddy_cfg) = compile_pair(&env);
|
||||||
|
let ianitor = start_edge(&env, "ianitor", &edge_cfg);
|
||||||
|
let caddy = start_caddy(&env, "caddy", &caddy_bin, &caddy_cfg);
|
||||||
|
settle().await;
|
||||||
|
|
||||||
|
let report = run_corpus(&ianitor, &caddy, env.roots()).await;
|
||||||
|
println!("{}", report.render("Ianitor vs Caddy"));
|
||||||
|
let statuses: Vec<u16> = report.outcomes.iter().map(|o| o.ianitor.status).collect();
|
||||||
|
assert!(
|
||||||
|
!statuses.contains(&0),
|
||||||
|
"every case got an answer: {statuses:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
report.mismatches().is_empty(),
|
||||||
|
"{}",
|
||||||
|
report.render("Ianitor vs Caddy")
|
||||||
|
);
|
||||||
|
|
||||||
|
// The corpus really exercises the interesting paths (and not, say, 404 everywhere).
|
||||||
|
for wanted in [101, 200, 204, 302, 308, 401, 403, 404, 500, 502, 503] {
|
||||||
|
assert!(
|
||||||
|
statuses.contains(&wanted),
|
||||||
|
"corpus covers status {wanted}: {statuses:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
async fn a_deliberately_broken_compiler_is_caught() {
|
||||||
|
let Some(caddy_bin) = require_binary("caddy") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let env = Env::start().await;
|
||||||
|
let (edge_cfg, caddy_cfg) = compile_pair(&env);
|
||||||
|
let (edge_cfg2, caddy_cfg2) = compile_pair(&env);
|
||||||
|
|
||||||
|
let ianitor = start_edge(&env, "ianitor", &edge_cfg);
|
||||||
|
let broken_caddy = start_caddy(&env, "caddy-broken", &caddy_bin, &break_caddy(&caddy_cfg));
|
||||||
|
let caddy = start_caddy(&env, "caddy", &caddy_bin, &caddy_cfg2);
|
||||||
|
let broken_ianitor = start_edge(&env, "ianitor-broken", &break_edge(&edge_cfg2));
|
||||||
|
settle().await;
|
||||||
|
|
||||||
|
let r1 = run_corpus(&ianitor, &broken_caddy, env.roots()).await;
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
r1.render("Ianitor vs Caddy with response header rules dropped")
|
||||||
|
);
|
||||||
|
let diff1: Vec<&str> = r1.mismatches().iter().map(|o| o.name).collect();
|
||||||
|
assert!(!diff1.is_empty(), "broken Caddy compiler was not detected");
|
||||||
|
assert!(diff1.contains(&"plain GET"), "{diff1:?}");
|
||||||
|
|
||||||
|
let r2 = run_corpus(&broken_ianitor, &caddy, env.roots()).await;
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
r2.render("Ianitor with request header rules dropped vs Caddy")
|
||||||
|
);
|
||||||
|
let diff2: Vec<&str> = r2.mismatches().iter().map(|o| o.name).collect();
|
||||||
|
assert!(!diff2.is_empty(), "broken edge compiler was not detected");
|
||||||
|
assert!(diff2.contains(&"request header overwritten"), "{diff2:?}");
|
||||||
|
assert!(
|
||||||
|
diff2.contains(&"secret header cannot be preset"),
|
||||||
|
"{diff2:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
[package]
|
||||||
|
name = "ianitor-testkit"
|
||||||
|
description = "Shared test fixtures: test CA, upstreams, a mock Authelia, TLS/websocket clients, process helpers."
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tokio.workspace = true
|
||||||
|
bytes.workspace = true
|
||||||
|
http.workspace = true
|
||||||
|
hyper.workspace = true
|
||||||
|
hyper-util.workspace = true
|
||||||
|
http-body-util.workspace = true
|
||||||
|
rustls.workspace = true
|
||||||
|
rustls-pki-types.workspace = true
|
||||||
|
tokio-rustls.workspace = true
|
||||||
|
rcgen.workspace = true
|
||||||
|
tokio-tungstenite.workspace = true
|
||||||
|
futures-util.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
|
||||||
|
[lints.rust]
|
||||||
|
unsafe_code = "forbid"
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
// 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 mock of Authelia's ForwardAuth endpoint (`GET /api/authz/forward-auth`), following
|
||||||
|
//! Authelia's proxy-authorization guide: the proxy must send X-Forwarded-Method, -Proto, -Host
|
||||||
|
//! and -URI; a 2xx answer allows the request and carries Remote-User, Remote-Groups,
|
||||||
|
//! Remote-Email and Remote-Name; anything else is returned to the client as is.
|
||||||
|
//!
|
||||||
|
//! Decisions of the mock (the real Authelia decides from its access-control rules):
|
||||||
|
//! - `Authorization: Bearer good` → 200 with identity; any other Authorization → 401 + WWW-Authenticate
|
||||||
|
//! - cookie `authelia_session=good` → 200 with identity; `nameless` → 200 without identity;
|
||||||
|
//! `forbidden` → 403
|
||||||
|
//! - misbehaving answers, by cookie: `continue-ok` (100 Continue, then 200), `continue-xN`
|
||||||
|
//! (N × 102 Processing, then 200), `big-ok` /
|
||||||
|
//! `big-deny` (200 / 401 with a 5 MB body), `truncated-ok` (200 whose body is cut short),
|
||||||
|
//! `switch` (101 Switching Protocols), `hang` (never answers)
|
||||||
|
//! - otherwise GET/HEAD → 302 to the portal with `rd`, other methods → 401
|
||||||
|
//!
|
||||||
|
//! Every answer says in `x-sent-content-type` which Content-Type the mock sent (or `none`).
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
use crate::raw::{RawServer, Reply, response};
|
||||||
|
use crate::upstream::Recorded;
|
||||||
|
|
||||||
|
pub const PATH: &str = "/api/authz/forward-auth";
|
||||||
|
pub const PORTAL: &str = "https://auth.test/";
|
||||||
|
const IDENTITY: [(&str, &str); 4] = [
|
||||||
|
("Remote-User", "alice"),
|
||||||
|
("Remote-Groups", "admins,dev"),
|
||||||
|
("Remote-Email", "alice@example.org"),
|
||||||
|
("Remote-Name", "Alice Example"),
|
||||||
|
];
|
||||||
|
const BIG: usize = 5_000_000;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct MockAuthelia {
|
||||||
|
pub addr: SocketAddr,
|
||||||
|
server: RawServer,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn h(req: &Recorded, name: &str) -> Option<String> {
|
||||||
|
req.header(name)
|
||||||
|
.map(|v| String::from_utf8_lossy(v).into_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(status: u16, reason: &str, body: &str) -> Vec<u8> {
|
||||||
|
response(
|
||||||
|
status,
|
||||||
|
reason,
|
||||||
|
&[
|
||||||
|
("Content-Type", "text/plain; charset=utf-8"),
|
||||||
|
("X-Sent-Content-Type", "text/plain; charset=utf-8"),
|
||||||
|
],
|
||||||
|
body.as_bytes(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn allowed(identity: bool) -> Vec<u8> {
|
||||||
|
let mut hs: Vec<(&str, &str)> = vec![("X-Sent-Content-Type", "none")];
|
||||||
|
if identity {
|
||||||
|
hs.extend(IDENTITY);
|
||||||
|
}
|
||||||
|
response(200, "OK", &hs, b"")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decide(req: &Recorded) -> Reply {
|
||||||
|
if req.method != "GET" || req.path != PATH {
|
||||||
|
return Reply::Bytes(text(404, "Not Found", "404 page not found"));
|
||||||
|
}
|
||||||
|
let (Some(method), Some(proto), Some(host), Some(uri)) = (
|
||||||
|
h(req, "x-forwarded-method"),
|
||||||
|
h(req, "x-forwarded-proto"),
|
||||||
|
h(req, "x-forwarded-host"),
|
||||||
|
h(req, "x-forwarded-uri"),
|
||||||
|
) else {
|
||||||
|
return Reply::Bytes(text(400, "Bad Request", "missing X-Forwarded headers"));
|
||||||
|
};
|
||||||
|
if let Some(auth) = h(req, "authorization") {
|
||||||
|
return Reply::Bytes(if auth == "Bearer good" {
|
||||||
|
allowed(true)
|
||||||
|
} else {
|
||||||
|
response(
|
||||||
|
401,
|
||||||
|
"Unauthorized",
|
||||||
|
&[
|
||||||
|
("WWW-Authenticate", "Basic realm=\"Authorization Required\""),
|
||||||
|
("X-Sent-Content-Type", "none"),
|
||||||
|
],
|
||||||
|
b"401 Unauthorized",
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let cookie = h(req, "cookie").unwrap_or_default();
|
||||||
|
let session = cookie
|
||||||
|
.split(';')
|
||||||
|
.filter_map(|c| c.trim().strip_prefix("authelia_session="))
|
||||||
|
.next()
|
||||||
|
.unwrap_or("");
|
||||||
|
Reply::Bytes(match session {
|
||||||
|
"good" => allowed(true),
|
||||||
|
"nameless" => allowed(false),
|
||||||
|
"forbidden" => text(403, "Forbidden", "403 Forbidden"),
|
||||||
|
"continue-ok" => {
|
||||||
|
let mut b = b"HTTP/1.1 100 Continue\r\n\r\n".to_vec();
|
||||||
|
b.extend(allowed(true));
|
||||||
|
b
|
||||||
|
}
|
||||||
|
s if s.starts_with("continue-x") => {
|
||||||
|
// `continue-xN`: N informational heads (102 Processing), then 200.
|
||||||
|
let n: usize = s["continue-x".len()..].parse().unwrap_or(1);
|
||||||
|
let mut b = b"HTTP/1.1 102 Processing\r\n\r\n".repeat(n);
|
||||||
|
b.extend(allowed(true));
|
||||||
|
b
|
||||||
|
}
|
||||||
|
"big-ok" => {
|
||||||
|
let mut hs: Vec<(&str, &str)> = vec![("X-Sent-Content-Type", "none")];
|
||||||
|
hs.extend(IDENTITY);
|
||||||
|
response(200, "OK", &hs, &vec![b'a'; BIG])
|
||||||
|
}
|
||||||
|
"big-deny" => response(401, "Unauthorized", &[("X-Sent-Content-Type", "none")], &vec![b'a'; BIG]),
|
||||||
|
"truncated-ok" => {
|
||||||
|
b"HTTP/1.1 200 OK\r\nRemote-User: alice\r\nContent-Length: 1000\r\nConnection: close\r\n\r\nonly-a-bit".to_vec()
|
||||||
|
}
|
||||||
|
"switch" => b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n".to_vec(),
|
||||||
|
"hang" => return Reply::Hang,
|
||||||
|
_ if method == "GET" || method == "HEAD" => {
|
||||||
|
let rd = format!("{proto}://{host}{uri}");
|
||||||
|
let location = format!("{PORTAL}?rd={}", percent(&rd));
|
||||||
|
let body = format!("<a href=\"{location}\">302 Found</a>");
|
||||||
|
response(
|
||||||
|
302,
|
||||||
|
"Found",
|
||||||
|
&[
|
||||||
|
("Location", &location),
|
||||||
|
("Set-Cookie", "authelia_flow=1; Path=/; HttpOnly"),
|
||||||
|
("Content-Type", "text/html; charset=utf-8"),
|
||||||
|
("X-Sent-Content-Type", "text/html; charset=utf-8"),
|
||||||
|
],
|
||||||
|
body.as_bytes(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
_ => text(401, "Unauthorized", "401 Unauthorized"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MockAuthelia {
|
||||||
|
pub async fn start() -> MockAuthelia {
|
||||||
|
let server = RawServer::start(decide).await;
|
||||||
|
MockAuthelia {
|
||||||
|
addr: server.addr,
|
||||||
|
server,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `[forward_auth] url` for the site file.
|
||||||
|
pub fn url(&self) -> String {
|
||||||
|
format!("http://{}{PATH}", self.addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn requests(&self) -> Vec<Recorded> {
|
||||||
|
self.server.requests()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn percent(s: &str) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
for b in s.bytes() {
|
||||||
|
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
|
||||||
|
out.push(char::from(b));
|
||||||
|
} else {
|
||||||
|
out.push_str(&format!("%{b:02X}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Minimal HTTP/1.1 clients (plain, TLS with SNI, websocket) that send exactly the headers
|
||||||
|
//! they are given, so both engines see byte-identical requests.
|
||||||
|
|
||||||
|
use std::io;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use bytes::Bytes;
|
||||||
|
use futures_util::{SinkExt, StreamExt};
|
||||||
|
use http_body_util::{BodyExt, Full};
|
||||||
|
use hyper_util::rt::TokioIo;
|
||||||
|
use rustls::RootCertStore;
|
||||||
|
use rustls_pki_types::ServerName;
|
||||||
|
use tokio::io::{AsyncRead, AsyncWrite};
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
use tokio_rustls::TlsConnector;
|
||||||
|
use tokio_tungstenite::tungstenite;
|
||||||
|
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct Req {
|
||||||
|
pub method: String,
|
||||||
|
pub path: String,
|
||||||
|
/// Sent in this order; include `host` yourself.
|
||||||
|
pub headers: Vec<(String, String)>,
|
||||||
|
pub body: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Req {
|
||||||
|
pub fn get(host: &str, path: &str) -> Req {
|
||||||
|
Req::new("GET", host, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(method: &str, host: &str, path: &str) -> Req {
|
||||||
|
Req {
|
||||||
|
method: method.into(),
|
||||||
|
path: path.into(),
|
||||||
|
headers: vec![("host".into(), host.into())],
|
||||||
|
body: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn header(mut self, name: &str, value: &str) -> Req {
|
||||||
|
self.headers.push((name.into(), value.into()));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn body(mut self, body: &[u8]) -> Req {
|
||||||
|
self.body = body.to_vec();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Resp {
|
||||||
|
pub status: u16,
|
||||||
|
/// Lowercase names, in received order.
|
||||||
|
pub headers: Vec<(String, String)>,
|
||||||
|
pub body: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Resp {
|
||||||
|
pub fn header(&self, name: &str) -> Option<&str> {
|
||||||
|
self.headers
|
||||||
|
.iter()
|
||||||
|
.find(|(n, _)| n.eq_ignore_ascii_case(name))
|
||||||
|
.map(|(_, v)| v.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn header_all(&self, name: &str) -> Vec<&str> {
|
||||||
|
self.headers
|
||||||
|
.iter()
|
||||||
|
.filter(|(n, _)| n.eq_ignore_ascii_case(name))
|
||||||
|
.map(|(_, v)| v.as_str())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn text(&self) -> String {
|
||||||
|
String::from_utf8_lossy(&self.body).into_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||||
|
|
||||||
|
fn other(e: impl std::fmt::Display) -> io::Error {
|
||||||
|
io::Error::other(e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tls_connector(roots: Arc<RootCertStore>) -> TlsConnector {
|
||||||
|
crate::tls::install_crypto();
|
||||||
|
let mut cfg = rustls::ClientConfig::builder()
|
||||||
|
.with_root_certificates(roots)
|
||||||
|
.with_no_client_auth();
|
||||||
|
cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||||
|
TlsConnector::from(Arc::new(cfg))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn tls_stream(
|
||||||
|
addr: SocketAddr,
|
||||||
|
sni: &str,
|
||||||
|
roots: Arc<RootCertStore>,
|
||||||
|
) -> io::Result<tokio_rustls::client::TlsStream<TcpStream>> {
|
||||||
|
let tcp = TcpStream::connect(addr).await?;
|
||||||
|
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
|
||||||
|
tls_connector(roots).connect(name, tcp).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
|
||||||
|
io: S,
|
||||||
|
req: &Req,
|
||||||
|
) -> io::Result<Resp> {
|
||||||
|
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io))
|
||||||
|
.await
|
||||||
|
.map_err(other)?;
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = conn.await;
|
||||||
|
});
|
||||||
|
let mut b = hyper::Request::builder()
|
||||||
|
.method(req.method.as_str())
|
||||||
|
.uri(req.path.as_str());
|
||||||
|
for (n, v) in &req.headers {
|
||||||
|
b = b.header(n.as_str(), v.as_str());
|
||||||
|
}
|
||||||
|
let request = b
|
||||||
|
.body(Full::new(Bytes::from(req.body.clone())))
|
||||||
|
.map_err(other)?;
|
||||||
|
let resp = sender.send_request(request).await.map_err(other)?;
|
||||||
|
let status = resp.status().as_u16();
|
||||||
|
let headers = resp
|
||||||
|
.headers()
|
||||||
|
.iter()
|
||||||
|
.map(|(n, v)| {
|
||||||
|
(
|
||||||
|
n.as_str().to_owned(),
|
||||||
|
String::from_utf8_lossy(v.as_bytes()).into_owned(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let body = resp
|
||||||
|
.into_body()
|
||||||
|
.collect()
|
||||||
|
.await
|
||||||
|
.map_err(other)?
|
||||||
|
.to_bytes()
|
||||||
|
.to_vec();
|
||||||
|
Ok(Resp {
|
||||||
|
status,
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One request over a fresh TLS connection to `addr` with the given SNI.
|
||||||
|
pub async fn https(
|
||||||
|
addr: SocketAddr,
|
||||||
|
sni: &str,
|
||||||
|
roots: Arc<RootCertStore>,
|
||||||
|
req: &Req,
|
||||||
|
) -> io::Result<Resp> {
|
||||||
|
tokio::time::timeout(TIMEOUT, async {
|
||||||
|
let s = tls_stream(addr, sni, roots).await?;
|
||||||
|
send(s, req).await
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One request over a fresh plain TCP connection.
|
||||||
|
pub async fn http(addr: SocketAddr, req: &Req) -> io::Result<Resp> {
|
||||||
|
tokio::time::timeout(TIMEOUT, async {
|
||||||
|
let s = TcpStream::connect(addr).await?;
|
||||||
|
send(s, req).await
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum WsOutcome {
|
||||||
|
/// 101, the echoed message.
|
||||||
|
Upgraded {
|
||||||
|
status: u16,
|
||||||
|
headers: Vec<(String, String)>,
|
||||||
|
echo: String,
|
||||||
|
},
|
||||||
|
/// The upgrade was answered with a normal HTTP response.
|
||||||
|
Refused(Resp),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a websocket over TLS, send `message`, return the echo (or the refusal).
|
||||||
|
pub async fn websocket(
|
||||||
|
addr: SocketAddr,
|
||||||
|
sni: &str,
|
||||||
|
roots: Arc<RootCertStore>,
|
||||||
|
host: &str,
|
||||||
|
path: &str,
|
||||||
|
extra: &[(&str, &str)],
|
||||||
|
message: &str,
|
||||||
|
) -> io::Result<WsOutcome> {
|
||||||
|
tokio::time::timeout(TIMEOUT, async {
|
||||||
|
let s = tls_stream(addr, sni, roots).await?;
|
||||||
|
let mut request = format!("wss://{host}{path}")
|
||||||
|
.into_client_request()
|
||||||
|
.map_err(other)?;
|
||||||
|
for (n, v) in extra {
|
||||||
|
request.headers_mut().insert(
|
||||||
|
http::HeaderName::from_bytes(n.as_bytes()).map_err(other)?,
|
||||||
|
http::HeaderValue::from_str(v).map_err(other)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
match tokio_tungstenite::client_async(request, s).await {
|
||||||
|
Ok((mut ws, resp)) => {
|
||||||
|
let status = resp.status().as_u16();
|
||||||
|
let headers = resp
|
||||||
|
.headers()
|
||||||
|
.iter()
|
||||||
|
.map(|(n, v)| {
|
||||||
|
(
|
||||||
|
n.as_str().to_owned(),
|
||||||
|
String::from_utf8_lossy(v.as_bytes()).into_owned(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
ws.send(tungstenite::Message::text(message))
|
||||||
|
.await
|
||||||
|
.map_err(other)?;
|
||||||
|
let echo = match ws.next().await {
|
||||||
|
Some(Ok(m)) => m.into_text().map_err(other)?.to_string(),
|
||||||
|
other_msg => return Err(other(format!("no echo: {other_msg:?}"))),
|
||||||
|
};
|
||||||
|
let _ = ws.close(None).await;
|
||||||
|
Ok(WsOutcome::Upgraded {
|
||||||
|
status,
|
||||||
|
headers,
|
||||||
|
echo,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(tungstenite::Error::Http(resp)) => {
|
||||||
|
let status = resp.status().as_u16();
|
||||||
|
let headers = resp
|
||||||
|
.headers()
|
||||||
|
.iter()
|
||||||
|
.map(|(n, v)| {
|
||||||
|
(
|
||||||
|
n.as_str().to_owned(),
|
||||||
|
String::from_utf8_lossy(v.as_bytes()).into_owned(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let body = resp.body().clone().unwrap_or_default();
|
||||||
|
Ok(WsOutcome::Refused(Resp {
|
||||||
|
status,
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Err(e) => Err(other(e)),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "websocket timed out"))?
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Test fixtures shared by the edge integration tests and the differential harness.
|
||||||
|
//! Everything listens on 127.0.0.1 only. This is test code: panics are failures.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
|
pub mod authelia;
|
||||||
|
pub mod client;
|
||||||
|
pub mod more;
|
||||||
|
pub mod proc;
|
||||||
|
pub mod raw;
|
||||||
|
pub mod tls;
|
||||||
|
pub mod upstream;
|
||||||
|
|
||||||
|
/// FNV-1a 64-bit, used to compare bodies and secret values without echoing them.
|
||||||
|
pub fn fnv64(data: &[u8]) -> String {
|
||||||
|
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||||
|
for b in data {
|
||||||
|
h ^= u64::from(*b);
|
||||||
|
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||||
|
}
|
||||||
|
format!("{h:016x}")
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
//! Clients the phase 2 tests need: raw request bytes over TLS (for paths a URI type refuses,
|
||||||
|
//! like backslashes), a keep-alive HTTP/1.1 connection that is reused across requests, and
|
||||||
|
//! JSON over a Unix socket (edge's admin socket) or loopback TCP (the control API).
|
||||||
|
|
||||||
|
use std::io;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use bytes::Bytes;
|
||||||
|
use http_body_util::{BodyExt, Full};
|
||||||
|
use hyper_util::rt::TokioIo;
|
||||||
|
use rustls::RootCertStore;
|
||||||
|
use rustls_pki_types::ServerName;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
|
||||||
|
use crate::client::{Req, Resp, tls_connector};
|
||||||
|
|
||||||
|
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||||
|
|
||||||
|
fn other(e: impl std::fmt::Display) -> io::Error {
|
||||||
|
io::Error::other(e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse a complete HTTP/1.1 response (Content-Length, chunked or read-to-close).
|
||||||
|
pub fn parse_response(raw: &[u8]) -> io::Result<Resp> {
|
||||||
|
let end = raw
|
||||||
|
.windows(4)
|
||||||
|
.position(|w| w == b"\r\n\r\n")
|
||||||
|
.ok_or_else(|| other("no complete response head"))?;
|
||||||
|
let head = String::from_utf8_lossy(&raw[..end]).into_owned();
|
||||||
|
let mut lines = head.split("\r\n");
|
||||||
|
let status_line = lines.next().unwrap_or_default();
|
||||||
|
let status: u16 = status_line
|
||||||
|
.split(' ')
|
||||||
|
.nth(1)
|
||||||
|
.and_then(|s| s.parse().ok())
|
||||||
|
.ok_or_else(|| other(format!("bad status line {status_line:?}")))?;
|
||||||
|
let headers: Vec<(String, String)> = lines
|
||||||
|
.filter_map(|l| l.split_once(':'))
|
||||||
|
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().to_owned()))
|
||||||
|
.collect();
|
||||||
|
let mut body = raw[end + 4..].to_vec();
|
||||||
|
if headers
|
||||||
|
.iter()
|
||||||
|
.any(|(n, v)| n == "transfer-encoding" && v.eq_ignore_ascii_case("chunked"))
|
||||||
|
{
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut rest = &body[..];
|
||||||
|
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])
|
||||||
|
.split(';')
|
||||||
|
.next()
|
||||||
|
.unwrap_or("0")
|
||||||
|
.trim(),
|
||||||
|
16,
|
||||||
|
)
|
||||||
|
.map_err(other)?;
|
||||||
|
rest = &rest[p + 2..];
|
||||||
|
if size == 0 || rest.len() < size {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
out.extend_from_slice(&rest[..size]);
|
||||||
|
rest = &rest[(size + 2).min(rest.len())..];
|
||||||
|
}
|
||||||
|
body = out;
|
||||||
|
} else if let Some(len) = headers
|
||||||
|
.iter()
|
||||||
|
.find(|(n, _)| n == "content-length")
|
||||||
|
.and_then(|(_, v)| v.parse::<usize>().ok())
|
||||||
|
{
|
||||||
|
body.truncate(len);
|
||||||
|
}
|
||||||
|
Ok(Resp {
|
||||||
|
status,
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send `request` (complete raw bytes, which should ask for `Connection: close`) over a fresh
|
||||||
|
/// TLS connection and read until the server closes.
|
||||||
|
pub async fn https_raw(
|
||||||
|
addr: SocketAddr,
|
||||||
|
sni: &str,
|
||||||
|
roots: Arc<RootCertStore>,
|
||||||
|
request: &[u8],
|
||||||
|
) -> io::Result<Resp> {
|
||||||
|
tokio::time::timeout(TIMEOUT, async {
|
||||||
|
let tcp = TcpStream::connect(addr).await?;
|
||||||
|
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
|
||||||
|
let mut s = tls_connector(roots).connect(name, tcp).await?;
|
||||||
|
s.write_all(request).await?;
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
// A close_notify-less close is fine here.
|
||||||
|
let _ = s.read_to_end(&mut buf).await;
|
||||||
|
parse_response(&buf)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One HTTP/1.1 connection over TLS, reused for every request until it fails.
|
||||||
|
pub struct KeepAlive {
|
||||||
|
sender: hyper::client::conn::http1::SendRequest<Full<Bytes>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeepAlive {
|
||||||
|
pub async fn connect(
|
||||||
|
addr: SocketAddr,
|
||||||
|
sni: &str,
|
||||||
|
roots: Arc<RootCertStore>,
|
||||||
|
) -> io::Result<KeepAlive> {
|
||||||
|
let tcp = TcpStream::connect(addr).await?;
|
||||||
|
tcp.set_nodelay(true)?;
|
||||||
|
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
|
||||||
|
let s = tls_connector(roots).connect(name, tcp).await?;
|
||||||
|
let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(s))
|
||||||
|
.await
|
||||||
|
.map_err(other)?;
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = conn.await;
|
||||||
|
});
|
||||||
|
Ok(KeepAlive { sender })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send one request on this connection. An `Err` means the connection is gone.
|
||||||
|
pub async fn send(&mut self, req: &Req) -> io::Result<Resp> {
|
||||||
|
self.sender.ready().await.map_err(other)?;
|
||||||
|
let mut b = hyper::Request::builder()
|
||||||
|
.method(req.method.as_str())
|
||||||
|
.uri(req.path.as_str());
|
||||||
|
for (n, v) in &req.headers {
|
||||||
|
b = b.header(n.as_str(), v.as_str());
|
||||||
|
}
|
||||||
|
let request = b
|
||||||
|
.body(Full::new(Bytes::from(req.body.clone())))
|
||||||
|
.map_err(other)?;
|
||||||
|
let resp = tokio::time::timeout(TIMEOUT, self.sender.send_request(request))
|
||||||
|
.await
|
||||||
|
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||||
|
.map_err(other)?;
|
||||||
|
let status = resp.status().as_u16();
|
||||||
|
let headers = resp
|
||||||
|
.headers()
|
||||||
|
.iter()
|
||||||
|
.map(|(n, v)| {
|
||||||
|
(
|
||||||
|
n.as_str().to_owned(),
|
||||||
|
String::from_utf8_lossy(v.as_bytes()).into_owned(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let body = resp
|
||||||
|
.into_body()
|
||||||
|
.collect()
|
||||||
|
.await
|
||||||
|
.map_err(other)?
|
||||||
|
.to_bytes()
|
||||||
|
.to_vec();
|
||||||
|
Ok(Resp {
|
||||||
|
status,
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A JSON answer: status and parsed body (`Null` when the body is empty or not JSON).
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct JsonResp {
|
||||||
|
pub status: u16,
|
||||||
|
pub headers: Vec<(String, String)>,
|
||||||
|
pub json: serde_json::Value,
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl JsonResp {
|
||||||
|
pub fn header(&self, name: &str) -> Option<&str> {
|
||||||
|
self.headers
|
||||||
|
.iter()
|
||||||
|
.find(|(n, _)| n.eq_ignore_ascii_case(name))
|
||||||
|
.map(|(_, v)| v.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json_resp(r: Resp) -> JsonResp {
|
||||||
|
let text = String::from_utf8_lossy(&r.body).into_owned();
|
||||||
|
JsonResp {
|
||||||
|
status: r.status,
|
||||||
|
headers: r.headers,
|
||||||
|
json: serde_json::from_str(&text).unwrap_or(serde_json::Value::Null),
|
||||||
|
text,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn raw_request(
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
host: &str,
|
||||||
|
headers: &[(&str, &str)],
|
||||||
|
body: Option<&serde_json::Value>,
|
||||||
|
) -> Vec<u8> {
|
||||||
|
let body = body.map(|b| b.to_string()).unwrap_or_default();
|
||||||
|
let mut out = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
|
||||||
|
for (n, v) in headers {
|
||||||
|
out.push_str(&format!("{n}: {v}\r\n"));
|
||||||
|
}
|
||||||
|
if !body.is_empty() || method != "GET" {
|
||||||
|
out.push_str("Content-Type: application/json\r\n");
|
||||||
|
out.push_str(&format!("Content-Length: {}\r\n", body.len()));
|
||||||
|
}
|
||||||
|
out.push_str("\r\n");
|
||||||
|
out.push_str(&body);
|
||||||
|
out.into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A request over a Unix socket (edge's admin socket).
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub async fn unix_json(
|
||||||
|
socket: &std::path::Path,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
body: Option<&serde_json::Value>,
|
||||||
|
) -> io::Result<JsonResp> {
|
||||||
|
tokio::time::timeout(TIMEOUT, async {
|
||||||
|
let mut s = tokio::net::UnixStream::connect(socket).await?;
|
||||||
|
s.write_all(&raw_request(method, path, "localhost", &[], body))
|
||||||
|
.await?;
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
s.read_to_end(&mut buf).await?;
|
||||||
|
parse_response(&buf).map(json_resp)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A request over plain TCP (the control API on loopback), with extra headers.
|
||||||
|
pub async fn tcp_json(
|
||||||
|
addr: SocketAddr,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
headers: &[(&str, &str)],
|
||||||
|
body: Option<&serde_json::Value>,
|
||||||
|
) -> io::Result<JsonResp> {
|
||||||
|
tokio::time::timeout(Duration::from_secs(120), async {
|
||||||
|
let mut s = TcpStream::connect(addr).await?;
|
||||||
|
s.write_all(&raw_request(method, path, &addr.to_string(), headers, body))
|
||||||
|
.await?;
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
s.read_to_end(&mut buf).await?;
|
||||||
|
parse_response(&buf).map(json_resp)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send raw bytes over plain TCP and parse the answer (for malformed requests).
|
||||||
|
pub async fn tcp_raw(addr: SocketAddr, request: &[u8]) -> io::Result<Resp> {
|
||||||
|
tokio::time::timeout(TIMEOUT, async {
|
||||||
|
let mut s = TcpStream::connect(addr).await?;
|
||||||
|
s.write_all(request).await?;
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
s.read_to_end(&mut buf).await?;
|
||||||
|
parse_response(&buf)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
|
||||||
|
}
|
||||||
@@ -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/.
|
||||||
|
|
||||||
|
//! Ports, temporary directories, external binaries and child processes.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Child;
|
||||||
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
/// The kernel's ephemeral port range (ports it hands to `bind(:0)` and outgoing connections).
|
||||||
|
fn ephemeral_range() -> (u16, u16) {
|
||||||
|
std::fs::read_to_string("/proc/sys/net/ipv4/ip_local_port_range")
|
||||||
|
.ok()
|
||||||
|
.and_then(|s| {
|
||||||
|
let mut it = s.split_whitespace().filter_map(|x| x.parse::<u16>().ok());
|
||||||
|
Some((it.next()?, it.next()?))
|
||||||
|
})
|
||||||
|
.unwrap_or((32768, 60999))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A port on 127.0.0.1 that is free now, never handed out before by this process, and (where
|
||||||
|
/// possible) outside the ephemeral range, so the kernel does not give it to another socket
|
||||||
|
/// between this call and the server binding it, or while a server restarts on it.
|
||||||
|
pub fn free_port() -> u16 {
|
||||||
|
static GIVEN: std::sync::Mutex<Vec<u16>> = std::sync::Mutex::new(Vec::new());
|
||||||
|
let (low, high) = ephemeral_range();
|
||||||
|
let (from, to) = if low > 12_000 {
|
||||||
|
(10_000u32, u32::from(low))
|
||||||
|
} else {
|
||||||
|
(u32::from(high) + 1, 65_000)
|
||||||
|
};
|
||||||
|
let seed = std::process::id().wrapping_mul(2_654_435_761)
|
||||||
|
^ std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.subsec_nanos())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let span = to.saturating_sub(from).max(1);
|
||||||
|
let mut given = GIVEN.lock().unwrap();
|
||||||
|
for k in 0..span {
|
||||||
|
let port = (from + (seed.wrapping_add(k.wrapping_mul(7919))) % span) as u16;
|
||||||
|
if given.contains(&port) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() {
|
||||||
|
given.push(port);
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Everything outside the ephemeral range is taken: fall back to the kernel's choice.
|
||||||
|
loop {
|
||||||
|
let port = std::net::TcpListener::bind("127.0.0.1:0")
|
||||||
|
.unwrap()
|
||||||
|
.local_addr()
|
||||||
|
.unwrap()
|
||||||
|
.port();
|
||||||
|
if !given.contains(&port) {
|
||||||
|
given.push(port);
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn local(port: u16) -> SocketAddr {
|
||||||
|
SocketAddr::from(([127, 0, 0, 1], port))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wait until something accepts TCP connections on `addr`.
|
||||||
|
pub fn wait_for_port(addr: SocketAddr, timeout: Duration) -> bool {
|
||||||
|
let deadline = Instant::now() + timeout;
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A directory removed on drop (kept when `IANITOR_KEEP_TMP` is set, for debugging).
|
||||||
|
pub struct TempDir(PathBuf);
|
||||||
|
|
||||||
|
impl TempDir {
|
||||||
|
pub fn new(label: &str) -> TempDir {
|
||||||
|
static N: AtomicU32 = AtomicU32::new(0);
|
||||||
|
let p = std::env::temp_dir().join(format!(
|
||||||
|
"ianitor-{label}-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
N.fetch_add(1, Ordering::SeqCst)
|
||||||
|
));
|
||||||
|
let _ = std::fs::remove_dir_all(&p);
|
||||||
|
std::fs::create_dir_all(&p).unwrap();
|
||||||
|
TempDir(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn path(&self) -> &Path {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn join(&self, p: &str) -> PathBuf {
|
||||||
|
self.0.join(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn str(&self, p: &str) -> String {
|
||||||
|
self.join(p).to_string_lossy().into_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TempDir {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if std::env::var_os("IANITOR_KEEP_TMP").is_none() {
|
||||||
|
let _ = std::fs::remove_dir_all(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Locate an external tool: `$IANITOR_<NAME>_BIN`, then `$PATH`.
|
||||||
|
pub fn find_binary(name: &str) -> Option<PathBuf> {
|
||||||
|
let var = format!(
|
||||||
|
"IANITOR_{}_BIN",
|
||||||
|
name.to_ascii_uppercase().replace('-', "_")
|
||||||
|
);
|
||||||
|
if let Some(p) = std::env::var_os(&var) {
|
||||||
|
return Some(PathBuf::from(p));
|
||||||
|
}
|
||||||
|
let path = std::env::var_os("PATH")?;
|
||||||
|
std::env::split_paths(&path)
|
||||||
|
.map(|d| d.join(name))
|
||||||
|
.find(|p| p.is_file())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`find_binary`], but a missing tool fails the test, unless `IANITOR_ALLOW_SKIP=1`,
|
||||||
|
/// in which case the test prints SKIPPED and the caller returns early.
|
||||||
|
pub fn require_binary(name: &str) -> Option<PathBuf> {
|
||||||
|
match find_binary(name) {
|
||||||
|
Some(p) => Some(p),
|
||||||
|
None if std::env::var("IANITOR_ALLOW_SKIP").as_deref() == Ok("1") => {
|
||||||
|
eprintln!("SKIPPED: `{name}` not found (IANITOR_ALLOW_SKIP=1)");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let var = format!(
|
||||||
|
"IANITOR_{}_BIN",
|
||||||
|
name.to_ascii_uppercase().replace('-', "_")
|
||||||
|
);
|
||||||
|
panic!(
|
||||||
|
"`{name}` is needed for this test but was not found on PATH (or ${var}). \
|
||||||
|
In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Kills the child on drop.
|
||||||
|
pub struct ChildGuard(pub Child);
|
||||||
|
|
||||||
|
impl Drop for ChildGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = self.0.kill();
|
||||||
|
let _ = self.0.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
// 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 raw TCP HTTP/1.1 server that answers with scripted bytes: 1xx heads, truncated bodies,
|
||||||
|
//! hangs. One request per connection, then the connection is closed. The request body is
|
||||||
|
//! read and recorded (Content-Length or chunked), so tests can check what was sent.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
|
use crate::upstream::Recorded;
|
||||||
|
|
||||||
|
pub enum Reply {
|
||||||
|
/// Write these bytes, then close.
|
||||||
|
Bytes(Vec<u8>),
|
||||||
|
/// Accept, read the request, never answer (until the peer gives up).
|
||||||
|
Hang,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A complete response with Content-Length and `Connection: close`.
|
||||||
|
pub fn response(status: u16, reason: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
|
||||||
|
let mut out = format!("HTTP/1.1 {status} {reason}\r\n");
|
||||||
|
for (n, v) in headers {
|
||||||
|
out.push_str(&format!("{n}: {v}\r\n"));
|
||||||
|
}
|
||||||
|
out.push_str(&format!(
|
||||||
|
"Content-Length: {}\r\nConnection: close\r\n\r\n",
|
||||||
|
body.len()
|
||||||
|
));
|
||||||
|
let mut bytes = out.into_bytes();
|
||||||
|
bytes.extend_from_slice(body);
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
type Handler = dyn Fn(&Recorded) -> Reply + Send + Sync;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct RawServer {
|
||||||
|
pub addr: SocketAddr,
|
||||||
|
requests: Arc<Mutex<Vec<Recorded>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RawServer {
|
||||||
|
pub async fn start(handler: impl Fn(&Recorded) -> Reply + Send + Sync + 'static) -> RawServer {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let server = RawServer {
|
||||||
|
addr: listener.local_addr().unwrap(),
|
||||||
|
requests: Arc::default(),
|
||||||
|
};
|
||||||
|
let handler: Arc<Handler> = Arc::new(handler);
|
||||||
|
let requests = server.requests.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let Ok((mut stream, _)) = listener.accept().await else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let handler = handler.clone();
|
||||||
|
let requests = requests.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
let mut chunk = [0u8; 4096];
|
||||||
|
while !buf.windows(4).any(|w| w == b"\r\n\r\n") && buf.len() < 65536 {
|
||||||
|
match stream.read(&mut chunk).await {
|
||||||
|
Ok(0) | Err(_) => return,
|
||||||
|
Ok(n) => buf.extend_from_slice(&chunk[..n]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some(mut req) = parse(&buf) else { return };
|
||||||
|
let end = buf.windows(4).position(|w| w == b"\r\n\r\n").unwrap_or(0) + 4;
|
||||||
|
let rest = buf.split_off(end);
|
||||||
|
match read_body(&mut stream, &req, rest).await {
|
||||||
|
Some(body) => req.body = body,
|
||||||
|
None => return,
|
||||||
|
}
|
||||||
|
requests.lock().unwrap().push(req.clone());
|
||||||
|
match handler(&req) {
|
||||||
|
Reply::Bytes(b) => {
|
||||||
|
let _ = stream.write_all(&b).await;
|
||||||
|
let _ = stream.shutdown().await;
|
||||||
|
}
|
||||||
|
Reply::Hang => tokio::time::sleep(Duration::from_secs(600)).await,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
server
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn requests(&self) -> Vec<Recorded> {
|
||||||
|
self.requests.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn url(&self) -> String {
|
||||||
|
format!("http://{}", self.addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_BODY: usize = 16 << 20;
|
||||||
|
|
||||||
|
/// Read the request body that follows the head; `have` is what was read past the head.
|
||||||
|
/// `None` when the peer breaks off or sends malformed framing.
|
||||||
|
async fn read_body<S: AsyncReadExt + Unpin>(
|
||||||
|
stream: &mut S,
|
||||||
|
req: &Recorded,
|
||||||
|
mut have: Vec<u8>,
|
||||||
|
) -> Option<Vec<u8>> {
|
||||||
|
let mut chunk = [0u8; 4096];
|
||||||
|
let te = req
|
||||||
|
.header("transfer-encoding")
|
||||||
|
.map(|v| String::from_utf8_lossy(v).to_ascii_lowercase());
|
||||||
|
if te.as_deref().is_some_and(|t| t.contains("chunked")) {
|
||||||
|
let mut body = Vec::new();
|
||||||
|
let mut pos = 0;
|
||||||
|
loop {
|
||||||
|
// Need a full size line.
|
||||||
|
let line_end = loop {
|
||||||
|
if let Some(i) = have[pos..].windows(2).position(|w| w == b"\r\n") {
|
||||||
|
break pos + i;
|
||||||
|
}
|
||||||
|
let n = stream.read(&mut chunk).await.ok()?;
|
||||||
|
if n == 0 || have.len() > MAX_BODY {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
have.extend_from_slice(&chunk[..n]);
|
||||||
|
};
|
||||||
|
let line = std::str::from_utf8(&have[pos..line_end]).ok()?;
|
||||||
|
let size = usize::from_str_radix(line.split(';').next()?.trim(), 16).ok()?;
|
||||||
|
pos = line_end + 2;
|
||||||
|
if size == 0 {
|
||||||
|
// Trailers (if any) end with an empty line.
|
||||||
|
while !have[pos..].windows(2).any(|w| w == b"\r\n") {
|
||||||
|
let n = stream.read(&mut chunk).await.ok()?;
|
||||||
|
if n == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
have.extend_from_slice(&chunk[..n]);
|
||||||
|
}
|
||||||
|
return Some(body);
|
||||||
|
}
|
||||||
|
while have.len() < pos + size + 2 {
|
||||||
|
let n = stream.read(&mut chunk).await.ok()?;
|
||||||
|
if n == 0 || have.len() > MAX_BODY {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
have.extend_from_slice(&chunk[..n]);
|
||||||
|
}
|
||||||
|
body.extend_from_slice(&have[pos..pos + size]);
|
||||||
|
pos += size + 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let len: usize = match req.header("content-length") {
|
||||||
|
Some(v) => std::str::from_utf8(v).ok()?.trim().parse().ok()?,
|
||||||
|
None => 0,
|
||||||
|
};
|
||||||
|
if len > MAX_BODY {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
while have.len() < len {
|
||||||
|
let n = stream.read(&mut chunk).await.ok()?;
|
||||||
|
if n == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
have.extend_from_slice(&chunk[..n]);
|
||||||
|
}
|
||||||
|
have.truncate(len);
|
||||||
|
Some(have)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse(buf: &[u8]) -> Option<Recorded> {
|
||||||
|
let end = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
|
||||||
|
let head = std::str::from_utf8(&buf[..end]).ok()?;
|
||||||
|
let mut lines = head.split("\r\n");
|
||||||
|
let mut first = lines.next()?.split(' ');
|
||||||
|
let method = first.next()?.to_owned();
|
||||||
|
let target = first.next()?.to_owned();
|
||||||
|
let path = target.split('?').next().unwrap_or("").to_owned();
|
||||||
|
let headers = lines
|
||||||
|
.filter_map(|l| l.split_once(':'))
|
||||||
|
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().as_bytes().to_vec()))
|
||||||
|
.collect();
|
||||||
|
Some(Recorded {
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
headers,
|
||||||
|
body: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
|
||||||
|
async fn send(server: &RawServer, bytes: &[u8]) {
|
||||||
|
let mut s = TcpStream::connect(server.addr).await.unwrap();
|
||||||
|
s.write_all(bytes).await.unwrap();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let _ = s.read_to_end(&mut out).await;
|
||||||
|
assert!(
|
||||||
|
out.starts_with(b"HTTP/1.1 200"),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&out)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn records_request_bodies() {
|
||||||
|
let server = RawServer::start(|_| Reply::Bytes(response(200, "OK", &[], b""))).await;
|
||||||
|
send(&server, b"GET /none HTTP/1.1\r\nHost: x\r\n\r\n").await;
|
||||||
|
send(
|
||||||
|
&server,
|
||||||
|
b"POST /cl HTTP/1.1\r\nHost: x\r\nContent-Length: 11\r\n\r\nLEAKED-BODY",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
send(
|
||||||
|
&server,
|
||||||
|
b"POST /chunked HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n6\r\nLEAKED\r\n5;ext=1\r\n-BODY\r\n0\r\n\r\n",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let got: Vec<(String, Vec<u8>)> = server
|
||||||
|
.requests()
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| (r.path, r.body))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
got,
|
||||||
|
[
|
||||||
|
("/none".to_owned(), b"".to_vec()),
|
||||||
|
("/cl".to_owned(), b"LEAKED-BODY".to_vec()),
|
||||||
|
("/chunked".to_owned(), b"LEAKED-BODY".to_vec()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
// 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 throw-away test CA (stands in for the Domi CA, which arrives in phase 3).
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use rcgen::{
|
||||||
|
BasicConstraints, CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa,
|
||||||
|
Issuer, KeyPair, KeyUsagePurpose,
|
||||||
|
};
|
||||||
|
use rustls::RootCertStore;
|
||||||
|
use rustls_pki_types::CertificateDer;
|
||||||
|
use rustls_pki_types::pem::PemObject;
|
||||||
|
|
||||||
|
pub struct TestCa {
|
||||||
|
pub cert_pem: String,
|
||||||
|
issuer: Issuer<'static, KeyPair>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Leaf {
|
||||||
|
pub cert_pem: String,
|
||||||
|
pub key_pem: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestCa {
|
||||||
|
pub fn new(common_name: &str) -> Self {
|
||||||
|
let key = KeyPair::generate().unwrap();
|
||||||
|
let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
|
||||||
|
let mut dn = DistinguishedName::new();
|
||||||
|
dn.push(DnType::CommonName, common_name);
|
||||||
|
params.distinguished_name = dn;
|
||||||
|
params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
|
||||||
|
params.key_usages = vec![
|
||||||
|
KeyUsagePurpose::KeyCertSign,
|
||||||
|
KeyUsagePurpose::CrlSign,
|
||||||
|
KeyUsagePurpose::DigitalSignature,
|
||||||
|
];
|
||||||
|
let cert = params.self_signed(&key).unwrap();
|
||||||
|
TestCa {
|
||||||
|
cert_pem: cert.pem(),
|
||||||
|
issuer: Issuer::new(params, key),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A server certificate for the given DNS names (or IP literals).
|
||||||
|
pub fn issue(&self, names: &[&str]) -> Leaf {
|
||||||
|
let key = KeyPair::generate().unwrap();
|
||||||
|
let mut params =
|
||||||
|
CertificateParams::new(names.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>())
|
||||||
|
.unwrap();
|
||||||
|
let mut dn = DistinguishedName::new();
|
||||||
|
dn.push(DnType::CommonName, names.first().copied().unwrap_or("test"));
|
||||||
|
params.distinguished_name = dn;
|
||||||
|
params.is_ca = IsCa::NoCa;
|
||||||
|
params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
|
||||||
|
params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
|
||||||
|
let cert = params.signed_by(&key, &self.issuer).unwrap();
|
||||||
|
Leaf {
|
||||||
|
cert_pem: cert.pem(),
|
||||||
|
key_pem: key.serialize_pem(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn roots(&self) -> Arc<RootCertStore> {
|
||||||
|
roots_from_pem(&self.cert_pem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn roots_from_pem(pem: &str) -> Arc<RootCertStore> {
|
||||||
|
let mut roots = RootCertStore::empty();
|
||||||
|
for c in CertificateDer::pem_slice_iter(pem.as_bytes()) {
|
||||||
|
roots.add(c.unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
Arc::new(roots)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// rustls needs a process-wide crypto provider; install ring once.
|
||||||
|
pub fn install_crypto() {
|
||||||
|
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
// 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/.
|
||||||
|
|
||||||
|
//! Test upstreams on 127.0.0.1: an HTTP echo server and a websocket echo server.
|
||||||
|
|
||||||
|
use std::convert::Infallible;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::sync::atomic::{AtomicU16, AtomicUsize, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use bytes::Bytes;
|
||||||
|
use futures_util::{SinkExt, StreamExt};
|
||||||
|
use http_body_util::{BodyExt, Full, StreamBody, combinators::BoxBody};
|
||||||
|
use hyper::body::{Frame, Incoming};
|
||||||
|
use hyper::server::conn::http1;
|
||||||
|
use hyper::service::service_fn;
|
||||||
|
use hyper::{Request, Response};
|
||||||
|
use hyper_util::rt::TokioIo;
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
|
use crate::fnv64;
|
||||||
|
|
||||||
|
/// Request headers the echo server reports back (lowercase). Secret-carrying headers are
|
||||||
|
/// reported as a hash only, so a passing test never needs the value in a response body.
|
||||||
|
pub const ECHO_HEADERS: [&str; 13] = [
|
||||||
|
"host",
|
||||||
|
"x-remove-me-too",
|
||||||
|
"x-forwarded-for",
|
||||||
|
"x-forwarded-proto",
|
||||||
|
"x-forwarded-host",
|
||||||
|
"x-static",
|
||||||
|
"x-remove-me",
|
||||||
|
"x-client",
|
||||||
|
"remote-user",
|
||||||
|
"remote-groups",
|
||||||
|
"remote-email",
|
||||||
|
"remote-name",
|
||||||
|
"x-debug",
|
||||||
|
];
|
||||||
|
pub const HASHED_HEADERS: [&str; 2] = ["x-api-key", "authorization"];
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Recorded {
|
||||||
|
pub method: String,
|
||||||
|
pub path: String,
|
||||||
|
pub headers: Vec<(String, Vec<u8>)>,
|
||||||
|
pub body: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Recorded {
|
||||||
|
pub fn header(&self, name: &str) -> Option<&[u8]> {
|
||||||
|
self.headers
|
||||||
|
.iter()
|
||||||
|
.find(|(n, _)| n.eq_ignore_ascii_case(name))
|
||||||
|
.map(|(_, v)| v.as_slice())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Echo {
|
||||||
|
pub addr: SocketAddr,
|
||||||
|
pub name: String,
|
||||||
|
requests: Arc<Mutex<Vec<Recorded>>>,
|
||||||
|
/// Status answered on `/healthz`.
|
||||||
|
pub health: Arc<AtomicU16>,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Body = BoxBody<Bytes, Infallible>;
|
||||||
|
|
||||||
|
fn full(b: impl Into<Bytes>) -> Body {
|
||||||
|
Full::new(b.into()).boxed()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Echo {
|
||||||
|
pub async fn start(name: &str) -> Echo {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let echo = Echo {
|
||||||
|
addr: listener.local_addr().unwrap(),
|
||||||
|
name: name.to_owned(),
|
||||||
|
requests: Arc::default(),
|
||||||
|
health: Arc::new(AtomicU16::new(200)),
|
||||||
|
};
|
||||||
|
let e = echo.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let Ok((stream, _)) = listener.accept().await else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let e = e.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let svc = service_fn(move |req| {
|
||||||
|
let e = e.clone();
|
||||||
|
async move { Ok::<_, Infallible>(e.handle(req).await) }
|
||||||
|
});
|
||||||
|
let _ = http1::Builder::new()
|
||||||
|
.serve_connection(TokioIo::new(stream), svc)
|
||||||
|
.await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
echo
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn url(&self) -> String {
|
||||||
|
format!("http://{}", self.addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn requests(&self) -> Vec<Recorded> {
|
||||||
|
self.requests.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Requests other than health checks.
|
||||||
|
pub fn proxied(&self) -> Vec<Recorded> {
|
||||||
|
self.requests()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|r| r.path != "/healthz")
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear(&self) {
|
||||||
|
self.requests.lock().unwrap().clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every answer says in `x-sent-content-type` which Content-Type it carried (or `none`),
|
||||||
|
/// so the diff harness can tell what the engines added.
|
||||||
|
async fn handle(&self, req: Request<Incoming>) -> Response<Body> {
|
||||||
|
let mut resp = self.answer(req).await;
|
||||||
|
let sent = resp
|
||||||
|
.headers()
|
||||||
|
.get("content-type")
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| hyper::header::HeaderValue::from_static("none"));
|
||||||
|
resp.headers_mut().insert("x-sent-content-type", sent);
|
||||||
|
resp
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn answer(&self, req: Request<Incoming>) -> Response<Body> {
|
||||||
|
let (parts, body) = req.into_parts();
|
||||||
|
let body = body
|
||||||
|
.collect()
|
||||||
|
.await
|
||||||
|
.map(|b| b.to_bytes())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let path = parts.uri.path().to_owned();
|
||||||
|
let query = parts.uri.query().unwrap_or("").to_owned();
|
||||||
|
self.requests.lock().unwrap().push(Recorded {
|
||||||
|
method: parts.method.to_string(),
|
||||||
|
path: path.clone(),
|
||||||
|
headers: parts
|
||||||
|
.headers
|
||||||
|
.iter()
|
||||||
|
.map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec()))
|
||||||
|
.collect(),
|
||||||
|
body: body.to_vec(),
|
||||||
|
});
|
||||||
|
let base = |status: u16| {
|
||||||
|
Response::builder()
|
||||||
|
.status(status)
|
||||||
|
.header("x-powered-by", "echo")
|
||||||
|
.header("x-upstream", self.name.clone())
|
||||||
|
};
|
||||||
|
|
||||||
|
if path == "/healthz" {
|
||||||
|
let s = self.health.load(Ordering::SeqCst);
|
||||||
|
return base(s).body(full(format!("health {s}"))).unwrap();
|
||||||
|
}
|
||||||
|
if let Some(code) = path
|
||||||
|
.strip_prefix("/status/")
|
||||||
|
.and_then(|c| c.parse::<u16>().ok())
|
||||||
|
{
|
||||||
|
return base(code)
|
||||||
|
.header("content-type", "text/plain")
|
||||||
|
.body(full(format!("status {code}")))
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
if path == "/big" {
|
||||||
|
let n: usize = query
|
||||||
|
.strip_prefix("n=")
|
||||||
|
.and_then(|n| n.parse().ok())
|
||||||
|
.unwrap_or(1024)
|
||||||
|
.min(10 << 20);
|
||||||
|
return base(200)
|
||||||
|
.header("content-type", "application/octet-stream")
|
||||||
|
.body(full(vec![b'x'; n]))
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
if path == "/chunked" {
|
||||||
|
let chunks = ["first,", "second,", "third"]
|
||||||
|
.into_iter()
|
||||||
|
.map(|c| Ok::<_, Infallible>(Frame::data(Bytes::from_static(c.as_bytes()))));
|
||||||
|
let stream = futures_util::stream::iter(chunks);
|
||||||
|
return base(200)
|
||||||
|
.header("content-type", "text/plain")
|
||||||
|
.body(BodyExt::boxed(StreamBody::new(stream)))
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
if path == "/set-cookie" {
|
||||||
|
return base(200)
|
||||||
|
.header("set-cookie", "a=1; Path=/; HttpOnly")
|
||||||
|
.header("set-cookie", "b=2; Path=/; Secure")
|
||||||
|
.body(full("cookies"))
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
if path == "/reflect" {
|
||||||
|
// Copies one request header into the response: simulates an upstream that leaks.
|
||||||
|
let name = query.strip_prefix("h=").unwrap_or("x-api-key");
|
||||||
|
let mut b = base(200);
|
||||||
|
if let Some(v) = parts.headers.get(name) {
|
||||||
|
b = b.header("x-reflected", v.clone());
|
||||||
|
}
|
||||||
|
return b.body(full("reflected")).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut headers = serde_json::Map::new();
|
||||||
|
for h in ECHO_HEADERS {
|
||||||
|
if let Some(v) = parts.headers.get(h) {
|
||||||
|
headers.insert(
|
||||||
|
h.to_owned(),
|
||||||
|
String::from_utf8_lossy(v.as_bytes()).into_owned().into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for h in HASHED_HEADERS {
|
||||||
|
if let Some(v) = parts.headers.get(h) {
|
||||||
|
headers.insert(format!("{h}#fnv"), fnv64(v.as_bytes()).into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let json = serde_json::json!({
|
||||||
|
"upstream": self.name,
|
||||||
|
"method": parts.method.as_str(),
|
||||||
|
"path": path,
|
||||||
|
"query": query,
|
||||||
|
"body_len": body.len(),
|
||||||
|
"body_fnv": fnv64(&body),
|
||||||
|
"headers": headers,
|
||||||
|
});
|
||||||
|
base(200)
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(full(json.to_string()))
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Websocket echo upstream: answers the upgrade, then echoes every text/binary message.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct WsEcho {
|
||||||
|
pub addr: SocketAddr,
|
||||||
|
connections: Arc<AtomicUsize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WsEcho {
|
||||||
|
pub async fn start() -> WsEcho {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let ws = WsEcho {
|
||||||
|
addr: listener.local_addr().unwrap(),
|
||||||
|
connections: Arc::default(),
|
||||||
|
};
|
||||||
|
let conns = ws.connections.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let Ok((stream, _)) = listener.accept().await else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let conns = conns.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
conns.fetch_add(1, Ordering::SeqCst);
|
||||||
|
while let Some(Ok(msg)) = ws.next().await {
|
||||||
|
if msg.is_text() || msg.is_binary() {
|
||||||
|
if ws.send(msg).await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else if msg.is_close() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ws
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn url(&self) -> String {
|
||||||
|
format!("http://{}", self.addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn connections(&self) -> usize {
|
||||||
|
self.connections.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A port on 127.0.0.1 that nothing listens on.
|
||||||
|
pub fn closed_port() -> u16 {
|
||||||
|
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
l.local_addr().unwrap().port()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user