Compare commits

...

10 Commits

17 changed files with 2073 additions and 1237 deletions
+155 -45
View File
@@ -1,65 +1,175 @@
#!/bin/sh #!/usr/bin/env bash
# SPDX-License-Identifier: MPL-2.0 # SPDX-License-Identifier: MPL-2.0
# #
# Ianitor pre-commit hook. Rejects staged files that must never be in git: # Ianitor pre-commit hook. Rejects staged files that must never be in git:
# - binaries (anything git itself classifies as binary) # - binaries: any NUL byte anywhere in the staged blob (git attributes do not matter)
# - private keys (PEM / OpenSSH / PKCS#8 / PGP headers, and key-store file names) # - private keys: PEM/PKCS#8/OpenSSH/PGP blocks, SSH2 (RFC 4716) keys, PuTTY .ppk,
# - files over 5 MB # age secret keys, JWK private keys (an object with "kty" RSA/EC/OKP and "d"),
# - build output and dependencies (target/, node_modules/, dist/) # 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 # Enable once per clone: git config core.hooksPath .githooks
# Test it: sh .githooks/test-pre-commit.sh # Test it: bash .githooks/test-pre-commit.sh
# Plain POSIX sh: works in Git Bash on Windows and on Linux.
LIMIT=5242880 # 5 MiB 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
# Every check prints one "FAIL" line on stdout per problem (reasons go to stderr), set -u
# so the loop can run in a pipeline subshell and still be counted here. LIMIT=5000000
failures=$(
# numstat prints "-<TAB>-<TAB>path" for files git treats as binary. # Patterns are written so that this file does not match them itself. They are matched
git -c core.quotePath=false diff --cached --numstat --diff-filter=ACMR | while IFS= read -r line; do # case-insensitively.
added=${line%%" "*} KEY_PATTERNS=(
rest=${line#*" "} '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----'
deleted=${rest%%" "*} '---- BEGIN SSH2 ENCRYPTED PRIVATE KEY[ ]----'
path=${rest#*" "} '---- BEGIN SSH2 PRIVATE KEY[ ]----'
if [ "$added" = "-" ] && [ "$deleted" = "-" ]; then 'PuTTY-User-Key-File-[0-9]+:'
printf 'pre-commit: rejected %s: binary file\n' "$path" >&2 'AGE-SECRET-KEY-[1][0-9A-Z]+'
echo FAIL '^[[: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 fi
prefix+="$part/"
done done
return 1
}
git -c core.quotePath=false diff --cached --name-only --diff-filter=ACMR | while IFS= read -r path; do # --raw -z gives ":<old mode> <new mode> <old sha> <new sha> <status>" NUL "<path>" NUL.
case "/$path" in while IFS= read -r -d '' meta && IFS= read -r -d '' path; do
*/target/*|*/node_modules/*|*/dist/*) read -r -a f <<<"${meta#:}"
printf 'pre-commit: rejected %s: build output or dependency directory\n' "$path" >&2 mode=${f[1]} sha=${f[3]}
echo FAIL ;; lower=${path,,}
case "/$lower" in
*/target/*|*/node_modules/*|*/dist/*|*/.svelte-kit/*)
reject "$path" "build output or dependency directory" ;;
esac esac
if is_build_output "$lower"; then
reject "$path" "build output directory"
fi
base=${path##*/} base=${lower##*/}
case "$base" in case "$base" in
*.pub) ;; *.pub) ;;
*.key|*.p12|*.pfx|*.jks|*.keystore|id_rsa|id_dsa|id_ecdsa|id_ed25519|id_rsa.*|id_dsa.*|id_ecdsa.*|id_ed25519.*) *.key|*.p12|*.pfx|*.jks|*.keystore|*.ppk|id_rsa|id_dsa|id_ecdsa|id_ed25519|id_rsa.*|id_dsa.*|id_ecdsa.*|id_ed25519.*)
printf 'pre-commit: rejected %s: private key file name\n' "$path" >&2 reject "$path" "private key file name" ;;
echo FAIL ;;
esac esac
# Size of the staged blob, not of the working-tree file. # Submodule entries have no blob to inspect.
size=$(git cat-file -s ":$path" 2>/dev/null || echo 0) [ "$mode" = 160000 ] && continue
if [ "$size" -gt "$LIMIT" ]; then staged[$path]=$sha
printf 'pre-commit: rejected %s: %s bytes is over the 5 MB limit\n' "$path" "$size" >&2 paths+=("$path")
echo FAIL shas+=("$sha")
fi done <"$tmp/list"
if git cat-file -p ":$path" 2>/dev/null | grep -E -q -e '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----'; then if [ "${#paths[@]}" -gt 0 ]; then
printf 'pre-commit: rejected %s: contains a private key\n' "$path" >&2 # Sizes: one batch for every blob, in order.
echo FAIL 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 fi
done i=$((i + 1))
) done <"$tmp/sizes"
[ "$i" -eq "${#paths[@]}" ] || die "cannot read the size of every staged blob"
case "$failures" in # Contents: git grep over the index, every file read as text (-a), names NUL-separated,
*FAIL*) # then kept only when staged. Exit 1 means no match; anything above blocks the commit.
printf 'pre-commit: commit blocked. Unstage the files above (git rm --cached <file>).\n' >&2 search() {
exit 1 ;; local out=$1 rc
esac 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 exit 0
+172 -14
View File
@@ -1,9 +1,10 @@
#!/bin/sh #!/usr/bin/env bash
# SPDX-License-Identifier: MPL-2.0 # SPDX-License-Identifier: MPL-2.0
# #
# Self-test for .githooks/pre-commit. Creates a throw-away repository, points it at the # 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 a normal file is accepted. # hook and checks that every forbidden case is rejected and normal files are accepted.
# Usage: sh .githooks/test-pre-commit.sh (Git Bash on Windows or Linux) # 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 set -u
HOOKS=$(cd "$(dirname "$0")" && pwd) HOOKS=$(cd "$(dirname "$0")" && pwd)
@@ -16,28 +17,58 @@ git config user.name hook-test
git config user.email hook-test@invalid git config user.email hook-test@invalid
git config core.hooksPath "$HOOKS" git config core.hooksPath "$HOOKS"
git config core.autocrlf false 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 git commit -q --allow-empty -m base --no-gpg-sign
pass=0 pass=0
fail=0 fail=0
# expect <accept|reject> <description> <path> (file must already exist) commit_and_check() {
expect() { local want=$1 what=$2 got
want=$1; what=$2; path=$3 if git commit -q -m "$what" --no-gpg-sign >/dev/null 2>"$WORK/.err"; then
git add -f -- "$path" got=accept
if git commit -q -m "$what" --no-gpg-sign >/dev/null 2>"$WORK/.err"; then got=accept; else got=reject; fi 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 if [ "$got" = "$want" ]; then
pass=$((pass + 1)); printf 'ok %-7s %s\n' "$want" "$what" pass=$((pass + 1)); printf 'ok %-7s %s\n' "$want" "$what"
else else
fail=$((fail + 1)); printf 'FAIL wanted %s, got %s: %s\n' "$want" "$got" "$what"; cat "$WORK/.err" fail=$((fail + 1)); printf 'FAIL wanted %s, got %s: %s\n' "$want" "$got" "$what"; cat "$WORK/.err"
fi fi
# Leave the index clean for the next case.
git reset -q --hard HEAD >/dev/null 2>&1 git reset -q --hard HEAD >/dev/null 2>&1
git clean -q -fdx >/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' B='-----BEGIN'
E='-----END' 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 printf 'hello\n' > readme.txt
expect accept "plain text file" readme.txt expect accept "plain text file" readme.txt
@@ -48,7 +79,15 @@ expect accept "source file" main.rs
printf '\000\001\002\003binary\000' > blob.bin printf '\000\001\002\003binary\000' > blob.bin
expect reject "binary file" blob.bin expect reject "binary file" blob.bin
printf '%s RSA PRIVATE KEY-----\nMIIBOgIBAAJBAK\n%s RSA PRIVATE KEY-----\n' "$B" "$E" > notes.txt { 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 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 printf '%s PRIVATE KEY-----\nMIGHAgEAMBMG\n%s PRIVATE KEY-----\n' "$B" "$E" > pkcs8.pem
@@ -63,9 +102,60 @@ expect reject "EC private key" ec.txt
printf '%s OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA\n%s OPENSSH PRIVATE KEY-----\n' "$B" "$E" > deploy printf '%s OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA\n%s OPENSSH PRIVATE KEY-----\n' "$B" "$E" > deploy
expect reject "OpenSSH private key" 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 printf 'not really a key\n' > server.key
expect reject "*.key file name" 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 printf 'not really a key\n' > id_ed25519
expect reject "id_ed25519 file name" id_ed25519 expect reject "id_ed25519 file name" id_ed25519
@@ -75,20 +165,88 @@ expect accept "public key id_ed25519.pub" id_ed25519.pub
printf '%s CERTIFICATE-----\nMIIBszCCAVmg\n%s CERTIFICATE-----\n' "$B" "$E" > cert.pem printf '%s CERTIFICATE-----\nMIIBszCCAVmg\n%s CERTIFICATE-----\n' "$B" "$E" > cert.pem
expect accept "certificate (public) PEM" cert.pem expect accept "certificate (public) PEM" cert.pem
head -c 6291456 /dev/zero | tr '\000' 'a' > big.txt cp "$SRC/six-mb" big.txt
expect reject "6 MB text file" big.txt expect reject "6 MB text file" big.txt
head -c 4194304 /dev/zero | tr '\000' 'a' > medium.txt head -c 5000001 /dev/zero | tr '\000' 'a' > over.txt
expect accept "4 MB text file" medium.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 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 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 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 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 mkdir -p apps/web/dist && printf 'x\n' > apps/web/dist/index.html
expect reject "file under dist/" 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" printf '\nhook: %d passed, %d failed\n' "$pass" "$fail"
[ "$fail" -eq 0 ] [ "$fail" -eq 0 ]
+2 -1
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. apps/web Svelte 5 (runes, TypeScript strict). A client of the API; no logic.
packages/ui shared dark Domi theme. packages/ui shared dark Domi theme.
tests/diff same requests against Ianitor and Caddy, responses compared. tests/diff same requests against Ianitor and Caddy, responses compared.
tests/support shared test fixtures (test CA, upstreams, mock Authelia, clients); test-only.
tests/fuzz cargo-fuzz targets. tests/fuzz cargo-fuzz targets.
deploy/nixos NixOS module + VM tests. deploy/nixos NixOS module + VM tests.
@@ -23,7 +24,7 @@ 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 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`): 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' 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: sh .githooks/test-pre-commit.sh) One-time per clone: git config core.hooksPath .githooks (self-test: bash .githooks/test-pre-commit.sh)
## Rules ## Rules
- Commits: `[<crate|app>] <Feature>: <one line>`. No AI attribution, no trailers, ever. - Commits: `[<crate|app>] <Feature>: <one line>`. No AI attribution, no trailers, ever.
+4 -2
View File
@@ -28,8 +28,10 @@ pub struct Fetched {
/// Dial timeout, matching Caddy's reverse_proxy default. /// Dial timeout, matching Caddy's reverse_proxy default.
pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3); pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3);
/// More 1xx heads than this before a final answer is treated as a broken server. /// More 1xx heads than this before a final answer is treated as a broken server. Go (and so
const MAX_INFORMATIONAL: usize = 8; /// 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 { pub fn peer(addr: SocketAddr, u: &UpstreamRt) -> HttpPeer {
let mut p = HttpPeer::new(addr, u.tls, u.sni.clone()); let mut p = HttpPeer::new(addr, u.tls, u.sni.clone());
+5 -1
View File
@@ -13,7 +13,11 @@
//! client request and, when the auth answer has a non-empty value, set from it. //! 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 //! - Any other answer is returned to the client as it is (status, headers, body), and the
//! request never reaches the upstream. //! request never reaches the upstream.
//! - If the auth server cannot be reached, the request fails closed with 502. //! - 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 std::time::Duration;
+84 -6
View File
@@ -10,6 +10,7 @@ use std::net::SocketAddr;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::time::Duration;
use http::{HeaderName, HeaderValue}; use http::{HeaderName, HeaderValue};
use ianitor_core::edge_config::{ use ianitor_core::edge_config::{
@@ -127,16 +128,52 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
}) })
} }
/// 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 { impl UpstreamRt {
/// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's /// 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. /// 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>> { pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
if let Ok(ip) = self.host.parse::<std::net::IpAddr>() { resolve_with(
return Ok(vec![SocketAddr::new(ip, self.port)]); &self.host,
self.port,
RESOLVE_TIMEOUT,
|host, port| async move {
tokio::net::lookup_host((host.as_str(), port))
.await
.map(Iterator::collect)
},
)
.await
} }
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((self.host.as_str(), self.port)) }
.await?
.collect(); /// [`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() { if addrs.is_empty() {
return Err(std::io::Error::new( return Err(std::io::Error::new(
std::io::ErrorKind::NotFound, std::io::ErrorKind::NotFound,
@@ -144,7 +181,6 @@ impl UpstreamRt {
)); ));
} }
Ok(addrs) Ok(addrs)
}
} }
fn header_name(name: &str) -> Result<HeaderName, EdgeError> { fn header_name(name: &str) -> Result<HeaderName, EdgeError> {
@@ -284,3 +320,45 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
certs, 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);
}
}
+26 -11
View File
@@ -10,23 +10,37 @@
//! //!
//! This is not Let's Encrypt staging: that needs a public domain and DNS. //! This is not Let's Encrypt staging: that needs a public domain and DNS.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common; mod common;
use std::os::unix::fs::PermissionsExt; #[cfg(not(unix))]
use std::process::{Command, Stdio}; #[test]
use std::time::{Duration, Instant}; fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
file!()
);
}
use common::{EdgeSpec, host_file, spawn}; #[cfg(unix)]
use ianitor_testkit::client::{self, Req}; mod unix {
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")] use std::os::unix::fs::PermissionsExt;
async fn certificate_is_obtained_from_pebble_and_served() { 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)) = ( let (Some(pebble), Some(challtestsrv)) = (
require_binary("pebble"), require_binary("pebble"),
require_binary("pebble-challtestsrv"), require_binary("pebble-challtestsrv"),
@@ -215,4 +229,5 @@ async fn certificate_is_obtained_from_pebble_and_served() {
!edge.stderr().contains("PRIVATE KEY"), !edge.stderr().contains("PRIVATE KEY"),
"no key material in the log" "no key material in the log"
); );
}
} }
+38 -25
View File
@@ -6,22 +6,34 @@
//! goes back to the client unchanged, and an allowed request carries the identity headers //! goes back to the client unchanged, and an allowed request carries the identity headers
//! from the auth server and never the client's own. //! from the auth server and never the client's own.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common; mod common;
use common::{EdgeSpec, host_file, start}; #[cfg(not(unix))]
use ianitor_testkit::authelia::MockAuthelia; #[test]
use ianitor_testkit::client::{self, Req, WsOutcome}; fn skipped_on_windows() {
use ianitor_testkit::upstream::{Echo, WsEcho, closed_port}; eprintln!(
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
fn site(auth_url: &str) -> String { file!()
format!("[forward_auth]\nurl = \"{auth_url}\"\n") );
} }
#[tokio::test(flavor = "multi_thread")] #[cfg(unix)]
async fn denial_never_reaches_the_upstream() { 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 authelia = MockAuthelia::start().await;
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
let ws = WsEcho::start().await; let ws = WsEcho::start().await;
@@ -148,10 +160,10 @@ async fn denial_never_reaches_the_upstream() {
post.body.is_empty(), post.body.is_empty(),
"the request body is not sent to the auth server" "the request body is not sent to the auth server"
); );
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn allowed_request_carries_identity_from_the_auth_server_only() { async fn allowed_request_carries_identity_from_the_auth_server_only() {
let authelia = MockAuthelia::start().await; let authelia = MockAuthelia::start().await;
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
let site = site(&authelia.url()); let site = site(&authelia.url());
@@ -224,10 +236,10 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() {
.await .await
.unwrap(); .unwrap();
assert_eq!(r.status, 200); assert_eq!(r.status, 200);
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn unreachable_auth_server_fails_closed() { async fn unreachable_auth_server_fails_closed() {
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
let site = site(&format!( let site = site(&format!(
"http://127.0.0.1:{}/api/authz/forward-auth", "http://127.0.0.1:{}/api/authz/forward-auth",
@@ -254,11 +266,11 @@ async fn unreachable_auth_server_fails_closed() {
.unwrap(); .unwrap();
assert_eq!(r.status, 502); assert_eq!(r.status, 502);
assert!(echo.proxied().is_empty()); assert!(echo.proxied().is_empty());
} }
/// QC B2a, B2b, m3: misbehaving auth servers. Edge fails closed and never crashes or hangs. /// QC B2a, B2b, m3: misbehaving auth servers. Edge fails closed and never crashes or hangs.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn misbehaving_auth_answers_fail_closed() { async fn misbehaving_auth_answers_fail_closed() {
let authelia = MockAuthelia::start().await; let authelia = MockAuthelia::start().await;
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
let site = site(&authelia.url()); let site = site(&authelia.url());
@@ -323,12 +335,12 @@ async fn misbehaving_auth_answers_fail_closed() {
// Still serving afterwards. // Still serving afterwards.
assert_eq!(go("good").await.unwrap().status, 200); assert_eq!(go("good").await.unwrap().status, 200);
} }
/// QC m5: client-sent Remote-* headers never reach a forward-auth upstream, whatever /// QC m5: client-sent Remote-* headers never reach a forward-auth upstream, whatever
/// copy_headers says. /// copy_headers says.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn remote_headers_are_stripped_even_with_a_custom_copy_list() { async fn remote_headers_are_stripped_even_with_a_custom_copy_list() {
let authelia = MockAuthelia::start().await; let authelia = MockAuthelia::start().await;
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
for copy in ["[]", "[\"Remote-User\"]"] { for copy in ["[]", "[\"Remote-User\"]"] {
@@ -373,4 +385,5 @@ async fn remote_headers_are_stripped_even_with_a_custom_copy_list() {
assert_eq!(up.header(h), None, "{h} with copy_headers = {copy}"); assert_eq!(up.header(h), None, "{h} with copy_headers = {copy}");
} }
} }
}
} }
+34 -21
View File
@@ -5,29 +5,41 @@
//! An injected secret reaches the upstream and never appears in a response, a log line, the //! 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. //! access log or the compiled config, even with the most verbose log level.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common; mod common;
use common::{EdgeSpec, host_file, spawn, start}; #[cfg(not(unix))]
use ianitor_testkit::client::{self, Req, Resp, WsOutcome}; #[test]
use ianitor_testkit::upstream::{Echo, WsEcho, closed_port}; fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
file!()
);
}
fn unique_secret() -> String { #[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() let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH) .duration_since(std::time::UNIX_EPOCH)
.unwrap() .unwrap()
.as_nanos(); .as_nanos();
format!("sekret-{}-{nanos:x}-tail", std::process::id()) format!("sekret-{}-{nanos:x}-tail", std::process::id())
} }
fn assert_clean(what: &str, haystack: &[u8], secret: &str) { fn assert_clean(what: &str, haystack: &[u8], secret: &str) {
let hay = String::from_utf8_lossy(haystack); let hay = String::from_utf8_lossy(haystack);
assert!(!hay.contains(secret), "secret leaked into {what}:\n{hay}"); assert!(!hay.contains(secret), "secret leaked into {what}:\n{hay}");
} }
fn assert_resp_clean(what: &str, r: &Resp, secret: &str) { fn assert_resp_clean(what: &str, r: &Resp, secret: &str) {
for (n, v) in &r.headers { for (n, v) in &r.headers {
assert_clean( assert_clean(
&format!("{what}: response header {n}"), &format!("{what}: response header {n}"),
@@ -36,10 +48,10 @@ fn assert_resp_clean(what: &str, r: &Resp, secret: &str) {
); );
} }
assert_clean(&format!("{what}: response body"), &r.body, secret); assert_clean(&format!("{what}: response body"), &r.body, secret);
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn injected_secret_never_appears_in_a_response_or_log() { async fn injected_secret_never_appears_in_a_response_or_log() {
let secret = unique_secret(); let secret = unique_secret();
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
let ws = WsEcho::start().await; let ws = WsEcho::start().await;
@@ -147,7 +159,7 @@ async fn injected_secret_never_appears_in_a_response_or_log() {
.await .await
.unwrap() .unwrap()
{ {
WsOutcome::Upgraded { status, echo } => { WsOutcome::Upgraded { status, echo, .. } => {
assert_eq!(status, 101); assert_eq!(status, 101);
assert_eq!(echo, "ping"); assert_eq!(echo, "ping");
} }
@@ -193,10 +205,10 @@ async fn injected_secret_never_appears_in_a_response_or_log() {
assert_clean("stderr (trace level)", stderr.as_bytes(), &secret); assert_clean("stderr (trace level)", stderr.as_bytes(), &secret);
assert_clean("access log", access.as_bytes(), &secret); assert_clean("access log", access.as_bytes(), &secret);
assert_clean("compiled edge config", edge.config_text.as_bytes(), &secret); assert_clean("compiled edge config", edge.config_text.as_bytes(), &secret);
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn missing_secret_stops_startup_without_leaking_others() { async fn missing_secret_stops_startup_without_leaking_others() {
let secret = unique_secret(); let secret = unique_secret();
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
let mut edge = spawn(EdgeSpec { let mut edge = spawn(EdgeSpec {
@@ -218,10 +230,10 @@ async fn missing_secret_stops_startup_without_leaking_others() {
let err = edge.stderr(); let err = edge.stderr();
assert!(err.contains("absent"), "names the missing secret:\n{err}"); assert!(err.contains("absent"), "names the missing secret:\n{err}");
assert_clean("stderr", err.as_bytes(), &secret); assert_clean("stderr", err.as_bytes(), &secret);
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn malformed_secret_is_rejected_without_echoing_it() { async fn malformed_secret_is_rejected_without_echoing_it() {
let secret = unique_secret(); let secret = unique_secret();
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
let mut edge = spawn(EdgeSpec { let mut edge = spawn(EdgeSpec {
@@ -247,9 +259,9 @@ async fn malformed_secret_is_rejected_without_echoing_it() {
"edge must refuse a secret that is not a valid header value" "edge must refuse a secret that is not a valid header value"
); );
assert_clean("stderr", edge.stderr().as_bytes(), &secret); assert_clean("stderr", edge.stderr().as_bytes(), &secret);
} }
fn wait_exit(edge: &mut common::Edge) -> std::process::ExitStatus { fn wait_exit(edge: &mut crate::common::Edge) -> std::process::ExitStatus {
for _ in 0..200 { for _ in 0..200 {
if let Some(s) = edge.exited() { if let Some(s) = edge.exited() {
return s; return s;
@@ -257,4 +269,5 @@ fn wait_exit(edge: &mut common::Edge) -> std::process::ExitStatus {
std::thread::sleep(std::time::Duration::from_millis(50)); std::thread::sleep(std::time::Duration::from_millis(50));
} }
panic!("edge kept running:\n{}", edge.stderr()); panic!("edge kept running:\n{}", edge.stderr());
}
} }
+36 -23
View File
@@ -5,21 +5,33 @@
//! Upstream handling: name resolution at connect time, health checks that survive odd //! Upstream handling: name resolution at connect time, health checks that survive odd
//! answers, websocket refusal on every Upgrade token, absolute-form requests. //! answers, websocket refusal on every Upgrade token, absolute-form requests.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common; mod common;
use std::time::{Duration, Instant}; #[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!()
);
}
use common::{EdgeSpec, host_file, start}; #[cfg(unix)]
use ianitor_testkit::client::{self, Req}; mod unix {
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. use std::time::{Duration, Instant};
#[tokio::test(flavor = "multi_thread")]
async fn upstream_names_are_resolved_at_connect_time_trying_every_address() { 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 echo = Echo::start("app").await;
let edge = start(EdgeSpec { let edge = start(EdgeSpec {
hosts: vec![ hosts: vec![
@@ -53,11 +65,11 @@ async fn upstream_names_are_resolved_at_connect_time_trying_every_address() {
.await .await
.unwrap(); .unwrap();
assert_eq!(r.status, 502); assert_eq!(r.status, 502);
} }
/// QC B2a: a health endpoint that sends a 1xx must not kill health checking. /// QC B2a: a health endpoint that sends a 1xx must not kill health checking.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn health_checks_survive_informational_answers() { async fn health_checks_survive_informational_answers() {
let started = Instant::now(); let started = Instant::now();
let up = RawServer::start(move |req| { let up = RawServer::start(move |req| {
if req.path == "/healthz" && started.elapsed() < Duration::from_secs(3) { if req.path == "/healthz" && started.elapsed() < Duration::from_secs(3) {
@@ -101,11 +113,11 @@ async fn health_checks_survive_informational_answers() {
.count() .count()
>= 4 >= 4
); );
} }
/// QC m4: every Upgrade header and every comma-separated token counts. /// QC m4: every Upgrade header and every comma-separated token counts.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn websocket_refusal_checks_every_upgrade_token() { async fn websocket_refusal_checks_every_upgrade_token() {
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
let edge = start(EdgeSpec { let edge = start(EdgeSpec {
hosts: vec![host_file( hosts: vec![host_file(
@@ -133,13 +145,13 @@ async fn websocket_refusal_checks_every_upgrade_token() {
assert_eq!(r.status, 403, "{req:?}"); assert_eq!(r.status, 403, "{req:?}");
} }
assert!(echo.proxied().is_empty()); assert!(echo.proxied().is_empty());
} }
/// QC nit: absolute-form request targets are answered, never dropped. Pingora refuses a target /// 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 /// whose authority differs from Host (400, on both listeners); a consistent one is routed and
/// sent upstream in origin form. /// sent upstream in origin form.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn absolute_form_requests_are_answered() { async fn absolute_form_requests_are_answered() {
let echo = Echo::start("app").await; let echo = Echo::start("app").await;
let edge = start(EdgeSpec { let edge = start(EdgeSpec {
hosts: vec![host_file( hosts: vec![host_file(
@@ -185,4 +197,5 @@ async fn absolute_form_requests_are_answered() {
.unwrap(); .unwrap();
assert_eq!(r.status, 200); assert_eq!(r.status, 200);
assert!(r.text().contains("\"path\":\"/abs\""), "{}", r.text()); assert!(r.text().contains("\"path\":\"/abs\""), "{}", r.text());
}
} }
+32 -4
View File
@@ -114,17 +114,45 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit
**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] **Answer: it compiles and the unit tests run on Windows (MSVC, Rust 1.99), but the README calls Windows support "preliminary by community's best effort only".** Unix-only parts include graceful upgrade, the in-process runner and the integration tests. Caddy and Pebble are not on this Windows box. So the edge integration tests, the diff suite and the ACME test run in WSL2 Debian, as noted in CLAUDE.md. One gotcha: libz-ng-sys's CMake build fails under a very deep CARGO_TARGET_DIR (MSBuild path length). [S github.com/cloudflare/pingora README; local builds 2026-11-07]
4. Pingora graceful reload behaviour under load. (phase 2) 4. Pingora graceful reload behaviour under load. (phase 2)
5. Authelia forward-auth endpoint and headers to mirror exactly. (phase 1) 5. Authelia forward-auth endpoint and headers to mirror exactly. (phase 1)
**Answer: `GET /api/authz/forward-auth` (ForwardAuth implementation; legacy `/api/verify` not used).** Edge sends X-Forwarded-Method, -Proto, -Host, -URI (required) and X-Forwarded-For, and always sets them itself. It also forwards the client's headers (Cookie, Authorization) without hop-by-hop headers or body. A 2xx answer copies Remote-User, Remote-Groups, Remote-Email and Remote-Name onto the request (client copies removed). Any other answer (302 portal, 401 + WWW-Authenticate, 403) goes back to the client verbatim. An unreachable auth server fails closed with 502. 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] **Answer: `GET /api/authz/forward-auth` (ForwardAuth implementation; legacy `/api/verify` not used).** Edge sends X-Forwarded-Method, -Proto, -Host, -URI (required) and X-Forwarded-For, and always sets them itself. It also forwards the client's headers (Cookie, Authorization) without hop-by-hop headers or body. A 2xx answer copies Remote-User, Remote-Groups, Remote-Email and Remote-Name onto the request (client copies removed). Any other answer (302 portal, 401 + WWW-Authenticate, 403) goes back to the client verbatim. An unreachable, silent (10 s deadline), oversized (>1 MiB), broken or `101` auth answer fails closed with 502; 1xx heads are skipped. Client-sent Remote-* headers are always stripped on forward-auth hosts, whatever copy_headers says. This mirrors `caddy adapt` output for Authelia's documented `forward_auth` snippet; tested against a mock, not a real Authelia. [S authelia.com/reference/guides/proxy-authorization, authelia.com/integration/proxies/caddy]
6. Custos CSR-signing operation with match-code approval. (phase 3) 6. Custos CSR-signing operation with match-code approval. (phase 3)
7. Red Panda Network donation route for a non-US individual and the receipt they issue. (phase 4, Mark) 7. Red Panda Network donation route for a non-US individual and the receipt they issue. (phase 4, Mark)
## 9. Status ## 9. Status
| Phase | State | Notes | | Phase | State | Notes |
|:--|:--|:--| |:--|:--|:--|
| 1 Core and engine | Not started | | | 1 Core and engine | Done, 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 | | | 2 Control plane | Not started | |
| 3 Web UI, PKI, NixOS | Not started | | | 3 Web UI, PKI, NixOS | Not started | UI design drafted: claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u ("murex" palette on the Domi system). |
| 4 Hardening and release | Not started | | | 4 Hardening and release | Not started | Known gaps carried here: see Handover. |
## 10. Handover ## 10. Handover
(Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.) (Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.)
**2026-11-07: Phase 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.
+376 -140
View File
@@ -58,7 +58,7 @@ impl Env {
let auth = MockAuthelia::start().await; let auth = MockAuthelia::start().await;
let site = format!( let site = format!(
"secrets = [\"api_key\"]\n\n[forward_auth]\nurl = \"{}\"\n", "secrets = [\"api_key\"]\n\n[forward_auth]\nurl = \"{}\"\ncopy_headers = [\"Remote-User\", \"Remote-Groups\"]\n",
auth.url() auth.url()
); );
let rules = "\ let rules = "\
@@ -276,37 +276,45 @@ pub enum Action {
}, },
} }
/// One request of the corpus. Status, every response header (except [`IGNORED_HEADERS`])
/// and the body are compared.
pub struct Case { pub struct Case {
pub name: &'static str, pub name: &'static str,
pub action: Action, pub action: Action,
/// Response headers compared besides status and body.
pub headers: &'static [&'static str],
} }
const STD: &[&str] = &[
"content-type",
"location",
"www-authenticate",
"set-cookie",
"x-powered-by",
"x-frame-options",
"x-upstream",
];
fn https(name: &'static str, sni: &'static str, req: Req) -> Case { fn https(name: &'static str, sni: &'static str, req: Req) -> Case {
Case { Case {
name, name,
action: Action::Https { sni, req }, action: Action::Https { sni, req },
headers: STD, }
}
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, /// The seed corpus: plain requests, header rules, websocket upgrades, upstream down,
/// auth denied and allowed, health checks. /// auth denied and allowed, misbehaving auth server, health checks, odd request targets.
pub fn corpus() -> Vec<Case> { pub fn corpus() -> Vec<Case> {
let p = "plain.test"; let p = "plain.test";
let a = "auth.test"; let a = "auth.test";
let good = ("cookie", "authelia_session=good"); let good = ("cookie", "authelia_session=good");
let session = |s: &str| format!("authelia_session={s}");
vec![ vec![
https("plain GET", p, Req::get(p, "/")), https("plain GET", p, Req::get(p, "/")),
https( https(
@@ -333,6 +341,13 @@ pub fn corpus() -> Vec<Case> {
p, p,
Req::get(p, "/").header("x-remove-me", "1"), 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( https(
"request header overwritten", "request header overwritten",
p, p,
@@ -368,50 +383,52 @@ pub fn corpus() -> Vec<Case> {
p, p,
Req::get("unknown.test", "/"), Req::get("unknown.test", "/"),
), ),
Case { https(
name: "HTTP redirects to HTTPS", "absolute-form target, same host",
action: Action::Http { p,
req: Req::get(p, "/a/b?c=d"), Req::get(p, "https://plain.test/abs?q=1"),
}, ),
headers: STD, https(
}, "absolute-form target, other host",
Case { p,
name: "HTTP unknown host", Req::get(p, "https://evil.test/x"),
action: Action::Http { ),
req: Req::get("unknown.test", "/"), http("HTTP redirects to HTTPS", Req::get(p, "/a/b?c=d")),
}, http("HTTP unknown host", Req::get("unknown.test", "/")),
headers: STD, http(
}, "HTTP unknown ACME token",
Case { Req::get(p, "/.well-known/acme-challenge/nope"),
name: "HTTP unknown ACME token", ),
action: Action::Http { http(
req: Req::get(p, "/.well-known/acme-challenge/nope"), "HTTP absolute-form, same host",
}, Req::get(p, "http://plain.test/x?y"),
headers: STD, ),
}, http(
Case { "HTTP absolute-form, other host",
name: "websocket upgrade", Req::get(p, "http://evil.test/x"),
action: Action::Websocket { ),
sni: "ws.test", ws("websocket upgrade", "ws.test", vec![]),
host: "ws.test", ws("websocket refused when disabled", "nows.test", vec![]),
headers: vec![],
},
headers: &["upgrade"],
},
Case {
name: "websocket refused when disabled",
action: Action::Websocket {
sni: "nows.test",
host: "nows.test",
headers: vec![],
},
headers: STD,
},
https( https(
"plain GET where websockets are disabled", "plain GET where websockets are disabled",
"nows.test", "nows.test",
Req::get("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 GET", "down.test", Req::get("down.test", "/")),
https( https(
"upstream down POST", "upstream down POST",
@@ -437,7 +454,7 @@ pub fn corpus() -> Vec<Case> {
https( https(
"auth forbidden", "auth forbidden",
a, a,
Req::get(a, "/").header("cookie", "authelia_session=forbidden"), Req::get(a, "/").header("cookie", &session("forbidden")),
), ),
https( https(
"auth allowed with session", "auth allowed with session",
@@ -451,11 +468,19 @@ pub fn corpus() -> Vec<Case> {
.header(good.0, good.1) .header(good.0, good.1)
.header("remote-user", "mallory"), .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( https(
"auth allowed without identity strips spoofed", "auth allowed without identity strips spoofed",
a, a,
Req::get(a, "/me") Req::get(a, "/me")
.header("cookie", "authelia_session=nameless") .header("cookie", &session("nameless"))
.header("remote-user", "mallory"), .header("remote-user", "mallory"),
), ),
https( https(
@@ -468,24 +493,55 @@ pub fn corpus() -> Vec<Case> {
a, a,
Req::get(a, "/search?q=a+b").header(good.0, good.1), Req::get(a, "/search?q=a+b").header(good.0, good.1),
), ),
Case { https(
name: "websocket denied by auth", "auth allowed POST keeps the body",
action: Action::Websocket { a,
sni: "wsauth.test", Req::new("POST", a, "/form")
host: "wsauth.test", .header(good.0, good.1)
headers: vec![], .body(b"field=value"),
}, ),
headers: STD, https(
}, "auth answers 100 Continue first",
Case { a,
name: "websocket allowed by auth", Req::get(a, "/").header("cookie", &session("continue-ok")),
action: Action::Websocket { ),
sni: "wsauth.test", https(
host: "wsauth.test", "auth answers 9 informational heads first",
headers: vec![good], a,
}, Req::get(a, "/").header("cookie", &session("continue-x9")),
headers: &["upgrade"], ),
}, 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("healthy upstream", "hc.test", Req::get("hc.test", "/")),
https( https(
"all upstreams unhealthy", "all upstreams unhealthy",
@@ -497,6 +553,20 @@ pub fn corpus() -> Vec<Case> {
] ]
} }
/// 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. /// What one engine answered, normalised for comparison.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct Observation { pub struct Observation {
@@ -505,56 +575,59 @@ pub struct Observation {
pub body: String, pub body: String,
} }
fn observe(resp: &Resp, case: &Case, t: &Target) -> Observation { fn observe_parts(status: u16, raw: &[(String, String)], body: &[u8], t: &Target) -> Observation {
let mut headers = BTreeMap::new(); let mut headers: BTreeMap<String, String> = BTreeMap::new();
for h in case.headers { for (n, v) in raw {
let all = resp.header_all(h); let n = n.to_ascii_lowercase();
if !all.is_empty() { if IGNORED_HEADERS.iter().any(|(i, _)| *i == n) {
// The two engines listen on different ports; Location carries the HTTPS port. continue;
let v = all
.join("\n")
.replace(&format!(":{}", t.https.port()), ":<https-port>");
headers.insert((*h).to_owned(), v);
} }
// 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 { Observation {
status: resp.status, status,
headers, headers,
body: String::from_utf8_lossy(&resp.body).into_owned(), 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 { pub async fn run_case(case: &Case, t: &Target, roots: Arc<RootCertStore>) -> Observation {
match &case.action { match &case.action {
Action::Https { sni, req } => match client::https(t.https, sni, roots, req).await { Action::Https { sni, req } => client::https(t.https, sni, roots, req)
Ok(r) => observe(&r, case, t), .await
Err(e) => Observation { .map_or_else(failed, |r| observe(&r, t)),
status: 0, Action::Http { req } => client::http(t.http, req)
headers: BTreeMap::new(), .await
body: format!("client error: {e}"), .map_or_else(failed, |r| observe(&r, t)),
},
},
Action::Http { req } => match client::http(t.http, req).await {
Ok(r) => observe(&r, case, t),
Err(e) => Observation {
status: 0,
headers: BTreeMap::new(),
body: format!("client error: {e}"),
},
},
Action::Websocket { sni, host, headers } => { Action::Websocket { sni, host, headers } => {
match client::websocket(t.https, sni, roots, host, "/socket", headers, "ping").await { match client::websocket(t.https, sni, roots, host, "/socket", headers, "ping").await {
Ok(WsOutcome::Upgraded { status, echo }) => Observation { Ok(WsOutcome::Upgraded {
status, status,
headers: BTreeMap::new(), headers,
body: format!("echo: {echo}"), echo,
}, }) => observe_parts(status, &headers, format!("echo: {echo}").as_bytes(), t),
Ok(WsOutcome::Refused(r)) => observe(&r, case, t), Ok(WsOutcome::Refused(r)) => observe(&r, t),
Err(e) => Observation { Err(e) => failed(e),
status: 0,
headers: BTreeMap::new(),
body: format!("client error: {e}"),
},
} }
} }
} }
@@ -566,19 +639,125 @@ pub struct Outcome {
pub caddy: Observation, pub caddy: Observation,
} }
/// Documented, accepted differences between the engines, each with its reason. Anything /// How a documented divergence is recognised. Each rule is narrow on purpose.
/// else is a mismatch. pub enum Rule {
pub const KNOWN_DIVERGENCES: &[(&str, &str)] = &[( /// Caddy has `header` with one of `values` and Ianitor has no such header; with `only_if`,
"KD-1", /// Caddy's answer must also carry that header/value pair (the upstream's own report).
"Caddy (Go net/http) adds a sniffed Content-Type when the upstream sends none; \ ExtraHeaderInCaddy {
Ianitor passes the upstream response unchanged (no MIME sniffing).", 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,
},
}
/// Content types Go's `http.DetectContentType` produces for small text and binary bodies. pub struct Divergence {
const SNIFFED: [&str; 3] = [ 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/plain; charset=utf-8",
"text/html; charset=utf-8", "text/html; charset=utf-8",
"application/octet-stream", "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 { impl Outcome {
@@ -586,24 +765,46 @@ impl Outcome {
self.ianitor == self.caddy self.ianitor == self.caddy
} }
/// `Some(id)` when the only difference is a documented divergence. /// The divergence ids that explain every difference, or `None`.
pub fn known_divergence(&self) -> Option<&'static str> { pub fn known_divergence(&self) -> Option<String> {
if self.same() { if self.same() {
return None; return None;
} }
let sniffed = self for d in KNOWN_DIVERGENCES {
.caddy if let Rule::Status {
.headers case,
.get("content-type") ianitor,
.is_some_and(|v| SNIFFED.contains(&v.as_str())); caddy,
if sniffed && !self.ianitor.headers.contains_key("content-type") { } = 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 c = self.caddy.clone();
c.headers.remove("content-type"); let mut ids = Vec::new();
if c == self.ianitor { for d in KNOWN_DIVERGENCES {
return Some("KD-1"); 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);
} }
} }
None }
(!ids.is_empty() && c == self.ianitor).then(|| ids.join("+"))
} }
pub fn mismatch(&self) -> bool { pub fn mismatch(&self) -> bool {
@@ -628,26 +829,37 @@ impl Report {
} }
pub fn render(&self, title: &str) -> String { 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!( let mut s = format!(
"== {title}: {} cases, {} identical, {} known divergence, {} differ\n", "== {title}: {} cases: {} identical, {} identical apart from Via/Server (KD-2, KD-3), \
{} other known divergence, {} differ\n",
self.outcomes.len(), self.outcomes.len(),
self.outcomes.iter().filter(|o| o.same()).count(), self.outcomes.iter().filter(|o| o.same()).count(),
self.known().len(), identity,
self.known().len() - identity,
self.mismatches().len() self.mismatches().len()
); );
for o in &self.outcomes { for o in &self.outcomes {
if o.same() { if o.same() {
let _ = writeln!(s, " same {:3} {}", o.ianitor.status, o.name); let _ = writeln!(s, " same {:3} {}", o.ianitor.status, o.name);
} else if let Some(kd) = o.known_divergence() { } else if let Some(kd) = o.known_divergence() {
let _ = writeln!(s, " {kd:<4} {:3} {}", o.ianitor.status, o.name); let _ = writeln!(s, " {kd:<10} {:3} {}", o.ianitor.status, o.name);
} else { } else {
let _ = writeln!(s, " DIFF {}", o.name); let _ = writeln!(s, " DIFF {}", o.name);
let _ = writeln!(s, " ianitor: {:?}", short(&o.ianitor)); for d in differences(&o.ianitor, &o.caddy) {
let _ = writeln!(s, " caddy: {:?}", short(&o.caddy)); let _ = writeln!(s, " {d}");
} }
} }
for (id, why) in KNOWN_DIVERGENCES { }
let _ = writeln!(s, " {id}: {why}"); 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 s
} }
@@ -721,3 +933,27 @@ pub fn break_edge(json: &str) -> String {
pub async fn settle() { pub async fn settle() {
tokio::time::sleep(Duration::from_millis(2500)).await; 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
}
+22 -10
View File
@@ -5,16 +5,27 @@
//! The differential suite (ROADMAP §5 layer 1). Needs the `caddy` binary on PATH (or //! 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`. //! `$IANITOR_CADDY_BIN`); without it the tests fail unless `IANITOR_ALLOW_SKIP=1`.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use ianitor_diff::{ #[cfg(not(unix))]
Env, break_caddy, break_edge, compile_pair, corpus, run_corpus, settle, start_caddy, start_edge, #[test]
}; fn skipped_on_windows() {
use ianitor_testkit::proc::require_binary; eprintln!(
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
file!()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[cfg(unix)]
async fn ianitor_and_caddy_answer_the_corpus_identically() { 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 { let Some(caddy_bin) = require_binary("caddy") else {
return; return;
}; };
@@ -48,10 +59,10 @@ async fn ianitor_and_caddy_answer_the_corpus_identically() {
"corpus covers status {wanted}: {statuses:?}" "corpus covers status {wanted}: {statuses:?}"
); );
} }
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_deliberately_broken_compiler_is_caught() { async fn a_deliberately_broken_compiler_is_caught() {
let Some(caddy_bin) = require_binary("caddy") else { let Some(caddy_bin) = require_binary("caddy") else {
return; return;
}; };
@@ -86,4 +97,5 @@ async fn a_deliberately_broken_compiler_is_caught() {
diff2.contains(&"secret header cannot be preset"), diff2.contains(&"secret header cannot be preset"),
"{diff2:?}" "{diff2:?}"
); );
}
} }
+9 -1
View File
@@ -11,7 +11,8 @@
//! - `Authorization: Bearer good` → 200 with identity; any other Authorization → 401 + WWW-Authenticate //! - `Authorization: Bearer good` → 200 with identity; any other Authorization → 401 + WWW-Authenticate
//! - cookie `authelia_session=good` → 200 with identity; `nameless` → 200 without identity; //! - cookie `authelia_session=good` → 200 with identity; `nameless` → 200 without identity;
//! `forbidden` → 403 //! `forbidden` → 403
//! - misbehaving answers, by cookie: `continue-ok` (100 Continue, then 200), `big-ok` / //! - 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), //! `big-deny` (200 / 401 with a 5 MB body), `truncated-ok` (200 whose body is cut short),
//! `switch` (101 Switching Protocols), `hang` (never answers) //! `switch` (101 Switching Protocols), `hang` (never answers)
//! - otherwise GET/HEAD → 302 to the portal with `rd`, other methods → 401 //! - otherwise GET/HEAD → 302 to the portal with `rd`, other methods → 401
@@ -106,6 +107,13 @@ fn decide(req: &Recorded) -> Reply {
b.extend(allowed(true)); b.extend(allowed(true));
b 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" => { "big-ok" => {
let mut hs: Vec<(&str, &str)> = vec![("X-Sent-Content-Type", "none")]; let mut hs: Vec<(&str, &str)> = vec![("X-Sent-Content-Type", "none")];
hs.extend(IDENTITY); hs.extend(IDENTITY);
+20 -2
View File
@@ -183,7 +183,11 @@ pub async fn http(addr: SocketAddr, req: &Req) -> io::Result<Resp> {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsOutcome { pub enum WsOutcome {
/// 101, the echoed message. /// 101, the echoed message.
Upgraded { status: u16, echo: String }, Upgraded {
status: u16,
headers: Vec<(String, String)>,
echo: String,
},
/// The upgrade was answered with a normal HTTP response. /// The upgrade was answered with a normal HTTP response.
Refused(Resp), Refused(Resp),
} }
@@ -212,6 +216,16 @@ pub async fn websocket(
match tokio_tungstenite::client_async(request, s).await { match tokio_tungstenite::client_async(request, s).await {
Ok((mut ws, resp)) => { Ok((mut ws, resp)) => {
let status = resp.status().as_u16(); 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)) ws.send(tungstenite::Message::text(message))
.await .await
.map_err(other)?; .map_err(other)?;
@@ -220,7 +234,11 @@ pub async fn websocket(
other_msg => return Err(other(format!("no echo: {other_msg:?}"))), other_msg => return Err(other(format!("no echo: {other_msg:?}"))),
}; };
let _ = ws.close(None).await; let _ = ws.close(None).await;
Ok(WsOutcome::Upgraded { status, echo }) Ok(WsOutcome::Upgraded {
status,
headers,
echo,
})
} }
Err(tungstenite::Error::Http(resp)) => { Err(tungstenite::Error::Http(resp)) => {
let status = resp.status().as_u16(); let status = resp.status().as_u16();
+128 -2
View File
@@ -3,7 +3,8 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/. // 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, //! 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. //! 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::net::SocketAddr;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -69,7 +70,13 @@ impl RawServer {
Ok(n) => buf.extend_from_slice(&chunk[..n]), Ok(n) => buf.extend_from_slice(&chunk[..n]),
} }
} }
let Some(req) = parse(&buf) else { return }; 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()); requests.lock().unwrap().push(req.clone());
match handler(&req) { match handler(&req) {
Reply::Bytes(b) => { Reply::Bytes(b) => {
@@ -93,6 +100,77 @@ impl RawServer {
} }
} }
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> { fn parse(buf: &[u8]) -> Option<Recorded> {
let end = buf.windows(4).position(|w| w == b"\r\n\r\n")?; let end = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
let head = std::str::from_utf8(&buf[..end]).ok()?; let head = std::str::from_utf8(&buf[..end]).ok()?;
@@ -112,3 +190,51 @@ fn parse(buf: &[u8]) -> Option<Recorded> {
body: Vec::new(), 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()),
]
);
}
}
+2 -1
View File
@@ -23,8 +23,9 @@ use crate::fnv64;
/// Request headers the echo server reports back (lowercase). Secret-carrying headers are /// 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. /// reported as a hash only, so a passing test never needs the value in a response body.
pub const ECHO_HEADERS: [&str; 12] = [ pub const ECHO_HEADERS: [&str; 13] = [
"host", "host",
"x-remove-me-too",
"x-forwarded-for", "x-forwarded-for",
"x-forwarded-proto", "x-forwarded-proto",
"x-forwarded-host", "x-forwarded-host",