28 Commits

Author SHA1 Message Date
mnovak cee64dd462 [docs] Roadmap: Phase 1 status and handover 2026-11-07 16:46:25 +01:00
mnovak 0c42138d74 [edge] Lint: resolver tests at the end of runtime.rs 2026-11-07 16:42:45 +01:00
mnovak 27b0a165b2 [edge] Fetch: accept up to 1000 informational heads (Go has no count limit); KD-10 beyond 2026-11-07 16:41:41 +01:00
mnovak 8c04b0f4bd [edge] Upstreams: 3 s deadline on name lookups, 502 on timeout 2026-11-07 16:39:29 +01:00
mnovak ee8c304740 [tests] Mock Authelia: record request bodies (Content-Length and chunked) so body assertions can fail 2026-11-07 16:39:28 +01:00
mnovak ed2a166165 [repo] Hygiene: batched hook (300 files 1.7 s), narrower build/ and JWK rules, more key forms, bash-4 check 2026-11-07 16:33:13 +01:00
mnovak 2dfb0b8ecc [tests] Windows: Linux-only test targets report one explicit skip instead of zero tests 2026-11-07 15:58:14 +01:00
mnovak ecdba7775f [docs] Notes: tests/support in layout, forward-auth failure modes, bash hook self-test 2026-11-07 15:58:00 +01:00
mnovak a052c32b77 [repo] Hygiene: NUL-safe pre-commit hook, more key formats, 5,000,000-byte limit, QC bypass cases 2026-11-07 15:57:04 +01:00
mnovak bcf94928c9 [diff] Corpus: 57 cases, all headers compared, narrow named divergences, misbehaving-auth and Upgrade-token cases 2026-11-07 15:53:38 +01:00
mnovak a272e476b7 [edge] Fixes: skip 1xx, enforce auth timeout, resolve upstreams per connect, all Upgrade tokens, strip Remote-* 2026-11-07 15:48:18 +01:00
mnovak 60aee5d78a [core] Schema: reject wildcard header names, cap file size and upstreams, require <hostname>.toml 2026-11-07 15:44:09 +01:00
mnovak 58d0397875 [core] Tests first: wildcard headers, file name, size and upstream caps, identity stripping (red) 2026-11-07 15:42:25 +01:00
mnovak d42c178a13 [edge] Tests first: QC repros for 1xx, auth timeout, name resolution, Upgrade tokens, Remote-* stripping (red) 2026-11-07 15:36:00 +01:00
mnovak fd4b4a7775 [docs] Roadmap: answer open points 1, 2, 3 and 5; WSL note in CLAUDE.md 2026-11-07 15:09:41 +01:00
mnovak c50fcd5a5a [core] Compilers: TLS server name for IP upstreams is the IP literal 2026-11-07 15:09:41 +01:00
mnovak 6a7aafc859 [edge] ACME: end-to-end test against Pebble next to a Domi-cert host 2026-11-07 15:06:40 +01:00
mnovak e7fa5f57ec [tests] Lint: collapse nested ifs, format panic message 2026-11-07 15:03:08 +01:00
mnovak c14fb2dea6 [diff] Harness: 43-request corpus against Ianitor and Caddy, broken-compiler check 2026-11-07 15:02:09 +01:00
mnovak 17e1df8320 [edge] Proxy: Pingora data plane with SNI certs, forward-auth, header rules, health checks, ACME 2026-11-07 14:57:36 +01:00
mnovak 4fe041082d [edge] Tests first: secret never leaks, forward-auth denial never reaches upstream (red) 2026-11-07 14:48:06 +01:00
mnovak a94a242c79 [tests] Testkit: test CA, echo and websocket upstreams, mock Authelia, clients 2026-11-07 14:48:05 +01:00
mnovak a5823ba33d [core] Compilers: Pingora runtime config and Caddy JSON, golden files 2026-11-07 14:39:34 +01:00
mnovak ff087a14dd [core] Schema: host file model and validation with typed errors 2026-11-07 14:36:35 +01:00
mnovak 9176cc63a4 [core] Schema: tests first for validation and compiler determinism (red: 37+11 failing) 2026-11-07 14:34:33 +01:00
mnovak c1abe88688 [repo] Workspace: cargo workspace, MPL-2.0 license, control and web placeholders 2026-11-07 14:31:04 +01:00
mnovak 8f79ce042c [repo] Hygiene: .gitignore and pre-commit hook 2026-11-07 14:22:48 +01:00
mnovak 7e557f47ae [docs] Bootstrap: merge docs/bootstrap (PR #1) 2026-11-07 12:16:27 +01:00
61 changed files with 13708 additions and 3 deletions
+3
View File
@@ -0,0 +1,3 @@
* text=auto eol=lf
*.png binary
*.ico binary
+175
View File
@@ -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
+252
View File
@@ -0,0 +1,252 @@
#!/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'
mkdir -p "$WORK/../ianitor-hook-src.$$" && SRC="$WORK/../ianitor-hook-src.$$"
trap 'rm -rf "$WORK" "$SRC"' 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
View File
@@ -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
+6
View File
@@ -10,6 +10,7 @@ crates/control API, git routes repo, apply/rollback, share links, PKI flows. Lo
apps/web Svelte 5 (runes, TypeScript strict). A client of the API; no logic.
packages/ui shared dark Domi theme.
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.
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 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
- 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.
Generated
+3205
View File
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
[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.88"
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"
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
+373
View File
@@ -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.
+10
View File
@@ -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')\""
}
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "ianitor-control"
description = "Ianitor Domi control plane (API, routes repo, apply/rollback). Placeholder until phase 2."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ianitor-control"
path = "src/main.rs"
[lints]
workspace = true
+12
View File
@@ -0,0 +1,12 @@
// 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/.
//! Placeholder for ianitor-control (ROADMAP phase 2). It deliberately opens no socket.
fn main() {
println!(
"ianitor-control {}: placeholder. The control plane (API on 127.0.0.1) arrives in phase 2.",
env!("CARGO_PKG_VERSION")
);
}
+18
View File
@@ -0,0 +1,18 @@
[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
[lints]
workspace = true
+341
View File
@@ -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)
}
+85
View File
@@ -0,0 +1,85 @@
// 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,
})
.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() },
}
}
+129
View File
@@ -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)
}
+106
View File
@@ -0,0 +1,106 @@
// 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 = 1;
#[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,
}
+126
View File
@@ -0,0 +1,126 @@
// 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,
//! so the UI can show it as is.
use std::fmt;
/// 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: {hostname}.toml")]
FileNameMismatch { file: String, hostname: String },
#[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,
},
#[error("{file}: upstream `{url}` is listed twice")]
DuplicateUpstream { file: String, url: String },
#[error("{file}: secret `{secret}` is used but not declared in the site file")]
UndefinedSecret { file: String, secret: String },
#[error(
"{file}: response header `{header}` may not use a secret; secrets only go to upstreams"
)]
SecretInResponseHeader { file: String, header: 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 },
#[error("{file}: value for header `{header}` is not allowed: {reason}")]
InvalidHeaderValue {
file: String,
header: String,
reason: &'static str,
},
#[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")]
ProtectedHeader { file: String, header: String },
#[error("{file}: header `{header}` has more than one rule in the same list")]
DuplicateHeaderRule { file: String, header: String },
#[error("{file}: rule for header `{header}` is incomplete: {reason}")]
BadHeaderRule {
file: String,
header: String,
reason: &'static str,
},
#[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(),
}
}
/// 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
}
}
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 {}
+23
View File
@@ -0,0 +1,23 @@
// 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;
mod validate;
pub use error::{ValidationError, ValidationErrors};
pub use model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, Model, Scheme,
SecretName, Site, TlsMode, Upstream, UpstreamHost,
};
pub use validate::{SourceFile, load};
+234
View File
@@ -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",
];
+725
View File
@@ -0,0 +1,725 @@
// 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};
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 &copy_headers {
if !valid_header_name(h) {
errors.push(E::InvalidHeaderName {
file: file.to_owned(),
name: h.clone(),
});
} else if is_protected(h) {
errors.push(E::ProtectedHeader {
file: file.to_owned(),
header: h.clone(),
});
} 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: `hosts/<hostname>.toml`.
let base = file.rsplit(['/', '\\']).next().unwrap_or(file);
if base != format!("{}.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 u in raw.upstreams.iter().take(MAX_UPSTREAMS) {
match parse_url(u, false) {
Ok((up, _)) => {
if seen_upstreams.insert(up.clone()) {
upstreams.push(up);
} else {
errors.push(E::DuplicateUpstream {
file: f(),
url: u.clone(),
});
}
}
Err(reason) => errors.push(E::BadUpstreamUrl {
file: f(),
url: u.clone(),
reason,
}),
}
}
if upstreams.windows(2).any(|w| w[0].scheme != w[1].scheme) {
errors.push(E::BadUpstreamUrl {
file: f(),
url: raw.upstreams.join(", "),
reason: "all upstreams of a host must use the same scheme",
});
}
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, raw.request_headers, true, &identity, site, errors);
let response_headers = check_rules(file, raw.response_headers, false, &[], 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(
"path must start with '/' and contain only visible ASCII without '{', '}' or '#'",
));
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("interval_secs must be between 1 and 3600"));
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,
raw: Vec<RawRule>,
request: bool,
identity: &[String],
site: Option<&Site>,
errors: &mut Vec<E>,
) -> Vec<HeaderRule> {
let f = || file.to_owned();
let mut out = Vec::new();
let mut seen = BTreeSet::new();
for r in raw {
let header = r.name.clone();
if !valid_header_name(&r.name) {
errors.push(E::InvalidHeaderName {
file: f(),
name: r.name,
});
continue;
}
let lower = r.name.to_ascii_lowercase();
if is_protected(&r.name) || identity.contains(&lower) {
errors.push(E::ProtectedHeader { file: f(), header });
continue;
}
if !seen.insert(lower) {
errors.push(E::DuplicateHeaderRule { file: f(), header });
continue;
}
let bad = |reason| E::BadHeaderRule {
file: f(),
header: header.clone(),
reason,
};
match (r.action, r.value, r.secret) {
(RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }),
(RawAction::Remove, _, _) => errors.push(bad("remove takes no value or secret")),
(RawAction::Set, Some(_), Some(_)) => {
errors.push(bad("give either value or secret, not both"))
}
(RawAction::Set, None, None) => errors.push(bad("set needs a value or a secret")),
(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,
}),
},
(RawAction::Set, None, Some(s)) => {
if !request {
errors.push(E::SecretInResponseHeader { file: f(), header });
} else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) {
errors.push(E::UndefinedSecret {
file: f(),
secret: s,
});
} 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("an empty value is not allowed; use action = \"remove\"");
}
if v.len() > 4096 {
return Err("it is longer than 4096 characters");
}
if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) {
return Err("only visible ASCII characters and spaces are allowed");
}
if v.contains(['{', '}']) {
return Err("'{' and '}' are not allowed (they are placeholders in Caddy)");
}
if v.starts_with(' ') || v.ends_with(' ') {
return Err("it must not start or end with a space");
}
Ok(())
}
// ------------------------------------------------------------------ names and URLs
pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> {
if h.is_empty() {
return Err("it is empty");
}
if h.len() > 253 {
return Err("it is longer than 253 characters");
}
if h.parse::<IpAddr>().is_ok() || h.starts_with('[') {
return Err("IP addresses are not hostnames");
}
if h.contains('*') {
return Err("wildcards are not supported");
}
if h.ends_with('.') {
return Err("it must not end with a dot");
}
if h.bytes().any(|c| c.is_ascii_uppercase()) {
return Err("it must be lowercase");
}
let mut last = "";
for label in h.split('.') {
if label.is_empty() {
return Err("it has an empty label");
}
if label.len() > 63 {
return Err("a label is longer than 63 characters");
}
if !label
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
{
return Err("only a-z, 0-9, '-' and '.' are allowed");
}
if label.starts_with('-') || label.ends_with('-') {
return Err("a label must not start or end with '-'");
}
last = label;
}
if last.bytes().all(|c| c.is_ascii_digit()) {
return Err("the last label must not be 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("it must be plain ASCII without spaces");
}
let u = url::Url::parse(raw).map_err(|_| "it is not a URL like http://127.0.0.1:8080")?;
let scheme = match u.scheme() {
"http" => Scheme::Http,
"https" => Scheme::Https,
_ => return Err("only http:// and https:// are supported"),
};
if !u.username().is_empty() || u.password().is_some() {
return Err("credentials in the URL are not allowed");
}
if u.fragment().is_some() {
return Err("a #fragment is not allowed");
}
let host = match u.host() {
None => return Err("it has no host"),
Some(url::Host::Ipv4(ip)) => UpstreamHost::Ip(IpAddr::V4(ip)),
Some(url::Host::Ipv6(ip)) => UpstreamHost::Ip(IpAddr::V6(ip)),
Some(url::Host::Domain(d)) => {
if check_hostname(d).is_err() {
return Err("the host name is not valid");
}
UpstreamHost::Name(d.to_owned())
}
};
let port = u.port_or_known_default().ok_or("it has no port")?;
if port == 0 {
return Err("port 0 is not usable");
}
let mut path = u.path().to_owned();
if !allow_path {
if path != "/" && !path.is_empty() {
return Err("a path is not allowed; requests keep their own path");
}
if u.query().is_some() {
return Err("a ?query is not allowed");
}
} else {
if let Some(q) = u.query() {
path.push('?');
path.push_str(q);
}
if path.contains(['{', '}']) {
return Err("'{' and '}' are not allowed");
}
}
Ok((Upstream { scheme, host, port }, path))
}
+279
View File
@@ -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"
+9
View File
@@ -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"
+573
View File
@@ -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"
}
}
+137
View File
@@ -0,0 +1,137 @@
{
"version": 1,
"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
},
{
"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
},
{
"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
}
]
}
+923
View File
@@ -0,0 +1,923 @@
// 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: "b.test.toml",
contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
};
let b = SourceFile {
name: "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: "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: "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 rejects_duplicate_hostnames_across_files() {
let r = load(
&site(),
&[
SourceFile {
name: "hosts/app.test.toml",
contents: MINIMAL,
},
SourceFile {
name: "other/app.test.toml",
contents: MINIMAL,
},
],
);
let errs = r.unwrap_err();
assert_eq!(
errs.errors(),
[ValidationError::DuplicateHostname {
hostname: "app.test".into(),
first: "hosts/app.test.toml".into(),
second: "other/app.test.toml".into()
}]
);
}
#[test]
fn duplicate_detection_is_independent_of_file_order() {
let r = load(
&site(),
&[
SourceFile {
name: "other/app.test.toml",
contents: MINIMAL,
},
SourceFile {
name: "hosts/app.test.toml",
contents: MINIMAL,
},
],
);
let errs = r.unwrap_err();
assert!(
matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/app.test.toml" && second == "other/app.test.toml")
);
}
#[test]
fn rejects_duplicate_source_file_names() {
let r = load(
&site(),
&[
SourceFile {
name: "app.test.toml",
contents: MINIMAL,
},
SourceFile {
name: "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!(
matches!(e, ValidationError::BadUpstreamUrl { ref url, .. } if url == bad),
"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()
}
);
}
#[test]
fn undefined_secret_is_reported_when_site_declares_none() {
let r = load(
&SourceFile {
name: "ianitor.toml",
contents: "",
},
&[SourceFile {
name: "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: "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: "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: "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: "a.test.toml",
contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n",
},
SourceFile {
name: "B.test.toml",
contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
},
SourceFile {
name: "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: "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: "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}"
);
}
}
+35
View File
@@ -0,0 +1,35 @@
[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
[dev-dependencies]
ianitor-testkit.workspace = true
[lints]
workspace = true
+289
View File
@@ -0,0 +1,289 @@
// 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::runtime::Runtime;
use crate::tls::{CertStore, 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);
/// 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 rt: Arc<Runtime>,
pub certs: Arc<CertStore>,
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.rt.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.certs.insert(host, ck);
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.certs.insert(host, ck);
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.
async fn round(&self, expiries: &mut HashMap<String, i64>) -> bool {
let Some(acme) = &self.rt.cfg.acme else {
return true;
};
let due: Vec<String> = self
.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;
}
let account = match self.account(&acme.directory, acme.email.as_deref()).await {
Ok(a) => a,
Err(e) => {
log::error!(target: "ianitor::acme", "{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}");
ok = false;
}
}
}
ok
}
}
#[async_trait]
impl BackgroundService for AcmeService {
async fn start(&self, mut shutdown: ShutdownWatch) {
if self.rt.acme_hosts().is_empty() {
return;
}
let dir = self.dir();
if let Err(e) = std::fs::create_dir_all(&dir) {
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
return;
}
let mut expiries = HashMap::new();
for h in self.rt.acme_hosts() {
if let Some(e) = self.load_stored(&h) {
expiries.insert(h, e);
}
}
let mut retry = FIRST_RETRY;
loop {
let wait = if self.round(&mut expiries).await {
retry = FIRST_RETRY;
CHECK_EVERY
} else {
let w = retry;
retry = (retry * 2).min(MAX_RETRY);
w
};
tokio::select! {
_ = tokio::time::sleep(wait) => {}
_ = shutdown.changed() => return,
}
}
}
}
+37
View File
@@ -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),
}
+133
View File
@@ -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(),
})
}
+116
View File
@@ -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))
}
+114
View File
@@ -0,0 +1,114 @@
// 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 at startup; upstreams start healthy.
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use async_trait::async_trait;
use pingora::connectors::http::Connector;
use pingora::http::RequestHeader;
use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService;
use crate::fetch::fetch;
use crate::runtime::{HostRt, Runtime, UpstreamRt};
const TIMEOUT: Duration = Duration::from_secs(5);
pub struct HealthChecks {
pub rt: Arc<Runtime>,
}
async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool {
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
return false;
};
if req
.insert_header(http::header::HOST, u.authority.as_str())
.is_err()
{
return false;
}
match fetch(connector, u, req, 64 * 1024, TIMEOUT).await {
Ok(f) => f.header.status.is_success(),
Err(_) => false,
}
}
/// 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>) {
for i in 0..host.upstreams.len() {
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
let ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await {
Ok(ok) => ok,
Err(e) => {
log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority);
false
}
};
let u = &host.upstreams[i];
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 watch(host: Arc<HostRt>, path: String, every: Duration) {
let connector = Arc::new(Connector::new(None));
loop {
round(&host, &path, &connector).await;
tokio::time::sleep(every).await;
}
}
#[async_trait]
impl BackgroundService for HealthChecks {
async fn start(&self, mut shutdown: ShutdownWatch) {
let checked: Vec<(Arc<HostRt>, String, Duration)> = self
.rt
.hosts
.values()
.filter_map(|h| {
h.cfg.health_check.as_ref().map(|hc| {
(
h.clone(),
hc.path.clone(),
Duration::from_secs(u64::from(hc.interval_secs.max(1))),
)
})
})
.collect();
let mut tasks = tokio::task::JoinSet::new();
let mut which = std::collections::HashMap::new();
for (i, (h, p, every)) in checked.iter().enumerate() {
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
}
// A watcher never returns; if one ends anyway, say so and start it again.
loop {
tokio::select! {
_ = shutdown.changed() => break,
Some(done) = tasks.join_next_with_id() => {
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
if let Some(i) = which.remove(&id) {
let (h, p, every) = &checked[i];
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname);
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
}
}
}
}
tasks.abort_all();
}
}
+130
View File
@@ -0,0 +1,130 @@
// 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::runtime::Runtime;
pub struct HttpApp {
pub rt: Arc<Runtime>,
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 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) = self.rt.host(&name) else {
return empty(StatusCode::NOT_FOUND);
};
let uri = req.uri.path_and_query().map_or("/", |p| p.as_str());
let port = self.rt.cfg.https_port;
let 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) = &self.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
}
}
+129
View File
@@ -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/.
//! Ianitor edge: the Pingora data plane. It reads the config compiled by `ianitor-core`
//! and serves it; it never decides policy.
//!
//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, websockets, header rules,
//! round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and redirects),
//! health checks, ACME issuance and renewal.
pub mod acme;
pub mod error;
pub mod fetch;
pub mod forward_auth;
pub mod health;
pub mod http_app;
pub mod logging;
pub mod proxy;
pub mod runtime;
pub mod secrets;
pub mod tls;
use std::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;
#[derive(Debug, Clone, Default)]
pub struct Options {
/// The compiled edge config (`ianitor-core` edge compiler output).
pub config: PathBuf,
/// Extra trust root for the ACME directory's TLS (Pebble in tests).
pub acme_root: Option<PathBuf>,
}
/// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates.
pub fn prepare(opts: &Options) -> Result<Arc<Runtime>, EdgeError> {
let cfg = runtime::read_config(&opts.config)?;
let creds = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from);
runtime::build(cfg, creds.as_deref()).map(Arc::new)
}
/// Assemble the Pingora server with all services. Listeners bind when it runs.
pub fn server(rt: Arc<Runtime>, 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 mut https = http_proxy_service(
&server.configuration,
proxy::EdgeProxy {
rt: rt.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(rt.certs.clone());
tls.enable_h2();
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls);
let mut http = Service::new(
"ianitor http".to_owned(),
http_app::HttpApp {
rt: rt.clone(),
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 { rt: rt.clone() },
));
server.add_service(background_service(
"ianitor acme",
acme::AcmeService {
rt: rt.clone(),
certs: rt.certs.clone(),
challenges,
ca_root: opts.acme_root.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)))),
});
}
+171
View File
@@ -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");
}
}
+62
View File
@@ -0,0 +1,62 @@
// 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] [--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("--check") => check = true,
Some("--help" | "-h") => {
println!(
"usage: ianitor-edge --config <edge.json> [--check] [--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 rt = ianitor_edge::prepare(&opts)?;
log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), rt.hosts.len());
if check {
return Ok(None);
}
ianitor_edge::server(rt, &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
}
}
}
+397
View File
@@ -0,0 +1,397 @@
// 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};
pub struct EdgeProxy {
pub rt: Arc<Runtime>,
pub connector: Connector,
}
pub struct Ctx {
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 {
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> {
ctx.host_header = host_header(session.req_header());
let Some(host) = self.rt.host(&hostname(&ctx.host_header)).cloned() else {
respond_empty(session, 404).await?;
return Ok(true);
};
ctx.host = Some(host.clone());
if host.cfg.forward_auth {
let fa = self.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);
}
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)?;
}
}
}
}
}
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
respond_empty(session, 403).await?;
return Ok(true);
}
Ok(false)
}
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) = &self.rt.access_log 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())
}
}
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"));
}
}
+364
View File
@@ -0,0 +1,364 @@
// 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: resolved upstream addresses,
//! parsed header names, secrets loaded, certificates loaded. Built once at startup.
use std::collections::{BTreeSet, HashMap};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::time::Duration;
use http::{HeaderName, HeaderValue};
use ianitor_core::edge_config::{
EDGE_CONFIG_VERSION, EdgeConfig, EdgeHeaderOp, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
};
use crate::error::EdgeError;
use crate::logging::AccessLog;
use crate::secrets::Secrets;
use crate::tls::{CertStore, certified_key};
pub enum Op {
Set(HeaderName, HeaderValue),
Remove(HeaderName),
}
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 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>,
pub certs: Arc<CertStore>,
}
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 read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
let text = std::fs::read_to_string(path).map_err(|source| EdgeError::Read {
path: path.to_owned(),
source,
})?;
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),
})
}
/// 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()
}
/// Load secrets and certificates and resolve upstreams. Fails on the first problem; edge never
/// starts half-configured.
pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
let 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 secrets = Secrets::load(&names, credentials_dir)?;
let certs = Arc::new(CertStore::default());
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 pair =
certified_key(&read(cert)?, &read(key)?).map_err(|reason| EdgeError::Cert {
host: h.hostname.clone(),
reason,
})?;
certs.insert(&h.hostname, 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,
certs,
})
}
#[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);
}
}
+163
View File
@@ -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"));
}
}
+66
View File
@@ -0,0 +1,66 @@
// 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};
#[derive(Debug, Default)]
pub struct CertStore {
certs: 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
});
}
pub fn has(&self, host: &str) -> bool {
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();
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())
}
+233
View File
@@ -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"
);
}
}
+169
View File
@@ -0,0 +1,169 @@
// 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.
#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
use ianitor_core::compile::{self, CompileOptions};
use ianitor_core::{SourceFile, TlsMode, load};
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
use ianitor_testkit::tls::TestCa;
use rustls::RootCertStore;
pub struct Edge {
pub child: ChildGuard,
pub http: SocketAddr,
pub https: SocketAddr,
pub dir: TempDir,
pub ca: TestCa,
pub config_text: String,
}
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 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,
}
}
}
/// Compile, write certificates and credentials, start the binary. Does not wait for readiness.
pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
let dir = TempDir::new("edge");
for d in ["certs", "state", "creds", "logs"] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
let sources: Vec<SourceFile> = spec
.hosts
.iter()
.map(|(n, c)| SourceFile {
name: n,
contents: c,
})
.collect();
let model = load(
&SourceFile {
name: "ianitor.toml",
contents: spec.site,
},
&sources,
)
.expect("valid routes");
let ca = TestCa::new("Ianitor Test CA");
for h in model.hosts() {
if h.tls == TlsMode::Domi {
let leaf = ca.issue(&[h.hostname.as_str()]);
std::fs::write(
dir.join(&format!("certs/{}.crt", h.hostname)),
leaf.cert_pem,
)
.unwrap();
std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap();
}
}
for (name, value) in &spec.secrets {
std::fs::write(dir.join(&format!("creds/{name}")), value).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::edge(&model, &opts).unwrap();
std::fs::write(dir.join("edge.json"), &config_text).unwrap();
let stderr = std::fs::File::create(dir.join("edge.stderr")).unwrap();
let mut cmd = Command::new(env!("CARGO_BIN_EXE_ianitor-edge"));
cmd.arg("--config").arg(dir.join("edge.json"));
cmd.args(&spec.extra_args);
cmd.env("CREDENTIALS_DIRECTORY", dir.join("creds"));
cmd.env("IANITOR_LOG", spec.log_level);
cmd.stdout(Stdio::from(stderr.try_clone().unwrap()))
.stderr(Stdio::from(stderr));
let child = ChildGuard(cmd.spawn().expect("spawn ianitor-edge"));
Edge {
child,
http,
https,
dir,
ca,
config_text,
}
}
/// Spawn and wait until both listeners accept connections.
pub fn start(spec: EdgeSpec<'_>) -> Edge {
let mut e = spawn(spec);
let ok = wait_for_port(e.https, Duration::from_secs(20))
&& wait_for_port(e.http, Duration::from_secs(5));
if !ok || e.exited().is_some() {
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}"),
)
}
+389
View File
@@ -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}");
}
}
}
}
+273
View File
@@ -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());
}
}
+201
View File
@@ -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());
}
}
+35 -3
View File
@@ -107,20 +107,52 @@ 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)
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)
**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)
**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)
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)
7. Red Panda Network donation route for a non-US individual and the receipt they issue. (phase 4, Mark)
## 9. Status
| Phase | State | Notes |
|:--|:--|:--|
| 1 Core and engine | Not started | |
| 1 Core and engine | Done, except the Let's Encrypt staging check | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. LE staging needs a public domain: Mark to decide whether to defer it to phase 3 or give a domain now. |
| 2 Control plane | Not started | |
| 3 Web UI, PKI, NixOS | Not started | |
| 4 Hardening and release | Not started | |
| 3 Web UI, PKI, NixOS | Not started | UI design drafted: claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u ("murex" palette on the Domi system). |
| 4 Hardening and release | Not started | Known gaps carried here: see Handover. |
## 10. Handover
(Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.)
**2026-11-07: Phase 1, design draft.**
- **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.
+5
View File
@@ -0,0 +1,5 @@
{
"name": "ianitor-domi",
"private": true,
"license": "MPL-2.0"
}
+3
View File
@@ -0,0 +1,3 @@
packages:
- "apps/*"
- "packages/*"
+19
View File
@@ -0,0 +1,19 @@
[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
[lints.rust]
unsafe_code = "forbid"
+959
View File
@@ -0,0 +1,959 @@
// 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/.
//! Differential harness: one set of route files, compiled by `ianitor-core` into the edge
//! config and into Caddy JSON; the same request corpus is sent to Ianitor (in-process) and
//! to Caddy (the `caddy` binary running the generated JSON); status, selected headers and
//! body are compared. Everything listens on 127.0.0.1.
//!
//! Test code: panics are failures.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::net::SocketAddr;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
use ianitor_core::compile::{self, CompileOptions};
use ianitor_core::{Model, SourceFile, load};
use ianitor_testkit::authelia::MockAuthelia;
use ianitor_testkit::client::{self, Req, Resp, WsOutcome};
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
use ianitor_testkit::tls::TestCa;
use ianitor_testkit::upstream::{Echo, WsEcho, closed_port};
use rustls::RootCertStore;
/// The value behind the `api_key` credential. Written with a trailing newline, like most
/// systemd credentials; both engines must drop it.
pub const SECRET: &str = "diff-secret-value-7f3a";
/// Upstreams, auth server, certificates, credentials and the compiled model.
pub struct Env {
pub dir: TempDir,
pub ca: TestCa,
pub model: Model,
_upstreams: (Echo, Echo, Echo, Echo, WsEcho, MockAuthelia),
}
fn host(name: &str, body: &str) -> (String, String) {
(
format!("hosts/{name}.toml"),
format!("hostname = \"{name}\"\ntls = \"domi\"\n{body}"),
)
}
impl Env {
pub async fn start() -> Env {
let app = Echo::start("app").await;
let sick = Echo::start("sick").await;
sick.health.store(500, std::sync::atomic::Ordering::SeqCst);
let rr_a = Echo::start("rr").await;
let rr_b = Echo::start("rr").await;
let ws = WsEcho::start().await;
let auth = MockAuthelia::start().await;
let site = format!(
"secrets = [\"api_key\"]\n\n[forward_auth]\nurl = \"{}\"\ncopy_headers = [\"Remote-User\", \"Remote-Groups\"]\n",
auth.url()
);
let rules = "\
[[request_headers]]\naction = \"set\"\nname = \"X-Static\"\nvalue = \"static-value\"\n\
[[request_headers]]\naction = \"remove\"\nname = \"X-Remove-Me\"\n\
[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"api_key\"\n\
[[response_headers]]\naction = \"set\"\nname = \"X-Frame-Options\"\nvalue = \"DENY\"\n\
[[response_headers]]\naction = \"remove\"\nname = \"X-Powered-By\"\n";
let hosts = vec![
host(
"plain.test",
&format!(
"upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rules}",
app.url()
),
),
host("ws.test", &format!("upstreams = [\"{}\"]\n", ws.url())),
host(
"nows.test",
&format!("upstreams = [\"{}\"]\nwebsockets = false\n", app.url()),
),
host(
"down.test",
&format!("upstreams = [\"http://127.0.0.1:{}\"]\n", closed_port()),
),
host(
"auth.test",
&format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", app.url()),
),
host(
"wsauth.test",
&format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", ws.url()),
),
host(
"hc.test",
&format!(
"upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n",
app.url()
),
),
host(
"hcdown.test",
&format!(
"upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n",
sick.url()
),
),
host(
"rr.test",
&format!("upstreams = [\"{}\", \"{}\"]\n", rr_a.url(), rr_b.url()),
),
];
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("diff routes are valid");
let dir = TempDir::new("diff");
for d in ["certs", "creds", "logs", "state-edge", "state-caddy", "xdg"] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
let ca = TestCa::new("Ianitor Diff CA");
for h in model.hosts() {
let leaf = ca.issue(&[h.hostname.as_str()]);
std::fs::write(
dir.join(&format!("certs/{}.crt", h.hostname)),
leaf.cert_pem,
)
.unwrap();
std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap();
}
std::fs::write(dir.join("creds/api_key"), format!("{SECRET}\n")).unwrap();
Env {
dir,
ca,
model,
_upstreams: (app, sick, rr_a, rr_b, ws, auth),
}
}
pub fn options(&self, engine: &str) -> CompileOptions {
CompileOptions {
http_listen: local(free_port()),
https_listen: local(free_port()),
cert_dir: self.dir.str("certs"),
state_dir: self.dir.str(&format!("state-{engine}")),
access_log: self.dir.str(&format!("logs/{engine}-access.log")),
caddy_credentials_dir: self.dir.str("creds"),
caddy_admin: None,
}
}
pub fn roots(&self) -> Arc<RootCertStore> {
self.ca.roots()
}
}
/// A running engine: where to send requests.
pub struct Target {
pub name: &'static str,
pub http: SocketAddr,
pub https: SocketAddr,
_guard: Guard,
}
enum Guard {
Edge(Option<tokio::sync::oneshot::Sender<()>>),
Caddy(#[allow(dead_code)] ChildGuard),
}
impl Drop for Target {
fn drop(&mut self) {
if let Guard::Edge(stop) = &mut self._guard
&& let Some(s) = stop.take()
{
let _ = s.send(());
}
}
}
/// Start Ianitor edge in this process from an edge config text.
pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target {
let cfg: ianitor_core::edge_config::EdgeConfig = serde_json::from_str(config_text).unwrap();
let (http, https) = (
cfg.http_listen.parse().unwrap(),
cfg.https_listen.parse().unwrap(),
);
let rt = Arc::new(
ianitor_edge::runtime::build(cfg, Some(&env.dir.join("creds"))).expect("edge runtime"),
);
let server = ianitor_edge::server(rt, &ianitor_edge::Options::default()).expect("edge server");
let (tx, rx) = tokio::sync::oneshot::channel();
std::thread::spawn(move || ianitor_edge::run_until(server, rx));
assert!(
wait_for_port(https, Duration::from_secs(20)),
"edge did not listen on {https}"
);
assert!(
wait_for_port(http, Duration::from_secs(5)),
"edge did not listen on {http}"
);
Target {
name,
http,
https,
_guard: Guard::Edge(Some(tx)),
}
}
/// Start `caddy run` on a generated Caddy JSON.
pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json: &str) -> Target {
let v: serde_json::Value = serde_json::from_str(json).unwrap();
let servers = &v["apps"]["http"]["servers"];
let https: SocketAddr = servers["ianitor_https"]["listen"][0]
.as_str()
.unwrap()
.parse()
.unwrap();
let http: SocketAddr = servers["ianitor_http"]["listen"][0]
.as_str()
.unwrap()
.parse()
.unwrap();
let file = env.dir.join(&format!("{name}.json"));
std::fs::write(&file, json).unwrap();
let log = std::fs::File::create(env.dir.join(&format!("{name}.log"))).unwrap();
let child = Command::new(caddy)
.arg("run")
.arg("--config")
.arg(&file)
.env("HOME", env.dir.join("xdg"))
.env("XDG_CONFIG_HOME", env.dir.join("xdg"))
.env("XDG_DATA_HOME", env.dir.join("xdg"))
.stdout(Stdio::from(log.try_clone().unwrap()))
.stderr(Stdio::from(log))
.spawn()
.expect("spawn caddy");
let guard = ChildGuard(child);
if !wait_for_port(https, Duration::from_secs(20)) {
let out = std::fs::read_to_string(env.dir.join(&format!("{name}.log"))).unwrap_or_default();
panic!("caddy did not listen on {https}:\n{out}");
}
assert!(wait_for_port(http, Duration::from_secs(5)));
Target {
name,
http,
https,
_guard: Guard::Caddy(guard),
}
}
pub enum Action {
Https {
sni: &'static str,
req: Req,
},
Http {
req: Req,
},
Websocket {
sni: &'static str,
host: &'static str,
headers: Vec<(&'static str, &'static str)>,
},
}
/// One request of the corpus. Status, every response header (except [`IGNORED_HEADERS`])
/// and the body are compared.
pub struct Case {
pub name: &'static str,
pub action: Action,
}
fn https(name: &'static str, sni: &'static str, req: Req) -> Case {
Case {
name,
action: Action::Https { sni, req },
}
}
fn http(name: &'static str, req: Req) -> Case {
Case {
name,
action: Action::Http { req },
}
}
fn ws(name: &'static str, host: &'static str, headers: Vec<(&'static str, &'static str)>) -> Case {
Case {
name,
action: Action::Websocket {
sni: host,
host,
headers,
},
}
}
/// The seed corpus: plain requests, header rules, websocket upgrades, upstream down,
/// auth denied and allowed, misbehaving auth server, health checks, odd request targets.
pub fn corpus() -> Vec<Case> {
let p = "plain.test";
let a = "auth.test";
let good = ("cookie", "authelia_session=good");
let session = |s: &str| format!("authelia_session={s}");
vec![
https("plain GET", p, Req::get(p, "/")),
https(
"GET with path and query",
p,
Req::get(p, "/deep/path/x.html?q=1&r=two"),
),
https("HEAD", p, Req::new("HEAD", p, "/")),
https(
"POST with body",
p,
Req::new("POST", p, "/submit")
.header("content-type", "application/x-www-form-urlencoded")
.body(b"a=1&b=2"),
),
https(
"PUT binary body",
p,
Req::new("PUT", p, "/blob").body(&[0u8, 1, 2, 3, 255, 254]),
),
https("DELETE", p, Req::new("DELETE", p, "/item/7")),
https(
"request header removed",
p,
Req::get(p, "/").header("x-remove-me", "1"),
),
https(
"removal is exact, not a prefix match",
p,
Req::get(p, "/")
.header("x-remove-me", "1")
.header("x-remove-me-too", "kept"),
),
https(
"request header overwritten",
p,
Req::get(p, "/").header("x-static", "from-client"),
),
https(
"client header passes",
p,
Req::get(p, "/").header("x-client", "hello"),
),
https(
"X-Forwarded-* replaced",
p,
Req::get(p, "/")
.header("x-forwarded-for", "6.6.6.6")
.header("x-forwarded-host", "evil.test")
.header("x-forwarded-proto", "gopher"),
),
https(
"secret header cannot be preset",
p,
Req::get(p, "/").header("x-api-key", "client-value"),
),
https("upstream 404 passes through", p, Req::get(p, "/status/404")),
https("upstream 500 passes through", p, Req::get(p, "/status/500")),
https("upstream 204", p, Req::get(p, "/status/204")),
https("large body", p, Req::get(p, "/big?n=300000")),
https("chunked body", p, Req::get(p, "/chunked")),
https("two Set-Cookie headers", p, Req::get(p, "/set-cookie")),
https("Host in upper case", p, Req::get("PLAIN.TEST", "/")),
https(
"unknown Host on a known SNI",
p,
Req::get("unknown.test", "/"),
),
https(
"absolute-form target, same host",
p,
Req::get(p, "https://plain.test/abs?q=1"),
),
https(
"absolute-form target, other host",
p,
Req::get(p, "https://evil.test/x"),
),
http("HTTP redirects to HTTPS", Req::get(p, "/a/b?c=d")),
http("HTTP unknown host", Req::get("unknown.test", "/")),
http(
"HTTP unknown ACME token",
Req::get(p, "/.well-known/acme-challenge/nope"),
),
http(
"HTTP absolute-form, same host",
Req::get(p, "http://plain.test/x?y"),
),
http(
"HTTP absolute-form, other host",
Req::get(p, "http://evil.test/x"),
),
ws("websocket upgrade", "ws.test", vec![]),
ws("websocket refused when disabled", "nows.test", vec![]),
https(
"plain GET where websockets are disabled",
"nows.test",
Req::get("nows.test", "/"),
),
https(
"websocket refused: second Upgrade header",
"nows.test",
Req::get("nows.test", "/")
.header("connection", "upgrade")
.header("upgrade", "h2c")
.header("upgrade", "websocket"),
),
https(
"websocket refused: token list",
"nows.test",
Req::get("nows.test", "/")
.header("connection", "upgrade")
.header("upgrade", "websocket, h2c"),
),
https("upstream down GET", "down.test", Req::get("down.test", "/")),
https(
"upstream down POST",
"down.test",
Req::new("POST", "down.test", "/x").body(b"lost"),
),
https(
"auth denied GET redirects to portal",
a,
Req::get(a, "/private?x=1"),
),
https("auth denied HEAD", a, Req::new("HEAD", a, "/private")),
https(
"auth denied POST",
a,
Req::new("POST", a, "/submit").body(b"nope"),
),
https(
"auth bad credentials",
a,
Req::get(a, "/").header("authorization", "Bearer wrong"),
),
https(
"auth forbidden",
a,
Req::get(a, "/").header("cookie", &session("forbidden")),
),
https(
"auth allowed with session",
a,
Req::get(a, "/me").header(good.0, good.1),
),
https(
"auth allowed ignores spoofed identity",
a,
Req::get(a, "/me")
.header(good.0, good.1)
.header("remote-user", "mallory"),
),
https(
"auth strips spoofed identity it does not copy",
a,
Req::get(a, "/me")
.header(good.0, good.1)
.header("remote-email", "m@evil.test")
.header("remote-name", "Mallory"),
),
https(
"auth allowed without identity strips spoofed",
a,
Req::get(a, "/me")
.header("cookie", &session("nameless"))
.header("remote-user", "mallory"),
),
https(
"auth allowed with bearer token",
a,
Req::get(a, "/api").header("authorization", "Bearer good"),
),
https(
"auth allowed GET with query",
a,
Req::get(a, "/search?q=a+b").header(good.0, good.1),
),
https(
"auth allowed POST keeps the body",
a,
Req::new("POST", a, "/form")
.header(good.0, good.1)
.body(b"field=value"),
),
https(
"auth answers 100 Continue first",
a,
Req::get(a, "/").header("cookie", &session("continue-ok")),
),
https(
"auth answers 9 informational heads first",
a,
Req::get(a, "/").header("cookie", &session("continue-x9")),
),
https(
"auth answers 1000 informational heads first",
a,
Req::get(a, "/").header("cookie", &session("continue-x1000")),
),
https(
"auth answers 1001 informational heads first",
a,
Req::get(a, "/").header("cookie", &session("continue-x1001")),
),
https(
"auth answers 2xx with a 5 MB body",
a,
Req::get(a, "/").header("cookie", &session("big-ok")),
),
https(
"auth answers 401 with a 5 MB body",
a,
Req::get(a, "/").header("cookie", &session("big-deny")),
),
https(
"auth answers 2xx with a truncated body",
a,
Req::get(a, "/").header("cookie", &session("truncated-ok")),
),
https(
"auth answers 101",
a,
Req::get(a, "/").header("cookie", &session("switch")),
),
ws("websocket denied by auth", "wsauth.test", vec![]),
ws("websocket allowed by auth", "wsauth.test", vec![good]),
https("healthy upstream", "hc.test", Req::get("hc.test", "/")),
https(
"all upstreams unhealthy",
"hcdown.test",
Req::get("hcdown.test", "/"),
),
https("round robin 1", "rr.test", Req::get("rr.test", "/")),
https("round robin 2", "rr.test", Req::get("rr.test", "/")),
]
}
/// Response headers not compared, with the reason.
pub const IGNORED_HEADERS: &[(&str, &str)] = &[
("date", "the clock moves between the two requests"),
(
"connection",
"hop-by-hop (RFC 9110 7.6.1): describes the client connection, not the response",
),
("keep-alive", "hop-by-hop (RFC 9110 7.6.1)"),
(
"sec-websocket-accept",
"derived from the client's random Sec-WebSocket-Key",
),
];
/// What one engine answered, normalised for comparison.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Observation {
pub status: u16,
pub headers: BTreeMap<String, String>,
pub body: String,
}
fn observe_parts(status: u16, raw: &[(String, String)], body: &[u8], t: &Target) -> Observation {
let mut headers: BTreeMap<String, String> = BTreeMap::new();
for (n, v) in raw {
let n = n.to_ascii_lowercase();
if IGNORED_HEADERS.iter().any(|(i, _)| *i == n) {
continue;
}
// The two engines listen on different ports; Location carries the HTTPS port.
let v = v.replace(&format!(":{}", t.https.port()), ":<https-port>");
headers
.entry(n)
.and_modify(|e| {
e.push('\n');
e.push_str(&v)
})
.or_insert(v);
}
Observation {
status,
headers,
body: String::from_utf8_lossy(body).into_owned(),
}
}
fn observe(resp: &Resp, t: &Target) -> Observation {
observe_parts(resp.status, &resp.headers, &resp.body, t)
}
fn failed(e: std::io::Error) -> Observation {
Observation {
status: 0,
headers: BTreeMap::new(),
body: format!("client error: {e}"),
}
}
pub async fn run_case(case: &Case, t: &Target, roots: Arc<RootCertStore>) -> Observation {
match &case.action {
Action::Https { sni, req } => client::https(t.https, sni, roots, req)
.await
.map_or_else(failed, |r| observe(&r, t)),
Action::Http { req } => client::http(t.http, req)
.await
.map_or_else(failed, |r| observe(&r, t)),
Action::Websocket { sni, host, headers } => {
match client::websocket(t.https, sni, roots, host, "/socket", headers, "ping").await {
Ok(WsOutcome::Upgraded {
status,
headers,
echo,
}) => observe_parts(status, &headers, format!("echo: {echo}").as_bytes(), t),
Ok(WsOutcome::Refused(r)) => observe(&r, t),
Err(e) => failed(e),
}
}
}
}
pub struct Outcome {
pub name: &'static str,
pub ianitor: Observation,
pub caddy: Observation,
}
/// How a documented divergence is recognised. Each rule is narrow on purpose.
pub enum Rule {
/// Caddy has `header` with one of `values` and Ianitor has no such header; with `only_if`,
/// Caddy's answer must also carry that header/value pair (the upstream's own report).
ExtraHeaderInCaddy {
header: &'static str,
values: &'static [&'static str],
only_if: Option<(&'static str, &'static str)>,
},
/// This exact case, with exactly these statuses; nothing else is compared.
Status {
case: &'static str,
ianitor: u16,
caddy: u16,
},
}
pub struct Divergence {
pub id: &'static str,
pub rule: Rule,
pub reason: &'static str,
}
/// Documented, accepted differences between the engines. Anything else is a mismatch.
pub const KNOWN_DIVERGENCES: &[Divergence] = &[
Divergence {
id: "KD-1",
rule: Rule::ExtraHeaderInCaddy {
header: "content-type",
values: &[
"text/plain; charset=utf-8",
"text/html; charset=utf-8",
"application/octet-stream",
],
only_if: Some(("x-sent-content-type", "none")),
},
reason: "the upstream sent no Content-Type; Caddy (Go net/http) adds a sniffed one, Ianitor passes the response unchanged",
},
Divergence {
id: "KD-2",
rule: Rule::ExtraHeaderInCaddy {
header: "via",
values: &["1.1 Caddy"],
only_if: None,
},
reason: "Caddy adds `Via: 1.1 Caddy` to proxied responses; Ianitor adds no Via header",
},
Divergence {
id: "KD-3",
rule: Rule::ExtraHeaderInCaddy {
header: "server",
values: &["Caddy"],
only_if: None,
},
reason: "Caddy names itself in `Server`; Ianitor sends no Server header of its own",
},
Divergence {
id: "KD-4",
rule: Rule::Status {
case: "auth answers 2xx with a 5 MB body",
ianitor: 502,
caddy: 200,
},
reason: "edge reads at most 1 MiB of an auth answer and fails closed; Caddy ignores the body",
},
Divergence {
id: "KD-5",
rule: Rule::Status {
case: "auth answers 401 with a 5 MB body",
ianitor: 502,
caddy: 401,
},
reason: "edge reads at most 1 MiB of an auth answer and fails closed; Caddy streams it to the client",
},
Divergence {
id: "KD-6",
rule: Rule::Status {
case: "auth answers 2xx with a truncated body",
ianitor: 502,
caddy: 200,
},
reason: "edge treats a broken auth answer as a failure; Caddy allows on the 2xx status line",
},
Divergence {
id: "KD-7",
rule: Rule::Status {
case: "auth answers 101",
ianitor: 502,
caddy: 200,
},
reason: "edge treats 101 from the auth server as a denial (502); Caddy answers 200 without reaching the upstream",
},
Divergence {
id: "KD-8",
rule: Rule::Status {
case: "absolute-form target, other host",
ianitor: 400,
caddy: 404,
},
reason: "Pingora rejects a request whose target authority differs from Host (400); Go routes by the target (404 here)",
},
Divergence {
id: "KD-9",
rule: Rule::Status {
case: "HTTP absolute-form, other host",
ianitor: 400,
caddy: 404,
},
reason: "as KD-8, on the plain-HTTP listener",
},
Divergence {
id: "KD-10",
rule: Rule::Status {
case: "auth answers 1001 informational heads first",
ianitor: 502,
caddy: 200,
},
reason: "edge fails closed after 1000 informational heads from the auth server; Go limits only their total header bytes",
},
];
impl Outcome {
pub fn same(&self) -> bool {
self.ianitor == self.caddy
}
/// The divergence ids that explain every difference, or `None`.
pub fn known_divergence(&self) -> Option<String> {
if self.same() {
return None;
}
for d in KNOWN_DIVERGENCES {
if let Rule::Status {
case,
ianitor,
caddy,
} = d.rule
&& case == self.name
&& self.ianitor.status == ianitor
&& self.caddy.status == caddy
{
return Some(d.id.to_owned());
}
}
let mut c = self.caddy.clone();
let mut ids = Vec::new();
for d in KNOWN_DIVERGENCES {
if let Rule::ExtraHeaderInCaddy {
header,
values,
only_if,
} = d.rule
{
let extra = c
.headers
.get(header)
.is_some_and(|v| values.contains(&v.as_str()))
&& !self.ianitor.headers.contains_key(header)
&& only_if.is_none_or(|(h, v)| c.headers.get(h).is_some_and(|x| x == v));
if extra {
c.headers.remove(header);
ids.push(d.id);
}
}
}
(!ids.is_empty() && c == self.ianitor).then(|| ids.join("+"))
}
pub fn mismatch(&self) -> bool {
!self.same() && self.known_divergence().is_none()
}
}
pub struct Report {
pub outcomes: Vec<Outcome>,
}
impl Report {
pub fn mismatches(&self) -> Vec<&Outcome> {
self.outcomes.iter().filter(|o| o.mismatch()).collect()
}
pub fn known(&self) -> Vec<&Outcome> {
self.outcomes
.iter()
.filter(|o| o.known_divergence().is_some())
.collect()
}
pub fn render(&self, title: &str) -> String {
let identity_only = |o: &&Outcome| {
o.known_divergence()
.is_some_and(|k| k.split('+').all(|id| id == "KD-2" || id == "KD-3"))
};
let identity = self.outcomes.iter().filter(identity_only).count();
let mut s = format!(
"== {title}: {} cases: {} identical, {} identical apart from Via/Server (KD-2, KD-3), \
{} other known divergence, {} differ\n",
self.outcomes.len(),
self.outcomes.iter().filter(|o| o.same()).count(),
identity,
self.known().len() - identity,
self.mismatches().len()
);
for o in &self.outcomes {
if o.same() {
let _ = writeln!(s, " same {:3} {}", o.ianitor.status, o.name);
} else if let Some(kd) = o.known_divergence() {
let _ = writeln!(s, " {kd:<10} {:3} {}", o.ianitor.status, o.name);
} else {
let _ = writeln!(s, " DIFF {}", o.name);
for d in differences(&o.ianitor, &o.caddy) {
let _ = writeln!(s, " {d}");
}
}
}
for d in KNOWN_DIVERGENCES {
let _ = writeln!(s, " {}: {}", d.id, d.reason);
}
for (h, why) in IGNORED_HEADERS {
let _ = writeln!(s, " not compared: {h} ({why})");
}
s
}
}
fn short(o: &Observation) -> Observation {
let mut o = o.clone();
if o.body.len() > 300 {
o.body = format!(
"{}… ({} bytes)",
o.body.chars().take(300).collect::<String>(),
o.body.len()
);
}
o
}
/// Send every case to both targets, one after the other (round robin needs a stable order).
pub async fn run_corpus(ianitor: &Target, caddy: &Target, roots: Arc<RootCertStore>) -> Report {
let mut outcomes = Vec::new();
for case in corpus() {
let i = run_case(&case, ianitor, roots.clone()).await;
let c = run_case(&case, caddy, roots.clone()).await;
outcomes.push(Outcome {
name: case.name,
ianitor: i,
caddy: c,
});
}
Report { outcomes }
}
/// Compile both configs for one pair of engine instances.
pub fn compile_pair(env: &Env) -> (String, String) {
let edge = compile::edge(&env.model, &env.options("edge")).unwrap();
let caddy = compile::caddy(&env.model, &env.options("caddy")).unwrap();
(edge, caddy)
}
/// Deliberately broken Caddy compiler: forgets every response header rule.
pub fn break_caddy(json: &str) -> String {
let mut v: serde_json::Value = serde_json::from_str(json).unwrap();
fn walk(v: &mut serde_json::Value) {
match v {
serde_json::Value::Object(m) => {
if m.get("handler").and_then(|h| h.as_str()) == Some("reverse_proxy")
&& let Some(h) = m.get_mut("headers").and_then(|h| h.as_object_mut())
{
h.remove("response");
}
m.values_mut().for_each(walk);
}
serde_json::Value::Array(a) => a.iter_mut().for_each(walk),
_ => {}
}
}
walk(&mut v);
serde_json::to_string_pretty(&v).unwrap()
}
/// Deliberately broken edge compiler: forgets every request header rule.
pub fn break_edge(json: &str) -> String {
let mut cfg: ianitor_core::edge_config::EdgeConfig = serde_json::from_str(json).unwrap();
for h in &mut cfg.hosts {
h.request_headers.clear();
}
serde_json::to_string_pretty(&cfg).unwrap()
}
/// Both engines run health checks every second; give them time for the first verdicts.
pub async fn settle() {
tokio::time::sleep(Duration::from_millis(2500)).await;
}
/// Field-by-field differences, for the report.
fn differences(i: &Observation, c: &Observation) -> Vec<String> {
let mut out = Vec::new();
if i.status != c.status {
out.push(format!("status: ianitor {} / caddy {}", i.status, c.status));
}
let names: std::collections::BTreeSet<&String> =
i.headers.keys().chain(c.headers.keys()).collect();
for n in names {
let (a, b) = (i.headers.get(n), c.headers.get(n));
if a != b {
out.push(format!("header {n}: ianitor {a:?} / caddy {b:?}"));
}
}
if i.body != c.body {
out.push(format!(
"body: ianitor {:?} / caddy {:?}",
short(i).body,
short(c).body
));
}
out
}
+101
View File
@@ -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:?}"
);
}
}
+26
View File
@@ -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"
+177
View File
@@ -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
}
+267
View File
@@ -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"))?
}
+25
View File
@@ -0,0 +1,25 @@
// 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 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}")
}
+120
View File
@@ -0,0 +1,120 @@
// 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};
/// A port on 127.0.0.1 that was free a moment ago.
pub fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.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();
}
}
+240
View File
@@ -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()),
]
);
}
}
+82
View File
@@ -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();
}
+299
View File
@@ -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()
}