From 8f79ce042c74419276cdb9b94e5a6a29011e892f Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 14:22:48 +0100 Subject: [PATCH 01/27] [repo] Hygiene: .gitignore and pre-commit hook --- .gitattributes | 3 ++ .githooks/pre-commit | 65 +++++++++++++++++++++++++ .githooks/test-pre-commit.sh | 94 ++++++++++++++++++++++++++++++++++++ .gitignore | 34 +++++++++++++ 4 files changed, 196 insertions(+) create mode 100644 .gitattributes create mode 100755 .githooks/pre-commit create mode 100755 .githooks/test-pre-commit.sh create mode 100644 .gitignore diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e2d7a31 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +* text=auto eol=lf +*.png binary +*.ico binary diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..872895a --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,65 @@ +#!/bin/sh +# SPDX-License-Identifier: MPL-2.0 +# +# Ianitor pre-commit hook. Rejects staged files that must never be in git: +# - binaries (anything git itself classifies as binary) +# - private keys (PEM / OpenSSH / PKCS#8 / PGP headers, and key-store file names) +# - files over 5 MB +# - build output and dependencies (target/, node_modules/, dist/) +# +# Enable once per clone: git config core.hooksPath .githooks +# Test it: sh .githooks/test-pre-commit.sh +# Plain POSIX sh: works in Git Bash on Windows and on Linux. + +LIMIT=5242880 # 5 MiB + +# Every check prints one "FAIL" line on stdout per problem (reasons go to stderr), +# so the loop can run in a pipeline subshell and still be counted here. +failures=$( + # numstat prints "--path" for files git treats as binary. + git -c core.quotePath=false diff --cached --numstat --diff-filter=ACMR | while IFS= read -r line; do + added=${line%%" "*} + rest=${line#*" "} + deleted=${rest%%" "*} + path=${rest#*" "} + if [ "$added" = "-" ] && [ "$deleted" = "-" ]; then + printf 'pre-commit: rejected %s: binary file\n' "$path" >&2 + echo FAIL + fi + done + + git -c core.quotePath=false diff --cached --name-only --diff-filter=ACMR | while IFS= read -r path; do + case "/$path" in + */target/*|*/node_modules/*|*/dist/*) + printf 'pre-commit: rejected %s: build output or dependency directory\n' "$path" >&2 + echo FAIL ;; + esac + + base=${path##*/} + case "$base" in + *.pub) ;; + *.key|*.p12|*.pfx|*.jks|*.keystore|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 + echo FAIL ;; + esac + + # Size of the staged blob, not of the working-tree file. + size=$(git cat-file -s ":$path" 2>/dev/null || echo 0) + if [ "$size" -gt "$LIMIT" ]; then + printf 'pre-commit: rejected %s: %s bytes is over the 5 MB limit\n' "$path" "$size" >&2 + echo FAIL + fi + + if git cat-file -p ":$path" 2>/dev/null | grep -E -q -e '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----'; then + printf 'pre-commit: rejected %s: contains a private key\n' "$path" >&2 + echo FAIL + fi + done +) + +case "$failures" in + *FAIL*) + printf 'pre-commit: commit blocked. Unstage the files above (git rm --cached ).\n' >&2 + exit 1 ;; +esac +exit 0 diff --git a/.githooks/test-pre-commit.sh b/.githooks/test-pre-commit.sh new file mode 100755 index 0000000..6befb3f --- /dev/null +++ b/.githooks/test-pre-commit.sh @@ -0,0 +1,94 @@ +#!/bin/sh +# 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 a normal file is accepted. +# Usage: sh .githooks/test-pre-commit.sh (Git Bash on Windows 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 +git commit -q --allow-empty -m base --no-gpg-sign + +pass=0 +fail=0 + +# expect (file must already exist) +expect() { + want=$1; what=$2; path=$3 + git add -f -- "$path" + if git commit -q -m "$what" --no-gpg-sign >/dev/null 2>"$WORK/.err"; then got=accept; else got=reject; 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 + # Leave the index clean for the next case. + git reset -q --hard HEAD >/dev/null 2>&1 + git clean -q -fdx >/dev/null 2>&1 +} + +B='-----BEGIN' +E='-----END' + +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 + +printf '%s RSA PRIVATE KEY-----\nMIIBOgIBAAJBAK\n%s RSA PRIVATE KEY-----\n' "$B" "$E" > 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 'not really a key\n' > server.key +expect reject "*.key file name" 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 + +head -c 6291456 /dev/zero | tr '\000' 'a' > big.txt +expect reject "6 MB text file" big.txt + +head -c 4194304 /dev/zero | tr '\000' 'a' > medium.txt +expect accept "4 MB text file" medium.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 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 + +printf '\nhook: %d passed, %d failed\n' "$pass" "$fail" +[ "$fail" -eq 0 ] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..11607db --- /dev/null +++ b/.gitignore @@ -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 -- 2.53.0 From c1abe88688ff6bb5f4745b045187b8fa2aa03905 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 14:31:04 +0100 Subject: [PATCH 02/27] [repo] Workspace: cargo workspace, MPL-2.0 license, control and web placeholders --- Cargo.lock | 513 +++++++++++++++++++++++++++++++++++++ Cargo.toml | 32 +++ LICENSE | 373 +++++++++++++++++++++++++++ apps/web/package.json | 10 + crates/control/Cargo.toml | 15 ++ crates/control/src/main.rs | 12 + crates/core/Cargo.toml | 18 ++ crates/core/src/lib.rs | 5 + crates/edge/Cargo.toml | 14 + crates/edge/src/lib.rs | 5 + crates/edge/src/main.rs | 5 + package.json | 5 + pnpm-workspace.yaml | 3 + tests/diff/Cargo.toml | 15 ++ tests/diff/src/lib.rs | 5 + 15 files changed, 1030 insertions(+) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 apps/web/package.json create mode 100644 crates/control/Cargo.toml create mode 100644 crates/control/src/main.rs create mode 100644 crates/core/Cargo.toml create mode 100644 crates/core/src/lib.rs create mode 100644 crates/edge/Cargo.toml create mode 100644 crates/edge/src/lib.rs create mode 100644 crates/edge/src/main.rs create mode 100644 package.json create mode 100644 pnpm-workspace.yaml create mode 100644 tests/diff/Cargo.toml create mode 100644 tests/diff/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..7022890 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,513 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "ianitor-control" +version = "0.1.0" + +[[package]] +name = "ianitor-core" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror", + "toml", + "url", +] + +[[package]] +name = "ianitor-diff" +version = "0.1.0" +dependencies = [ + "ianitor-core", + "ianitor-edge", +] + +[[package]] +name = "ianitor-edge" +version = "0.1.0" +dependencies = [ + "ianitor-core", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..9d8972e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,32 @@ +[workspace] +resolver = "3" +members = ["crates/core", "crates/edge", "crates/control", "tests/diff"] + +[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" } +serde = { version = "1.0.228", features = ["derive"] } +serde_json = "1.0.145" +toml = "1.2.1" +thiserror = "2.0.17" +url = "2.5.7" + +[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 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d0a1fa1 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..591d4d1 --- /dev/null +++ b/apps/web/package.json @@ -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')\"" + } +} diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml new file mode 100644 index 0000000..8b31672 --- /dev/null +++ b/crates/control/Cargo.toml @@ -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 diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs new file mode 100644 index 0000000..47b4520 --- /dev/null +++ b/crates/control/src/main.rs @@ -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") + ); +} diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml new file mode 100644 index 0000000..51de11d --- /dev/null +++ b/crates/core/Cargo.toml @@ -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 diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs new file mode 100644 index 0000000..1a1db3f --- /dev/null +++ b/crates/core/src/lib.rs @@ -0,0 +1,5 @@ +// 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. diff --git a/crates/edge/Cargo.toml b/crates/edge/Cargo.toml new file mode 100644 index 0000000..aeb65f8 --- /dev/null +++ b/crates/edge/Cargo.toml @@ -0,0 +1,14 @@ +[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 + +[dependencies] +ianitor-core.workspace = true + +[lints] +workspace = true diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs new file mode 100644 index 0000000..117b823 --- /dev/null +++ b/crates/edge/src/lib.rs @@ -0,0 +1,5 @@ +// 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. diff --git a/crates/edge/src/main.rs b/crates/edge/src/main.rs new file mode 100644 index 0000000..a30c179 --- /dev/null +++ b/crates/edge/src/main.rs @@ -0,0 +1,5 @@ +// 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/. + +fn main() {} diff --git a/package.json b/package.json new file mode 100644 index 0000000..cfd6422 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "name": "ianitor-domi", + "private": true, + "license": "MPL-2.0" +} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..3ff5faa --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +packages: + - "apps/*" + - "packages/*" diff --git a/tests/diff/Cargo.toml b/tests/diff/Cargo.toml new file mode 100644 index 0000000..c2e986a --- /dev/null +++ b/tests/diff/Cargo.toml @@ -0,0 +1,15 @@ +[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 + +[lints] +workspace = true diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs new file mode 100644 index 0000000..d664c63 --- /dev/null +++ b/tests/diff/src/lib.rs @@ -0,0 +1,5 @@ +// 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: Ianitor edge versus Caddy on one request corpus. -- 2.53.0 From 9176cc63a40ee5b467ae1c81d7d86e4cd7ab0769 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 14:34:33 +0100 Subject: [PATCH 03/27] [core] Schema: tests first for validation and compiler determinism (red: 37+11 failing) --- crates/core/src/compile/mod.rs | 47 ++ crates/core/src/edge_config.rs | 103 ++++ crates/core/src/error.rs | 92 ++++ crates/core/src/lib.rs | 18 + crates/core/src/model.rs | 225 ++++++++ crates/core/src/validate.rs | 20 + crates/core/tests/compile.rs | 173 ++++++ .../routes/hosts/photos.example.org.toml | 27 + .../routes/hosts/status.example.org.toml | 2 + .../fixtures/routes/hosts/wiki.home.test.toml | 10 + .../core/tests/fixtures/routes/ianitor.toml | 9 + crates/core/tests/schema.rs | 505 ++++++++++++++++++ 12 files changed, 1231 insertions(+) create mode 100644 crates/core/src/compile/mod.rs create mode 100644 crates/core/src/edge_config.rs create mode 100644 crates/core/src/error.rs create mode 100644 crates/core/src/model.rs create mode 100644 crates/core/src/validate.rs create mode 100644 crates/core/tests/compile.rs create mode 100644 crates/core/tests/fixtures/routes/hosts/photos.example.org.toml create mode 100644 crates/core/tests/fixtures/routes/hosts/status.example.org.toml create mode 100644 crates/core/tests/fixtures/routes/hosts/wiki.home.test.toml create mode 100644 crates/core/tests/fixtures/routes/ianitor.toml create mode 100644 crates/core/tests/schema.rs diff --git a/crates/core/src/compile/mod.rs b/crates/core/src/compile/mod.rs new file mode 100644 index 0000000..f3fe41d --- /dev/null +++ b/crates/core/src/compile/mod.rs @@ -0,0 +1,47 @@ +// 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. + +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: `.crt` and `.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, +} + +#[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 { + let _ = (model, options); + Err(CompileError::Serialize("not implemented".into())) +} + +/// Compile to Caddy JSON for the caddy-fallback unit. +pub fn caddy(model: &Model, options: &CompileOptions) -> Result { + let _ = (model, options); + Err(CompileError::Serialize("not implemented".into())) +} diff --git a/crates/core/src/edge_config.rs b/crates/core/src/edge_config.rs new file mode 100644 index 0000000..9dcb8ec --- /dev/null +++ b/crates/core/src/edge_config.rs @@ -0,0 +1,103 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! 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 `.crt` / `.key`. + pub cert_dir: String, + /// Edge state; ACME account and certificates live in `/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, + pub forward_auth: Option, + /// Sorted by hostname. + pub hosts: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EdgeAcme { + pub directory: String, + pub email: Option, +} + +#[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, +} + +#[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, + /// SNI and certificate name when `tls` is set. + 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 `/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, + pub forward_auth: bool, + pub websockets: bool, + pub request_headers: Vec, + pub response_headers: Vec, + pub health_check: Option, + pub access_log: bool, +} diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs new file mode 100644 index 0000000..01e05bf --- /dev/null +++ b/crates/core/src/error.rs @@ -0,0 +1,92 @@ +// 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, 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}: `{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) -> 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); + +impl ValidationErrors { + pub fn errors(&self) -> &[ValidationError] { + &self.0 + } + + pub fn into_errors(self) -> Vec { + 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 {} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 1a1db3f..76dc4a8 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -3,3 +3,21 @@ // 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::{ + AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname, + Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, AUTHELIA_COPY_HEADERS, + LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, +}; +pub use validate::{load, SourceFile}; diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs new file mode 100644 index 0000000..19f5f83 --- /dev/null +++ b/crates/core/src/model.rs @@ -0,0 +1,225 @@ +// 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, + pub tls: TlsMode, + pub auth: AuthMode, + pub request_headers: Vec, + pub response_headers: Vec, + pub websockets: bool, + pub health_check: Option, + 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, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Acme { + pub email: Option, + pub directory: String, +} + +/// Site-wide settings from `ianitor.toml`. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Site { + pub secrets: BTreeSet, + pub forward_auth: Option, + 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, +} + +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"; +/// 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"]; diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs new file mode 100644 index 0000000..90e05c4 --- /dev/null +++ b/crates/core/src/validate.rs @@ -0,0 +1,20 @@ +// 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. + +use crate::{Model, ValidationErrors}; + +/// 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, +} + +/// Parse and validate the site file and every host file. +pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result { + let _ = (site, hosts); + Err(ValidationErrors(Vec::new())) +} diff --git a/crates/core/tests/compile.rs b/crates/core/tests/compile.rs new file mode 100644 index 0000000..a4c5f18 --- /dev/null +++ b/crates/core/tests/compile.rs @@ -0,0 +1,173 @@ +// 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::{load, Model, SourceFile}; + +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 = 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::(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()); +} diff --git a/crates/core/tests/fixtures/routes/hosts/photos.example.org.toml b/crates/core/tests/fixtures/routes/hosts/photos.example.org.toml new file mode 100644 index 0000000..14af727 --- /dev/null +++ b/crates/core/tests/fixtures/routes/hosts/photos.example.org.toml @@ -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" diff --git a/crates/core/tests/fixtures/routes/hosts/status.example.org.toml b/crates/core/tests/fixtures/routes/hosts/status.example.org.toml new file mode 100644 index 0000000..5af5e95 --- /dev/null +++ b/crates/core/tests/fixtures/routes/hosts/status.example.org.toml @@ -0,0 +1,2 @@ +hostname = "status.example.org" +upstreams = ["http://[::1]:3001"] diff --git a/crates/core/tests/fixtures/routes/hosts/wiki.home.test.toml b/crates/core/tests/fixtures/routes/hosts/wiki.home.test.toml new file mode 100644 index 0000000..a7c9ead --- /dev/null +++ b/crates/core/tests/fixtures/routes/hosts/wiki.home.test.toml @@ -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" diff --git a/crates/core/tests/fixtures/routes/ianitor.toml b/crates/core/tests/fixtures/routes/ianitor.toml new file mode 100644 index 0000000..ea37de4 --- /dev/null +++ b/crates/core/tests/fixtures/routes/ianitor.toml @@ -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" diff --git a/crates/core/tests/schema.rs b/crates/core/tests/schema.rs new file mode 100644 index 0000000..527fade --- /dev/null +++ b/crates/core/tests/schema.rs @@ -0,0 +1,505 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! 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::{ + load, AccessLog, AuthMode, HeaderRule, HeaderValue, SourceFile, TlsMode, ValidationError, + ValidationErrors, +}; + +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 { + load(&site(), &[SourceFile { name: "hosts/app.test.toml", contents }]) +} + +fn errors(contents: &str) -> Vec { + 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 = ["http://127.0.0.1:8080", "https://backend.lan", "http://[::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 = h.upstreams.iter().map(|u| u.to_string()).collect(); + assert_eq!(ups, ["http://127.0.0.1:8080", "https://backend.lan:443", "http://[::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.toml", contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n" }; + let b = SourceFile { name: "a.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::>(); + 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: "a.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: "a.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 r = one(&format!("hostname = {good:?}\nupstreams = [\"http://127.0.0.1:1\"]\n")); + assert!(r.is_ok(), "{good}: {r:?}"); + } +} + +#[test] +fn rejects_duplicate_hostnames_across_files() { + let r = load( + &site(), + &[ + SourceFile { name: "hosts/one.toml", contents: MINIMAL }, + SourceFile { name: "hosts/two.toml", contents: MINIMAL }, + ], + ); + let errs = r.unwrap_err(); + assert_eq!( + errs.errors(), + [ValidationError::DuplicateHostname { + hostname: "app.test".into(), + first: "hosts/one.toml".into(), + second: "hosts/two.toml".into() + }] + ); +} + +#[test] +fn duplicate_detection_is_independent_of_file_order() { + let r = load( + &site(), + &[ + SourceFile { name: "hosts/two.toml", contents: MINIMAL }, + SourceFile { name: "hosts/one.toml", contents: MINIMAL }, + ], + ); + let errs = r.unwrap_err(); + assert!(matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/one.toml" && second == "hosts/two.toml")); +} + +#[test] +fn rejects_duplicate_source_file_names() { + let r = load( + &site(), + &[SourceFile { name: "a.toml", contents: MINIMAL }, SourceFile { name: "a.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_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: "a.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: "a.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 e = single_error(&rule("response_headers", &format!("action = \"set\"\nname = \"X-A\"\nvalue = {bad:?}"))); + 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: "a.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: "a.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.toml", contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n" }, + SourceFile { name: "b.toml", contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n" }, + SourceFile { name: "c.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"); + } +} -- 2.53.0 From ff087a14dd7021c7073ec3861323e8d44e8300b1 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 14:36:35 +0100 Subject: [PATCH 04/27] [core] Schema: host file model and validation with typed errors --- crates/core/src/validate.rs | 581 +++++++++++++++++++++++++++++++++++- crates/core/tests/schema.rs | 3 +- 2 files changed, 577 insertions(+), 7 deletions(-) diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index 90e05c4..639a452 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -2,9 +2,21 @@ // 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. +//! Parsing and validation of the routes tree. Route files are hostile input: everything is +//! checked, every problem becomes a typed [`ValidationError`], nothing panics. -use crate::{Model, ValidationErrors}; +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, Model, Scheme, SecretName, Site, TlsMode, + Upstream, UpstreamHost, +}; /// One route file handed in by the caller (core does no I/O). #[derive(Debug, Clone, Copy)] @@ -13,8 +25,565 @@ pub struct SourceFile<'a> { pub contents: &'a str, } -/// Parse and validate the site file and every host file. -pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result { - let _ = (site, hosts); - Err(ValidationErrors(Vec::new())) +// ------------------------------------------------------------------ raw file shapes + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawSite { + #[serde(default)] + secrets: Vec, + forward_auth: Option, + acme: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawForwardAuth { + url: String, + copy_headers: Option>, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawAcme { + email: Option, + directory: Option, +} + +#[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, + secret: Option, +} + +#[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, + #[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, + #[serde(default)] + request_headers: Vec, + #[serde(default)] + response_headers: Vec, +} + +// ------------------------------------------------------------------ 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 { + let mut errors = Vec::new(); + + let site_model = match parse::(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::(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 = 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(f: &SourceFile<'_>) -> Result { + let file = f.name.to_owned(); + // A plain table parse first tells syntax errors apart from schema errors. + if let Err(e) = toml::from_str::(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::(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 { + 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) -> Option { + 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 = match fa.copy_headers { + Some(h) => h, + None => AUTHELIA_COPY_HEADERS.iter().map(|s| (*s).to_owned()).collect(), + }; + let mut seen = BTreeSet::new(); + for h in ©_headers { + if !valid_header_name(h) { + errors.push(E::InvalidHeaderName { file: file.to_owned(), name: h.clone() }); + } 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 let Some(email) = &a.email { + if !valid_email(email) { + 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) -> Option { + let before = errors.len(); + let f = || file.to_owned(); + + if let Err(reason) = check_hostname(&raw.hostname) { + errors.push(E::InvalidHostname { file: f(), hostname: raw.hostname.clone(), reason }); + } + + if raw.upstreams.is_empty() { + errors.push(E::NoUpstreams { file: f() }); + } + let mut upstreams: Vec = Vec::new(); + for u in &raw.upstreams { + match parse_url(u, false) { + Ok((up, _)) => { + if upstreams.contains(&up) { + errors.push(E::DuplicateUpstream { file: f(), url: u.clone() }); + } else { + upstreams.push(up); + } + } + Err(reason) => errors.push(E::BadUpstreamUrl { file: f(), url: u.clone(), reason }), + } + } + + 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 set by forward-auth must not be overridable by a rule. + let identity: Vec = match (auth, site.and_then(|s| s.forward_auth.as_ref())) { + (AuthMode::ForwardAuth, Some(fa)) => fa.copy_headers.iter().map(|h| h.to_ascii_lowercase()).collect(), + (AuthMode::ForwardAuth, None) => AUTHELIA_COPY_HEADERS.iter().map(|h| h.to_ascii_lowercase()).collect(), + _ => 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() && c != b'{' && c != b'}'); + 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, + request: bool, + identity: &[String], + site: Option<&Site>, + errors: &mut Vec, +) -> Vec { + 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. +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::().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)) } diff --git a/crates/core/tests/schema.rs b/crates/core/tests/schema.rs index 527fade..ec5b3a7 100644 --- a/crates/core/tests/schema.rs +++ b/crates/core/tests/schema.rs @@ -397,7 +397,8 @@ fn rejects_invalid_header_names() { #[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 e = single_error(&rule("response_headers", &format!("action = \"set\"\nname = \"X-A\"\nvalue = {bad:?}"))); + 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:?}"); } } -- 2.53.0 From a5823ba33d47e23998b99f82b8a6ef560ccd5ad8 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 14:39:34 +0100 Subject: [PATCH 05/27] [core] Compilers: Pingora runtime config and Caddy JSON, golden files --- crates/core/src/compile/caddy.rs | 339 +++++++++++++++++ crates/core/src/compile/edge.rs | 88 +++++ crates/core/src/compile/mod.rs | 79 +++- crates/core/src/error.rs | 44 ++- crates/core/src/lib.rs | 8 +- crates/core/src/model.rs | 7 +- crates/core/src/validate.rs | 188 ++++++++-- crates/core/tests/compile.rs | 72 +++- crates/core/tests/golden/caddy.json | 558 ++++++++++++++++++++++++++++ crates/core/tests/golden/edge.json | 131 +++++++ crates/core/tests/schema.rs | 428 +++++++++++++++++---- 11 files changed, 1794 insertions(+), 148 deletions(-) create mode 100644 crates/core/src/compile/caddy.rs create mode 100644 crates/core/src/compile/edge.rs create mode 100644 crates/core/tests/golden/caddy.json create mode 100644 crates/core/tests/golden/edge.json diff --git a/crates/core/src/compile/caddy.rs b/crates/core/src/compile/caddy.rs new file mode 100644 index 0000000..bb54087 --- /dev/null +++ b/crates/core/src/compile/caddy.rs @@ -0,0 +1,339 @@ +// 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}; +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 = 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 = 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::>() + }), + ); + https.insert("protocols".into(), json!(["h1", "h2"])); + if !logged.is_empty() { + let names: Map = 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::>() }], + "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 = 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) { + steps.push(json!({ "handle": [forward_auth(fa)] })); + } + if !h.websockets { + steps.push(json!({ + "match": [{ "header_regexp": { "Upgrade": { "pattern": "(?i)^websocket$" } } }], + "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 { + // 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 { + 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) +} diff --git a/crates/core/src/compile/edge.rs b/crates/core/src/compile/edge.rs new file mode 100644 index 0000000..4afdc2a --- /dev/null +++ b/crates/core/src/compile/edge.rs @@ -0,0 +1,88 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Model → [`EdgeConfig`] for the Pingora data plane. + +use super::{CompileOptions, join}; +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, UpstreamHost, +}; + +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(), + }), + 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: SNI is the host name; IP literals send none. + sni: match &u.host { + UpstreamHost::Name(n) => n.clone(), + UpstreamHost::Ip(_) => String::new(), + }, + } +} + +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() }, + } +} diff --git a/crates/core/src/compile/mod.rs b/crates/core/src/compile/mod.rs index f3fe41d..917d4e0 100644 --- a/crates/core/src/compile/mod.rs +++ b/crates/core/src/compile/mod.rs @@ -3,7 +3,19 @@ // 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. +//! 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; @@ -29,19 +41,74 @@ pub struct CompileOptions { #[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 }, + 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 { - let _ = (model, options); - Err(CompileError::Serialize("not implemented".into())) + 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 { - let _ = (model, options); - Err(CompileError::Serialize("not implemented".into())) + 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(()) +} + +/// Join a validated directory and a validated file name. +fn join(dir: &str, file: &str) -> String { + format!("{}/{}", dir.trim_end_matches('/'), file) } diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index 01e05bf..ab02502 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -11,7 +11,11 @@ use std::fmt; #[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, message: String }, + Syntax { + file: String, + line: Option, + message: String, + }, #[error("{file}: unknown field `{field}`")] UnknownField { file: String, field: String }, #[error("{file}: required field `{field}` is missing")] @@ -21,31 +25,55 @@ pub enum ValidationError { #[error("{file} appears twice in the routes")] DuplicateFile { file: String }, #[error("{file}: `{hostname}` is not a valid hostname: {reason}")] - InvalidHostname { file: String, hostname: String, reason: &'static str }, + 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 }, + 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 }, + 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")] + #[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)")] + #[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 }, + 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 }, + 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")] diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 76dc4a8..eda6c33 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -16,8 +16,8 @@ mod validate; pub use error::{ValidationError, ValidationErrors}; pub use model::{ - AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname, - Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, AUTHELIA_COPY_HEADERS, - LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, + 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::{load, SourceFile}; +pub use validate::{SourceFile, load}; diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index 19f5f83..f636ea6 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -222,4 +222,9 @@ pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/d /// Let's Encrypt staging directory. pub const LETSENCRYPT_STAGING: &str = "https://acme-staging-v02.api.letsencrypt.org/directory"; /// 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"]; +pub const AUTHELIA_COPY_HEADERS: [&str; 4] = [ + "Remote-User", + "Remote-Groups", + "Remote-Email", + "Remote-Name", +]; diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index 639a452..2a311c6 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -151,7 +151,9 @@ pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result(f) { @@ -178,7 +180,10 @@ pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result Ok(Model { site, hosts: by_name.into_values().collect() }), + Some(site) if errors.is_empty() => Ok(Model { + site, + hosts: by_name.into_values().collect(), + }), _ => Err(ValidationErrors(errors)), } } @@ -215,7 +220,10 @@ fn classify(file: String, message: &str) -> E { } else if let Some(field) = quoted("missing field `") { E::MissingField { file, field } } else { - E::InvalidValue { file, message: message.to_owned() } + E::InvalidValue { + file, + message: message.to_owned(), + } } } @@ -228,12 +236,18 @@ fn check_site(file: &str, raw: RawSite, errors: &mut Vec) -> Option { if valid_secret_name(&name) { secrets.insert(SecretName(name)); } else { - errors.push(E::InvalidSecretName { file: file.to_owned(), name }); + 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 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) => { @@ -243,39 +257,67 @@ fn check_site(file: &str, raw: RawSite, errors: &mut Vec) -> Option { }; let copy_headers: Vec = match fa.copy_headers { Some(h) => h, - None => AUTHELIA_COPY_HEADERS.iter().map(|s| (*s).to_owned()).collect(), + None => AUTHELIA_COPY_HEADERS + .iter() + .map(|s| (*s).to_owned()) + .collect(), }; let mut seen = BTreeSet::new(); for h in ©_headers { if !valid_header_name(h) { - errors.push(E::InvalidHeaderName { file: file.to_owned(), name: h.clone() }); + 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() }); + 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 }) + Some(ForwardAuth { + upstream, + path_and_query, + copy_headers, + }) }); let acme = match raw.acme { - None => Acme { email: None, directory: LETSENCRYPT_PRODUCTION.to_owned() }, + None => Acme { + email: None, + directory: LETSENCRYPT_PRODUCTION.to_owned(), + }, Some(a) => { - let bad = |reason| E::BadAcme { file: file.to_owned(), reason }; - if let Some(email) = &a.email { - if !valid_email(email) { - errors.push(bad("email is not a plain address like admin@example.org")); - } + 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()); + 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")); + errors.push(bad( + "directory must be an https:// URL without credentials or fragment", + )); + } + Acme { + email: a.email, + directory, } - Acme { email: a.email, directory } } }; - (errors.len() == before).then_some(Site { secrets, forward_auth, acme }) + (errors.len() == before).then_some(Site { + secrets, + forward_auth, + acme, + }) } fn valid_secret_name(n: &str) -> bool { @@ -283,15 +325,20 @@ fn valid_secret_name(n: &str) -> bool { !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'-') + && 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 }; + 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)) + && local + .bytes() + .all(|c| c.is_ascii_graphic() && !b"{}@<>\"\\,;:[]()".contains(&c)) } fn valid_acme_directory(d: &str) -> bool { @@ -302,7 +349,8 @@ fn valid_acme_directory(d: &str) -> bool { && u.password().is_none() && u.fragment().is_none() && u.host().is_some() - && d.bytes().all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}') + && d.bytes() + .all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}') } Err(_) => false, } @@ -315,7 +363,11 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec let f = || file.to_owned(); if let Err(reason) = check_hostname(&raw.hostname) { - errors.push(E::InvalidHostname { file: f(), hostname: raw.hostname.clone(), reason }); + errors.push(E::InvalidHostname { + file: f(), + hostname: raw.hostname.clone(), + reason, + }); } if raw.upstreams.is_empty() { @@ -326,15 +378,30 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec match parse_url(u, false) { Ok((up, _)) => { if upstreams.contains(&up) { - errors.push(E::DuplicateUpstream { file: f(), url: u.clone() }); + errors.push(E::DuplicateUpstream { + file: f(), + url: u.clone(), + }); } else { upstreams.push(up); } } - Err(reason) => errors.push(E::BadUpstreamUrl { file: f(), url: u.clone(), reason }), + 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, @@ -345,8 +412,15 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec // Identity headers set by forward-auth must not be overridable by a rule. let identity: Vec = match (auth, site.and_then(|s| s.forward_auth.as_ref())) { - (AuthMode::ForwardAuth, Some(fa)) => fa.copy_headers.iter().map(|h| h.to_ascii_lowercase()).collect(), - (AuthMode::ForwardAuth, None) => AUTHELIA_COPY_HEADERS.iter().map(|h| h.to_ascii_lowercase()).collect(), + (AuthMode::ForwardAuth, Some(fa)) => fa + .copy_headers + .iter() + .map(|h| h.to_ascii_lowercase()) + .collect(), + (AuthMode::ForwardAuth, None) => AUTHELIA_COPY_HEADERS + .iter() + .map(|h| h.to_ascii_lowercase()) + .collect(), _ => Vec::new(), }; let request_headers = check_rules(file, raw.request_headers, true, &identity, site, errors); @@ -356,13 +430,21 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec 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() && c != b'{' && c != b'}'); + && hc + .path + .bytes() + .all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}'); if !ok_path { - errors.push(bad("path must start with '/' and contain only visible ASCII without '{' or '}'")); + 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 }), + 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 @@ -430,7 +512,10 @@ fn check_rules( for r in raw { let header = r.name.clone(); if !valid_header_name(&r.name) { - errors.push(E::InvalidHeaderName { file: f(), name: r.name }); + errors.push(E::InvalidHeaderName { + file: f(), + name: r.name, + }); continue; } let lower = r.name.to_ascii_lowercase(); @@ -442,23 +527,42 @@ fn check_rules( errors.push(E::DuplicateHeaderRule { file: f(), header }); continue; } - let bad = |reason| E::BadHeaderRule { file: f(), header: header.clone(), reason }; + 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, 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 }), + 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 }); + errors.push(E::UndefinedSecret { + file: f(), + secret: s, + }); } else { - out.push(HeaderRule::Set { name: r.name, value: HeaderValue::Secret(SecretName(s)) }); + out.push(HeaderRule::Set { + name: r.name, + value: HeaderValue::Secret(SecretName(s)), + }); } } } @@ -470,7 +574,8 @@ fn check_rules( fn valid_header_name(n: &str) -> bool { !n.is_empty() && n.len() <= 256 - && n.bytes().all(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&c)) + && n.bytes() + .all(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&c)) } fn check_header_value(v: &str) -> Result<(), &'static str> { @@ -521,7 +626,10 @@ pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> { 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'-') { + 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('-') { diff --git a/crates/core/tests/compile.rs b/crates/core/tests/compile.rs index a4c5f18..742ba98 100644 --- a/crates/core/tests/compile.rs +++ b/crates/core/tests/compile.rs @@ -12,7 +12,7 @@ use std::path::{Path, PathBuf}; use ianitor_core::compile::{self, CompileError, CompileOptions}; use ianitor_core::edge_config::EdgeConfig; -use ianitor_core::{load, Model, SourceFile}; +use ianitor_core::{Model, SourceFile, load}; fn fixtures() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/routes") @@ -34,15 +34,33 @@ fn host_files(reverse: bool) -> Vec<(String, String)> { } files .into_iter() - .map(|p| (format!("hosts/{}", p.file_name().unwrap().to_string_lossy()), read(&p))) + .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 = files.iter().map(|(n, c)| SourceFile { name: n, contents: c }).collect(); - load(&SourceFile { name: "ianitor.toml", contents: &site }, &sources).expect("fixtures are valid") + let sources: Vec = 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 { @@ -64,7 +82,11 @@ fn edge_compiler_is_deterministic() { 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"); + assert_eq!( + first, + compile::edge(&model(true), &options()).unwrap(), + "file order must not matter" + ); } #[test] @@ -74,7 +96,11 @@ fn caddy_compiler_is_deterministic() { 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"); + assert_eq!( + first, + compile::caddy(&model(true), &options()).unwrap(), + "file order must not matter" + ); } #[test] @@ -84,7 +110,10 @@ fn determinism_holds_across_threads() { .map(|i| { s.spawn(move || { let m = model(i % 2 == 0); - (compile::edge(&m, &options()).unwrap(), compile::caddy(&m, &options()).unwrap()) + ( + compile::edge(&m, &options()).unwrap(), + compile::caddy(&m, &options()).unwrap(), + ) }) }) .collect(); @@ -124,7 +153,10 @@ fn caddy_output_is_valid_json_with_servers() { 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!( + 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] { @@ -136,8 +168,14 @@ fn outputs_reference_secrets_by_name_only() { 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 { .. }))); + assert!(matches!( + compile::edge(&model(false), &o), + Err(CompileError::BadOption { .. }) + )); + assert!(matches!( + compile::caddy(&model(false), &o), + Err(CompileError::BadOption { .. }) + )); } #[test] @@ -150,7 +188,9 @@ fn rejects_path_options_that_would_break_out_of_json_or_placeholders() { } fn golden(name: &str, actual: &str) { - let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden").join(name); + 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; @@ -164,10 +204,16 @@ fn golden(name: &str, actual: &str) { #[test] fn edge_output_matches_golden_file() { - golden("edge.json", &compile::edge(&model(false), &options()).unwrap()); + 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()); + golden( + "caddy.json", + &compile::caddy(&model(false), &options()).unwrap(), + ); } diff --git a/crates/core/tests/golden/caddy.json b/crates/core/tests/golden/caddy.json new file mode 100644 index 0000000..0fd530c --- /dev/null +++ b/crates/core/tests/golden/caddy.json @@ -0,0 +1,558 @@ +{ + "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": [ + { + "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)^websocket$" + } + } + } + ] + }, + { + "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" + } +} diff --git a/crates/core/tests/golden/edge.json b/crates/core/tests/golden/edge.json new file mode 100644 index 0000000..a6b4249 --- /dev/null +++ b/crates/core/tests/golden/edge.json @@ -0,0 +1,131 @@ +{ + "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": "" + }, + "path_and_query": "/api/authz/forward-auth", + "copy_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": "" + }, + { + "address": "127.0.0.1:2343", + "tls": false, + "sni": "" + } + ], + "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": "" + } + ], + "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 + } + ] +} diff --git a/crates/core/tests/schema.rs b/crates/core/tests/schema.rs index ec5b3a7..4b7a101 100644 --- a/crates/core/tests/schema.rs +++ b/crates/core/tests/schema.rs @@ -8,8 +8,8 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use ianitor_core::{ - load, AccessLog, AuthMode, HeaderRule, HeaderValue, SourceFile, TlsMode, ValidationError, - ValidationErrors, + AccessLog, AuthMode, HeaderRule, HeaderValue, SourceFile, TlsMode, ValidationError, + ValidationErrors, load, }; const SITE: &str = r#" @@ -20,11 +20,20 @@ url = "http://127.0.0.1:9091/api/authz/forward-auth" "#; fn site() -> SourceFile<'static> { - SourceFile { name: "ianitor.toml", contents: SITE } + SourceFile { + name: "ianitor.toml", + contents: SITE, + } } fn one(contents: &str) -> Result { - load(&site(), &[SourceFile { name: "hosts/app.test.toml", contents }]) + load( + &site(), + &[SourceFile { + name: "hosts/app.test.toml", + contents, + }], + ) } fn errors(contents: &str) -> Vec { @@ -68,10 +77,9 @@ fn minimal_host_gets_documented_defaults() { #[test] fn full_host_is_accepted() { - let model = one( - r#" + let model = one(r#" hostname = "app.test" -upstreams = ["http://127.0.0.1:8080", "https://backend.lan", "http://[::1]:9000/"] +upstreams = ["https://127.0.0.1:8443", "https://backend.lan", "https://[::1]:9000/"] tls = "domi" auth = "forward-auth" websockets = false @@ -95,8 +103,7 @@ name = "X-Debug" 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); @@ -108,12 +115,27 @@ value = "max-age=31536000" assert_eq!(hc.path, "/healthz"); assert_eq!(hc.interval_secs, 10); let ups: Vec = h.upstreams.iter().map(|u| u.to_string()).collect(); - assert_eq!(ups, ["http://127.0.0.1:8080", "https://backend.lan:443", "http://[::1]:9000"]); + 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()) } + 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.request_headers[1], HeaderRule::Remove { name: "X-Debug".into() }); assert_eq!( h.response_headers[0], HeaderRule::Set { @@ -125,18 +147,38 @@ value = "max-age=31536000" #[test] fn hosts_are_sorted_by_hostname_whatever_the_file_order() { - let a = SourceFile { name: "b.toml", contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n" }; - let b = SourceFile { name: "a.toml", contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n" }; + let a = SourceFile { + name: "b.toml", + contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + }; + let b = SourceFile { + name: "a.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::>(); + let names = |m: &ianitor_core::Model| { + m.hosts() + .iter() + .map(|h| h.hostname.to_string()) + .collect::>() + }; 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: "a.toml", contents: MINIMAL }]); + let m = load( + &SourceFile { + name: "ianitor.toml", + contents: "", + }, + &[SourceFile { + name: "a.toml", + contents: MINIMAL, + }], + ); assert!(m.is_ok(), "{m:?}"); } @@ -145,20 +187,34 @@ fn empty_site_file_is_allowed() { #[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() }); + 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:?}"); + 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:?}"); + 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] @@ -166,14 +222,23 @@ 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:?}"); + 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: "a.toml", contents: MINIMAL }], + &SourceFile { + name: "ianitor.toml", + contents: "secrets = []\nsecret_values = { a = \"b\" }\n", + }, + &[SourceFile { + name: "a.toml", + contents: MINIMAL, + }], ); let errs = r.unwrap_err(); assert!( @@ -184,7 +249,9 @@ fn rejects_unknown_field_in_site_file() { #[test] fn rejects_unknown_enum_value() { - let e = single_error("hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ntls = \"selfsigned\"\n"); + let e = single_error( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ntls = \"selfsigned\"\n", + ); assert!(matches!(e, ValidationError::InvalidValue { .. }), "{e:?}"); } @@ -205,13 +272,25 @@ fn rejects_toml_syntax_error() { #[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() }); + 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() }); + assert_eq!( + e, + ValidationError::MissingField { + file: "hosts/app.test.toml".into(), + field: "upstreams".into() + } + ); } #[test] @@ -219,11 +298,26 @@ 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", + "", + "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")); + 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:?}" @@ -233,8 +327,16 @@ fn rejects_bad_hostnames() { #[test] fn accepts_good_hostnames() { - for good in ["localhost", "a.b", "app.test", "x-1.example.org", "0day.example.org"] { - let r = one(&format!("hostname = {good:?}\nupstreams = [\"http://127.0.0.1:1\"]\n")); + for good in [ + "localhost", + "a.b", + "app.test", + "x-1.example.org", + "0day.example.org", + ] { + let r = one(&format!( + "hostname = {good:?}\nupstreams = [\"http://127.0.0.1:1\"]\n" + )); assert!(r.is_ok(), "{good}: {r:?}"); } } @@ -244,8 +346,14 @@ fn rejects_duplicate_hostnames_across_files() { let r = load( &site(), &[ - SourceFile { name: "hosts/one.toml", contents: MINIMAL }, - SourceFile { name: "hosts/two.toml", contents: MINIMAL }, + SourceFile { + name: "hosts/one.toml", + contents: MINIMAL, + }, + SourceFile { + name: "hosts/two.toml", + contents: MINIMAL, + }, ], ); let errs = r.unwrap_err(); @@ -264,21 +372,43 @@ fn duplicate_detection_is_independent_of_file_order() { let r = load( &site(), &[ - SourceFile { name: "hosts/two.toml", contents: MINIMAL }, - SourceFile { name: "hosts/one.toml", contents: MINIMAL }, + SourceFile { + name: "hosts/two.toml", + contents: MINIMAL, + }, + SourceFile { + name: "hosts/one.toml", + contents: MINIMAL, + }, ], ); let errs = r.unwrap_err(); - assert!(matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/one.toml" && second == "hosts/two.toml")); + assert!( + matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/one.toml" && second == "hosts/two.toml") + ); } #[test] fn rejects_duplicate_source_file_names() { let r = load( &site(), - &[SourceFile { name: "a.toml", contents: MINIMAL }, SourceFile { name: "a.toml", contents: MINIMAL }], + &[ + SourceFile { + name: "a.toml", + contents: MINIMAL, + }, + SourceFile { + name: "a.toml", + contents: MINIMAL, + }, + ], + ); + assert!( + r.unwrap_err() + .errors() + .iter() + .any(|e| matches!(e, ValidationError::DuplicateFile { .. })) ); - assert!(r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::DuplicateFile { .. }))); } // ---------------------------------------------------------------- upstreams @@ -310,6 +440,17 @@ fn rejects_bad_upstream_urls() { } } +#[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"); @@ -318,8 +459,13 @@ fn rejects_empty_upstream_list() { #[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:?}"); + 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 @@ -329,19 +475,35 @@ 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() }); + 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: "ianitor.toml", + contents: "", + }, &[SourceFile { name: "a.toml", - contents: &format!("{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n"), + 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 { .. }))); + assert!( + r.unwrap_err() + .errors() + .iter() + .any(|e| matches!(e, ValidationError::UndefinedSecret { .. })) + ); } #[test] @@ -349,19 +511,30 @@ 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:?}"); + 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: "a.toml", contents: MINIMAL }], + &SourceFile { + name: "ianitor.toml", + contents: &format!("secrets = [{bad:?}]\n"), + }, + &[SourceFile { + name: "a.toml", + contents: MINIMAL, + }], ); let errs = r.unwrap_err(); assert!( - errs.errors().iter().any(|e| matches!(e, ValidationError::InvalidSecretName { name, .. } if name == bad)), + errs.errors().iter().any( + |e| matches!(e, ValidationError::InvalidSecretName { name, .. } if name == bad) + ), "{bad:?}: {errs:?}" ); } @@ -376,38 +549,92 @@ fn rule(list: &str, body: &str) -> String { #[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\"")), + ( + "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:?}"); + 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:?}"); + 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", "ü"] { + 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:?}"); + 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:?}"); + 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:?}" + ); } } @@ -417,7 +644,10 @@ fn identity_headers_are_protected_on_forward_auth_hosts() { "{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:?}"); + assert!( + matches!(e, ValidationError::ProtectedHeader { .. }), + "{e:?}" + ); } #[test] @@ -426,7 +656,10 @@ fn rejects_duplicate_header_rules_case_insensitively() { "{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:?}"); + assert!( + matches!(e, ValidationError::DuplicateHeaderRule { .. }), + "{e:?}" + ); } // ---------------------------------------------------------------- auth and health checks @@ -434,21 +667,46 @@ fn rejects_duplicate_header_rules_case_insensitively() { #[test] fn forward_auth_requires_site_configuration() { let r = load( - &SourceFile { name: "ianitor.toml", contents: "" }, - &[SourceFile { name: "a.toml", contents: &format!("{MINIMAL}auth = \"forward-auth\"\n") }], + &SourceFile { + name: "ianitor.toml", + contents: "", + }, + &[SourceFile { + name: "a.toml", + contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"), + }], + ); + assert!( + r.unwrap_err() + .errors() + .iter() + .any(|e| matches!(e, ValidationError::ForwardAuthNotConfigured { .. })) ); - 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"] { + 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: "a.toml", contents: MINIMAL }], + &SourceFile { + name: "ianitor.toml", + contents: &format!("[forward_auth]\nurl = {bad:?}\n"), + }, + &[SourceFile { + name: "a.toml", + contents: MINIMAL, + }], ); assert!( - r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::BadForwardAuth { .. })), + r.unwrap_err() + .errors() + .iter() + .any(|e| matches!(e, ValidationError::BadForwardAuth { .. })), "{bad}" ); } @@ -464,7 +722,10 @@ fn rejects_bad_health_checks() { "path = \"/{x}\"\ninterval_secs = 5", ] { let e = single_error(&format!("{MINIMAL}[health_check]\n{body}\n")); - assert!(matches!(e, ValidationError::BadHealthCheck { .. }), "{body}: {e:?}"); + assert!( + matches!(e, ValidationError::BadHealthCheck { .. }), + "{body}: {e:?}" + ); } } @@ -475,9 +736,18 @@ fn collects_errors_from_every_file() { let r = load( &site(), &[ - SourceFile { name: "a.toml", contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n" }, - SourceFile { name: "b.toml", contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n" }, - SourceFile { name: "c.toml", contents: MINIMAL }, + SourceFile { + name: "a.toml", + contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n", + }, + SourceFile { + name: "b.toml", + contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + }, + SourceFile { + name: "c.toml", + contents: MINIMAL, + }, ], ); let errs = r.unwrap_err(); @@ -495,8 +765,14 @@ fn error_messages_name_the_file_in_plain_english() { #[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 = [[]]", + "\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", ]; -- 2.53.0 From a94a242c79d7c1da05ef3d0d822adf86b67c07be Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 14:48:05 +0100 Subject: [PATCH 06/27] [tests] Testkit: test CA, echo and websocket upstreams, mock Authelia, clients --- Cargo.lock | 2713 ++++++++++++++++++++++++++++++++- Cargo.toml | 17 +- tests/support/Cargo.toml | 26 + tests/support/src/authelia.rs | 157 ++ tests/support/src/client.rs | 193 +++ tests/support/src/lib.rs | 24 + tests/support/src/proc.rs | 106 ++ tests/support/src/tls.rs | 70 + tests/support/src/upstream.rs | 238 +++ 9 files changed, 3530 insertions(+), 14 deletions(-) create mode 100644 tests/support/Cargo.toml create mode 100644 tests/support/src/authelia.rs create mode 100644 tests/support/src/client.rs create mode 100644 tests/support/src/lib.rs create mode 100644 tests/support/src/proc.rs create mode 100644 tests/support/src/tls.rs create mode 100644 tests/support/src/upstream.rs diff --git a/Cargo.lock b/Cargo.lock index 7022890..f4d900d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,601 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "const-random", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "aliasable" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "arc-swap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "asn1-rs" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048" +dependencies = [ + "asn1-rs-derive 0.5.1", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror 1.0.69", + "time", +] + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive 0.6.0", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "brotli" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640d25bc63c50fb1f0b545ffd80207d2e10a4c965530809b40ba3386825c391" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e2e4afe60d7dd600fdd3de8d0f08c2b7ec039712e3b6137ff98b7004e82de4f" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "num-traits", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "daemonix" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0b747381562a10fd2104e9333ad72fe5158d79de81b64426fc9e229c6d3fb38" +dependencies = [ + "libc", +] + +[[package]] +name = "daggy" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70def8d72740e44d9f676d8dab2c933a236663d86dd24319b57a2bed4d694774" +dependencies = [ + "petgraph", +] + +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553" +dependencies = [ + "asn1-rs 0.6.2", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs 0.7.2", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -10,7 +605,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -19,6 +614,82 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "libz-ng-sys", +] + +[[package]] +name = "flurry" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf5efcf77a4da27927d3ab0509dec5b0954bb3bc59da5a1de9e52642ebd4cdf9" +dependencies = [ + "ahash", + "num_cpus", + "parking_lot", + "seize", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -28,11 +699,308 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.14.2", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-native-certs 0.8.5", + "rustls-platform-verifier", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "libc", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] [[package]] name = "ianitor-control" @@ -44,7 +1012,7 @@ version = "0.1.0" dependencies = [ "serde", "serde_json", - "thiserror", + "thiserror 2.0.21", "toml", "url", ] @@ -61,7 +1029,40 @@ dependencies = [ name = "ianitor-edge" version = "0.1.0" dependencies = [ + "arc-swap", + "async-trait", + "bytes", + "http", "ianitor-core", + "ianitor-testkit", + "instant-acme", + "log", + "pingora", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "tokio", + "x509-parser 0.18.1", +] + +[[package]] +name = "ianitor-testkit" +version = "0.1.0" +dependencies = [ + "bytes", + "futures-util", + "http", + "http-body-util", + "hyper", + "hyper-util", + "rcgen", + "rustls", + "rustls-pki-types", + "serde_json", + "tokio", + "tokio-rustls", + "tokio-tungstenite", ] [[package]] @@ -168,6 +1169,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -175,33 +1186,664 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.17.1", ] +[[package]] +name = "instant-acme" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f05ad37c421b962354c358d347d4a6130151df9407978372d3ad7f0c8f71a64" +dependencies = [ + "async-trait", + "base64 0.22.1", + "bytes", + "http", + "http-body", + "http-body-util", + "httpdate", + "hyper", + "hyper-rustls", + "hyper-util", + "rcgen", + "ring", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libz-ng-sys" +version = "1.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d6f7f90c9e84e2716ee493ef7493995eb52772deb5ce12f960c13f6a90350a3" +dependencies = [ + "cmake", + "libc", +] + [[package]] name = "litemap" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "no_debug" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f23a60c850e1144fc1dd9435152e0cfdc7dd18725350b4243584118013a52a4" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "oid-registry" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8d8034d9489cdaf79228eb9f6a3b8d7bb32ba00d6645ebd48eef4077ceb5bd9" +dependencies = [ + "asn1-rs 0.6.2", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs 0.7.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl-probe" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "ouroboros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59" +dependencies = [ + "aliasable", + "ouroboros_macro", + "static_assertions", +] + +[[package]] +name = "ouroboros_macro" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" +dependencies = [ + "fixedbitset", + "indexmap 2.14.2", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pingora" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f97ba6539118cd573350647f34c2cd1fc288bd7ac94cb4597b05b3d0272bb5db" +dependencies = [ + "pingora-cache", + "pingora-core", + "pingora-http", + "pingora-load-balancing", + "pingora-proxy", + "pingora-timeout", +] + +[[package]] +name = "pingora-cache" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d28a5c622b0a2fba57117f0b313c62eb1e0b8c73ea5ebe75d4cc0fc83c9c08" +dependencies = [ + "ahash", + "arrayvec", + "async-trait", + "blake2", + "bstr", + "bytes", + "hex", + "http", + "httparse", + "httpdate", + "indexmap 1.9.3", + "log", + "lru", + "once_cell", + "parking_lot", + "pingora-core", + "pingora-error", + "pingora-header-serde", + "pingora-http", + "pingora-lru", + "pingora-timeout", + "rand 0.8.8", + "regex", + "rmp", + "rmp-serde", + "serde", + "strum", + "tokio", +] + +[[package]] +name = "pingora-core" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a535f47f65fdcb003f9e1df04cd18e614c128dfe9388acce3f211ae38ac14d68" +dependencies = [ + "ahash", + "async-trait", + "brotli", + "bstr", + "bytes", + "chrono", + "clap", + "daemonix", + "daggy", + "derivative", + "flate2", + "flurry", + "futures", + "h2", + "http", + "httparse", + "httpdate", + "libc", + "log", + "nix", + "once_cell", + "openssl-probe 0.1.6", + "ouroboros", + "parking_lot", + "percent-encoding", + "pingora-error", + "pingora-http", + "pingora-pool", + "pingora-runtime", + "pingora-rustls", + "pingora-timeout", + "rand 0.8.8", + "regex", + "serde", + "serde_yaml", + "sfv", + "socket2", + "strum", + "strum_macros", + "tokio", + "tokio-stream", + "tokio-test", + "unicase", + "windows-sys 0.59.0", + "x509-parser 0.16.0", + "zstd", +] + +[[package]] +name = "pingora-error" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c40ff4c1717b5fa27d80daa1d0f1b0bf15994a4de25023f18c79a69d4fc1f4c1" + +[[package]] +name = "pingora-header-serde" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b537b4d0079548ae396905063e74712300572ec73efb83c7532335675ca9e7" +dependencies = [ + "bytes", + "http", + "httparse", + "pingora-error", + "pingora-http", + "thread_local", + "zstd", + "zstd-safe", +] + +[[package]] +name = "pingora-http" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f38e9e519d53fab09eb320f7be2cd27ef9e66f755eba3bd84cc68852108d841" +dependencies = [ + "bytes", + "http", + "pingora-error", +] + +[[package]] +name = "pingora-ketama" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b164b534ff4bed5cc19d676b2bb6287da79f0de07cb696b2b5b92ddfca67136d" +dependencies = [ + "crc32fast", +] + +[[package]] +name = "pingora-load-balancing" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbd4318f1349222fd355029ba59fc387cb955b3ed5c0411137e3c0ee0486b481" +dependencies = [ + "arc-swap", + "async-trait", + "derivative", + "fnv", + "futures", + "http", + "log", + "pingora-core", + "pingora-error", + "pingora-http", + "pingora-ketama", + "pingora-runtime", + "rand 0.8.8", + "tokio", +] + +[[package]] +name = "pingora-lru" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f20e42e8c8822a2518ccbd6e2dce90a27132d87a29815ca601ce9eafd9f7425" +dependencies = [ + "ahash", + "arrayvec", + "async-channel", + "flurry", + "hashbrown 0.17.1", + "log", + "parking_lot", + "rand 0.8.8", + "tokio", +] + +[[package]] +name = "pingora-pool" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecda093a10bad5e887d73286f052dd0fc78ad0d6c7654235e507ed0f85b64af1" +dependencies = [ + "crossbeam-queue", + "dashmap", + "futures", + "log", + "lru", + "parking_lot", + "pingora-timeout", + "tokio", +] + +[[package]] +name = "pingora-proxy" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e3d5670490740405ecc8c6f75c3fcbce4d24f7adaffb355ca44550e7918e358" +dependencies = [ + "async-trait", + "bytes", + "clap", + "futures", + "h2", + "http", + "log", + "once_cell", + "pingora-cache", + "pingora-core", + "pingora-error", + "pingora-http", + "rand 0.8.8", + "regex", + "tokio", +] + +[[package]] +name = "pingora-runtime" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d2c5be0a8fcffa36c23d21b3d6ec5bad113395086f5b4e1a0c50b300c674c0" +dependencies = [ + "log", + "once_cell", + "rand 0.8.8", + "serde", + "thread_local", + "tokio", +] + +[[package]] +name = "pingora-rustls" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9a1bd91fd1adb760a3d44338b4dadc4bb6e8e20357d02ebec0a69811413a2bc" +dependencies = [ + "log", + "no_debug", + "pingora-error", + "ring", + "rustls", + "rustls-native-certs 0.7.3", + "rustls-pemfile", + "rustls-pki-types", + "tokio-rustls", +] + +[[package]] +name = "pingora-timeout" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d58d029af71f7694815494c681f1bb93aa06d83b6fa6a6b42e7154ee0e8e43e4" +dependencies = [ + "once_cell", + "parking_lot", + "pin-project-lite", + "thread_local", + "tokio", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "potential_utf" version = "0.1.6" @@ -211,6 +1853,21 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -220,6 +1877,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", + "yansi", +] + [[package]] name = "quote" version = "1.0.47" @@ -229,6 +1899,370 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser 0.18.1", + "yasna", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "rust_decimal" +version = "1.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a" +dependencies = [ + "arrayvec", + "num-traits", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5" +dependencies = [ + "openssl-probe 0.1.6", + "rustls-pemfile", + "rustls-pki-types", + "schannel", + "security-framework 2.11.1", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe 0.2.2", + "rustls-pki-types", + "schannel", + "security-framework 3.7.0", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs 0.8.5", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework 3.7.0", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "seize" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "689224d06523904ebcc9b482c6a3f4f7fb396096645c4cd10c0d2ff7371a34d3" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -256,7 +2290,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -281,18 +2315,163 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.2", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + +[[package]] +name = "sfv" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fa1f336066b758b7c9df34ed049c0e693a426afe2b27ff7d5b14f410ab1a132" +dependencies = [ + "base64 0.22.1", + "indexmap 2.14.2", + "rust_decimal", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.9" @@ -304,6 +2483,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -312,7 +2502,16 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", ] [[package]] @@ -321,7 +2520,18 @@ version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -332,7 +2542,55 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", ] [[package]] @@ -345,13 +2603,99 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-test" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12bc5db7778a8e08ee255090861e0e7aac55e784300077e7ed293c7be36168b2" +dependencies = [ + "futures-core", + "tokio", + "tokio-stream", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + [[package]] name = "toml" version = "1.2.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" dependencies = [ - "indexmap", + "indexmap 2.14.2", "serde_core", "serde_spanned", "toml_datetime", @@ -384,12 +2728,83 @@ version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -411,24 +2826,242 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x509-parser" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcbc162f30700d6f3f82a24bf7cc62ffe7caea42c0b2cba8bf7f3ae50cf51f69" +dependencies = [ + "asn1-rs 0.6.2", + "data-encoding", + "der-parser 9.0.0", + "lazy_static", + "nom", + "oid-registry 0.7.1", + "rusticata-macros", + "thiserror 1.0.69", + "time", +] + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs 0.7.2", + "data-encoding", + "der-parser 10.0.0", + "lazy_static", + "nom", + "oid-registry 0.8.1", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + [[package]] name = "yoke" version = "0.8.4" @@ -448,8 +3081,28 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn", - "synstructure", + "syn 3.0.9", + "synstructure 0.14.0", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -469,10 +3122,16 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn", - "synstructure", + "syn 3.0.9", + "synstructure 0.14.0", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" @@ -503,7 +3162,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -511,3 +3170,31 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml index 9d8972e..b4cd1ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/core", "crates/edge", "crates/control", "tests/diff"] +members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"] [workspace.package] version = "0.1.0" @@ -12,11 +12,26 @@ 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 = "0.4.28" +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" diff --git a/tests/support/Cargo.toml b/tests/support/Cargo.toml new file mode 100644 index 0000000..b3a1f71 --- /dev/null +++ b/tests/support/Cargo.toml @@ -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" diff --git a/tests/support/src/authelia.rs b/tests/support/src/authelia.rs new file mode 100644 index 0000000..82da540 --- /dev/null +++ b/tests/support/src/authelia.rs @@ -0,0 +1,157 @@ +// 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 +//! - cookie `authelia_session=nameless` → 200 without identity headers +//! - cookie `authelia_session=forbidden` → 403 +//! - otherwise GET/HEAD → 302 to the portal with `rd`, other methods → 401 + +use std::convert::Infallible; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full}; +use hyper::body::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::upstream::Recorded; + +pub const PATH: &str = "/api/authz/forward-auth"; +pub const PORTAL: &str = "https://auth.test/"; + +#[derive(Clone)] +pub struct MockAuthelia { + pub addr: SocketAddr, + requests: Arc>>, +} + +impl MockAuthelia { + pub async fn start() -> MockAuthelia { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let m = MockAuthelia { addr: listener.local_addr().unwrap(), requests: Arc::default() }; + let mm = m.clone(); + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { continue }; + let mm = mm.clone(); + tokio::spawn(async move { + let svc = service_fn(move |req| { + let mm = mm.clone(); + async move { Ok::<_, Infallible>(mm.handle(req).await) } + }); + let _ = http1::Builder::new().serve_connection(TokioIo::new(stream), svc).await; + }); + } + }); + m + } + + /// The `[forward_auth] url` for the site file. + pub fn url(&self) -> String { + format!("http://{}{PATH}", self.addr) + } + + pub fn requests(&self) -> Vec { + self.requests.lock().unwrap().clone() + } + + async fn handle(&self, req: Request) -> Response> { + let (parts, body) = req.into_parts(); + let body = body.collect().await.map(|b| b.to_bytes()).unwrap_or_default(); + self.requests.lock().unwrap().push(Recorded { + method: parts.method.to_string(), + path: parts.uri.path().to_owned(), + headers: parts.headers.iter().map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())).collect(), + body: body.to_vec(), + }); + let h = |name: &str| parts.headers.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned); + let text = |status: u16, body: &str| { + Response::builder() + .status(status) + .header("content-type", "text/plain; charset=utf-8") + .body(Full::new(Bytes::from(body.to_owned()))) + .unwrap() + }; + + if parts.method != hyper::Method::GET || parts.uri.path() != PATH { + return text(404, "404 page not found"); + } + let (Some(method), Some(proto), Some(host), Some(uri)) = + (h("x-forwarded-method"), h("x-forwarded-proto"), h("x-forwarded-host"), h("x-forwarded-uri")) + else { + return text(400, "missing X-Forwarded headers"); + }; + + let allowed = |identity: bool| { + let mut b = Response::builder().status(200); + if identity { + b = b + .header("remote-user", "alice") + .header("remote-groups", "admins,dev") + .header("remote-email", "alice@example.org") + .header("remote-name", "Alice Example"); + } + b.body(Full::new(Bytes::new())).unwrap() + }; + + if let Some(auth) = h("authorization") { + return if auth == "Bearer good" { + allowed(true) + } else { + Response::builder() + .status(401) + .header("www-authenticate", "Basic realm=\"Authorization Required\"") + .body(Full::new(Bytes::from_static(b"401 Unauthorized"))) + .unwrap() + }; + } + let cookie = h("cookie").unwrap_or_default(); + let session = cookie + .split(';') + .filter_map(|c| c.trim().strip_prefix("authelia_session=")) + .next() + .unwrap_or(""); + match session { + "good" => allowed(true), + "nameless" => allowed(false), + "forbidden" => text(403, "403 Forbidden"), + _ if method == "GET" || method == "HEAD" => { + let rd = format!("{proto}://{host}{uri}"); + let location = format!("{PORTAL}?rd={}", percent(&rd)); + Response::builder() + .status(302) + .header("location", location.clone()) + .header("set-cookie", "authelia_flow=1; Path=/; HttpOnly") + .header("content-type", "text/html; charset=utf-8") + .body(Full::new(Bytes::from(format!("302 Found")))) + .unwrap() + } + _ => text(401, "401 Unauthorized"), + } + } +} + +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 +} diff --git a/tests/support/src/client.rs b/tests/support/src/client.rs new file mode 100644 index 0000000..a006bd0 --- /dev/null +++ b/tests/support/src/client.rs @@ -0,0 +1,193 @@ +// 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, +} + +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, +} + +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) -> 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, +) -> io::Result> { + 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(io: S, req: &Req) -> io::Result { + 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, req: &Req) -> io::Result { + 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 { + 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, 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, + host: &str, + path: &str, + extra: &[(&str, &str)], + message: &str, +) -> io::Result { + 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(); + 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, 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"))? +} diff --git a/tests/support/src/lib.rs b/tests/support/src/lib.rs new file mode 100644 index 0000000..48c86d8 --- /dev/null +++ b/tests/support/src/lib.rs @@ -0,0 +1,24 @@ +// 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 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}") +} diff --git a/tests/support/src/proc.rs b/tests/support/src/proc.rs new file mode 100644 index 0000000..dd04640 --- /dev/null +++ b/tests/support/src/proc.rs @@ -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/. + +//! 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__BIN`, then `$PATH`. +pub fn find_binary(name: &str) -> Option { + 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 { + 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 => panic!( + "`{name}` is needed for this test but was not found on PATH (or ${}). \ + In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead.", + format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_")) + ), + } +} + +/// 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(); + } +} diff --git a/tests/support/src/tls.rs b/tests/support/src/tls.rs new file mode 100644 index 0000000..5674595 --- /dev/null +++ b/tests/support/src/tls.rs @@ -0,0 +1,70 @@ +// 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::::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::>()).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 { + roots_from_pem(&self.cert_pem) + } +} + +pub fn roots_from_pem(pem: &str) -> Arc { + 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(); +} diff --git a/tests/support/src/upstream.rs b/tests/support/src/upstream.rs new file mode 100644 index 0000000..e9c0427 --- /dev/null +++ b/tests/support/src/upstream.rs @@ -0,0 +1,238 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! 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; 12] = [ + "host", + "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)>, + pub body: Vec, +} + +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>>, + /// Status answered on `/healthz`. + pub health: Arc, +} + +type Body = BoxBody; + +fn full(b: impl Into) -> 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 { + self.requests.lock().unwrap().clone() + } + + /// Requests other than health checks. + pub fn proxied(&self) -> Vec { + self.requests().into_iter().filter(|r| r.path != "/healthz").collect() + } + + pub fn clear(&self) { + self.requests.lock().unwrap().clear(); + } + + async fn handle(&self, req: Request) -> Response { + 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::().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, +} + +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() +} -- 2.53.0 From 4fe041082d83afdda6cc8a5ccf5899a94ca666bb Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 14:48:06 +0100 Subject: [PATCH 07/27] [edge] Tests first: secret never leaks, forward-auth denial never reaches upstream (red) --- crates/edge/Cargo.toml | 20 ++++ crates/edge/src/main.rs | 7 +- crates/edge/tests/common/mod.rs | 125 ++++++++++++++++++++++ crates/edge/tests/forward_auth.rs | 172 ++++++++++++++++++++++++++++++ crates/edge/tests/secrets.rs | 166 ++++++++++++++++++++++++++++ 5 files changed, 489 insertions(+), 1 deletion(-) create mode 100644 crates/edge/tests/common/mod.rs create mode 100644 crates/edge/tests/forward_auth.rs create mode 100644 crates/edge/tests/secrets.rs diff --git a/crates/edge/Cargo.toml b/crates/edge/Cargo.toml index aeb65f8..162a55d 100644 --- a/crates/edge/Cargo.toml +++ b/crates/edge/Cargo.toml @@ -7,8 +7,28 @@ 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" + +[dev-dependencies] +ianitor-testkit.workspace = true [lints] workspace = true diff --git a/crates/edge/src/main.rs b/crates/edge/src/main.rs index a30c179..f2ceb6d 100644 --- a/crates/edge/src/main.rs +++ b/crates/edge/src/main.rs @@ -2,4 +2,9 @@ // 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/. -fn main() {} +//! ianitor-edge binary (not implemented yet). + +fn main() -> std::process::ExitCode { + eprintln!("ianitor-edge: not implemented yet"); + std::process::ExitCode::from(2) +} diff --git a/crates/edge/tests/common/mod.rs b/crates/edge/tests/common/mod.rs new file mode 100644 index 0000000..b3cc2c1 --- /dev/null +++ b/crates/edge/tests/common/mod.rs @@ -0,0 +1,125 @@ +// 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::{load, SourceFile, TlsMode}; +use ianitor_testkit::proc::{free_port, local, wait_for_port, ChildGuard, TempDir}; +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 { + 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 { + self.child.0.try_wait().unwrap() + } +} + +pub struct EdgeSpec<'a> { + pub site: &'a str, + pub hosts: Vec<(String, String)>, + pub secrets: Vec<(String, Vec)>, + pub log_level: &'a str, + pub extra_args: Vec, +} + +impl Default for EdgeSpec<'_> { + fn default() -> Self { + EdgeSpec { site: "", hosts: Vec::new(), secrets: Vec::new(), log_level: "info", extra_args: Vec::new() } + } +} + +/// Compile, write certificates and credentials, start the binary. Does not wait for readiness. +pub fn spawn(spec: EdgeSpec<'_>) -> Edge { + let dir = TempDir::new("edge"); + for d in ["certs", "state", "creds", "logs"] { + std::fs::create_dir_all(dir.join(d)).unwrap(); + } + let sources: Vec = spec.hosts.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(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}")) +} diff --git a/crates/edge/tests/forward_auth.rs b/crates/edge/tests/forward_auth.rs new file mode 100644 index 0000000..0f80807 --- /dev/null +++ b/crates/edge/tests/forward_auth.rs @@ -0,0 +1,172 @@ +// 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. + +#![cfg(unix)] +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::{host_file, start, EdgeSpec}; +use ianitor_testkit::authelia::MockAuthelia; +use ianitor_testkit::client::{self, Req, WsOutcome}; +use ianitor_testkit::upstream::{closed_port, Echo, WsEcho}; + +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()); +} diff --git a/crates/edge/tests/secrets.rs b/crates/edge/tests/secrets.rs new file mode 100644 index 0000000..43f9593 --- /dev/null +++ b/crates/edge/tests/secrets.rs @@ -0,0 +1,166 @@ +// 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. + +#![cfg(unix)] +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::{host_file, start, spawn, EdgeSpec}; +use ianitor_testkit::client::{self, Req, Resp, WsOutcome}; +use ianitor_testkit::upstream::{closed_port, Echo, WsEcho}; + +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 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()); +} -- 2.53.0 From 17e1df8320319e7beae5ef89dc89981cc44d77cb Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 14:57:36 +0100 Subject: [PATCH 08/27] [edge] Proxy: Pingora data plane with SNI certs, forward-auth, header rules, health checks, ACME --- Cargo.lock | 1 + Cargo.toml | 2 +- crates/edge/Cargo.toml | 1 + crates/edge/src/acme.rs | 289 ++++++++++++++++++++++++++ crates/edge/src/error.rs | 37 ++++ crates/edge/src/fetch.rs | 63 ++++++ crates/edge/src/forward_auth.rs | 105 ++++++++++ crates/edge/src/health.rs | 76 +++++++ crates/edge/src/http_app.rs | 90 ++++++++ crates/edge/src/lib.rs | 126 +++++++++++- crates/edge/src/logging.rs | 171 +++++++++++++++ crates/edge/src/main.rs | 60 +++++- crates/edge/src/proxy.rs | 332 ++++++++++++++++++++++++++++++ crates/edge/src/runtime.rs | 251 ++++++++++++++++++++++ crates/edge/src/secrets.rs | 163 +++++++++++++++ crates/edge/src/tls.rs | 66 ++++++ crates/edge/tests/common/mod.rs | 63 +++++- crates/edge/tests/forward_auth.rs | 137 +++++++++--- crates/edge/tests/secrets.rs | 146 ++++++++++--- tests/support/src/authelia.rs | 46 ++++- tests/support/src/client.rs | 88 ++++++-- tests/support/src/proc.rs | 27 ++- tests/support/src/tls.rs | 20 +- tests/support/src/upstream.rs | 79 +++++-- 24 files changed, 2316 insertions(+), 123 deletions(-) create mode 100644 crates/edge/src/acme.rs create mode 100644 crates/edge/src/error.rs create mode 100644 crates/edge/src/fetch.rs create mode 100644 crates/edge/src/forward_auth.rs create mode 100644 crates/edge/src/health.rs create mode 100644 crates/edge/src/http_app.rs create mode 100644 crates/edge/src/logging.rs create mode 100644 crates/edge/src/proxy.rs create mode 100644 crates/edge/src/runtime.rs create mode 100644 crates/edge/src/secrets.rs create mode 100644 crates/edge/src/tls.rs diff --git a/Cargo.lock b/Cargo.lock index f4d900d..289dd35 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1042,6 +1042,7 @@ dependencies = [ "rustls-pki-types", "serde", "serde_json", + "thiserror 2.0.21", "tokio", "x509-parser 0.18.1", ] diff --git a/Cargo.toml b/Cargo.toml index b4cd1ea..2259be2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ url = "2.5.7" tokio = { version = "1.48", features = ["full"] } bytes = "1.10" http = "1.3" -log = "0.4.28" +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" diff --git a/crates/edge/Cargo.toml b/crates/edge/Cargo.toml index 162a55d..f83f1f9 100644 --- a/crates/edge/Cargo.toml +++ b/crates/edge/Cargo.toml @@ -26,6 +26,7 @@ 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 diff --git a/crates/edge/src/acme.rs b/crates/edge/src/acme.rs new file mode 100644 index 0000000..1febc10 --- /dev/null +++ b/crates/edge/src/acme.rs @@ -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 `/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>); + +impl Challenges { + pub fn get(&self, token: &str) -> Option { + 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, + pub certs: Arc, + pub challenges: Arc, + /// Extra trust root for the ACME directory (tests against Pebble only). + pub ca_root: Option, +} + +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 { + 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 { + 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 { + 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 { + 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) -> bool { + let Some(acme) = &self.rt.cfg.acme else { + return true; + }; + let due: Vec = 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, + } + } + } +} diff --git a/crates/edge/src/error.rs b/crates/edge/src/error.rs new file mode 100644 index 0000000..32d774c --- /dev/null +++ b/crates/edge/src/error.rs @@ -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), +} diff --git a/crates/edge/src/fetch.rs b/crates/edge/src/fetch.rs new file mode 100644 index 0000000..f0172eb --- /dev/null +++ b/crates/edge/src/fetch.rs @@ -0,0 +1,63 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Small HTTP client on Pingora's connector, for forward-auth subrequests and health checks. + +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); + +pub fn peer(u: &UpstreamRt) -> HttpPeer { + let mut p = HttpPeer::new(u.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. +pub async fn fetch( + connector: &Connector, + u: &UpstreamRt, + req: RequestHeader, + max_body: usize, + timeout: Duration, +) -> Result { + let mut p = peer(u); + p.options.read_timeout = Some(timeout); + p.options.write_timeout = Some(timeout); + p.options.total_connection_timeout = Some(timeout); + let (mut http, _reused) = connector.get_http_session(&p).await?; + http.write_request_header(Box::new(req)).await?; + http.finish_request_body().await?; + http.read_response_header().await?; + let header = http + .response_header() + .cloned() + .ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?; + 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(), + }) +} diff --git a/crates/edge/src/forward_auth.rs b/crates/edge/src/forward_auth.rs new file mode 100644 index 0000000..6f7b0a5 --- /dev/null +++ b/crates/edge/src/forward_auth.rs @@ -0,0 +1,105 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! 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, the request fails closed with 502. + +use std::time::Duration; + +use bytes::Bytes; +use http::header::{self, HeaderName, HeaderValue}; +use pingora::Result; +use pingora::connectors::http::Connector; +use pingora::http::{RequestHeader, ResponseHeader}; +use pingora::proxy::Session; + +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)>), + Deny(Box, 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, +) -> Result { + 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 (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)) +} diff --git a/crates/edge/src/health.rs b/crates/edge/src/health.rs new file mode 100644 index 0000000..648a53d --- /dev/null +++ b/crates/edge/src/health.rs @@ -0,0 +1,76 @@ +// 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 ` 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, +} + +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 tokio::time::timeout(TIMEOUT, fetch(connector, u, req, 64 * 1024, TIMEOUT)).await { + Ok(Ok(f)) => f.header.status.is_success(), + _ => false, + } +} + +async fn watch(host: Arc, path: String, every: Duration) { + let connector = Connector::new(None); + loop { + for u in &host.upstreams { + let ok = probe(&connector, u, &path).await; + 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); + } + } + } + tokio::time::sleep(every).await; + } +} + +#[async_trait] +impl BackgroundService for HealthChecks { + async fn start(&self, mut shutdown: ShutdownWatch) { + let mut tasks = Vec::new(); + for host in self.rt.hosts.values() { + if let Some(hc) = &host.cfg.health_check { + let every = Duration::from_secs(u64::from(hc.interval_secs.max(1))); + tasks.push(tokio::spawn(watch(host.clone(), hc.path.clone(), every))); + } + } + let _ = shutdown.changed().await; + for t in tasks { + t.abort(); + } + } +} diff --git a/crates/edge/src/http_app.rs b/crates/edge/src/http_app.rs new file mode 100644 index 0000000..bae8e31 --- /dev/null +++ b/crates/edge/src/http_app.rs @@ -0,0 +1,90 @@ +// 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::apps::http_app::ServeHttp; +use pingora::protocols::http::ServerSession; + +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, + pub challenges: Arc, +} + +fn empty(status: StatusCode) -> Response> { + 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 ServeHttp for HttpApp { + async fn response(&self, session: &mut ServerSession) -> Response> { + 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 + } +} diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 117b823..1b42089 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -2,4 +2,128 @@ // 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. +//! 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, +} + +/// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates. +pub fn prepare(opts: &Options) -> Result, EdgeError> { + let cfg = runtime::read_config(&opts.config)?; + let creds = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from); + runtime::build(cfg, creds.as_deref()).map(Arc::new) +} + +/// Assemble the Pingora server with all services. Listeners bind when it runs. +pub fn server(rt: Arc, opts: &Options) -> Result { + 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>>); + + #[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)))), + }); +} diff --git a/crates/edge/src/logging.rs b/crates/edge/src/logging.rs new file mode 100644 index 0000000..0b89808 --- /dev/null +++ b/crates/edge/src/logging.rs @@ -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, + 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, +} + +impl AccessLog { + pub fn open(path: &Path) -> Result { + 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"); + } +} diff --git a/crates/edge/src/main.rs b/crates/edge/src/main.rs index f2ceb6d..08210f3 100644 --- a/crates/edge/src/main.rs +++ b/crates/edge/src/main.rs @@ -2,9 +2,61 @@ // 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 binary (not implemented yet). +//! `ianitor-edge --config [--check] [--acme-root ]` +//! +//! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG` +//! (error, warn, info, debug, trace; libraries are capped at info). -fn main() -> std::process::ExitCode { - eprintln!("ianitor-edge: not implemented yet"); - std::process::ExitCode::from(2) +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 [--check] [--acme-root ]" + ); + std::process::exit(0); + } + _ => { + return Err(EdgeError::Usage(format!( + "unknown argument {}", + a.to_string_lossy() + ))); + } + } + } + opts.config = + config.ok_or_else(|| EdgeError::Usage("--config 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 + } + } } diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs new file mode 100644 index 0000000..9016b7f --- /dev/null +++ b/crates/edge/src/proxy.rs @@ -0,0 +1,332 @@ +// 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, + pub connector: Connector, +} + +pub struct Ctx { + host: Option>, + /// The Host header as the client sent it (with port, if any). + host_header: String, + start: Instant, +} + +/// Host header (HTTP/1) or :authority (HTTP/2). +pub fn host_header(req: &RequestHeader) -> String { + req.headers + .get(header::HOST) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + .or_else(|| req.uri.authority().map(|a| a.as_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 { + 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(()) +} + +fn is_websocket_upgrade(req: &RequestHeader) -> bool { + req.headers + .get(header::UPGRADE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.trim().eq_ignore_ascii_case("websocket")) +} + +#[async_trait] +impl ProxyHttp for EdgeProxy { + type CTX = Ctx; + + fn new_ctx(&self) -> Ctx { + Ctx { + host: None, + host_header: String::new(), + start: Instant::now(), + } + } + + async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result { + 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") + })?; + 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> { + let host = ctx + .host + .as_ref() + .ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?; + let n = host.upstreams.len(); + let first = host.next.fetch_add(1, Ordering::Relaxed); + let chosen = (0..n) + .map(|i| &host.upstreams[(first + i) % n]) + .find(|u| u.healthy.load(Ordering::Relaxed)) + .ok_or_else(|| Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream"))?; + log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, chosen.authority); + Ok(Box::new(fetch::peer(chosen))) + } + + fn fail_to_connect( + &self, + _s: &mut Session, + _p: &HttpPeer, + _c: &mut Ctx, + mut e: Box, + ) -> Box { + // Like Caddy's default (no lb_try_duration): one attempt, then 502. + e.set_retry(false); + e + } + + async fn upstream_request_filter( + &self, + session: &mut Session, + req: &mut RequestHeader, + ctx: &mut Ctx, + ) -> Result<()> { + // 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 = 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")); + } +} diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs new file mode 100644 index 0000000..5661836 --- /dev/null +++ b/crates/edge/src/runtime.rs @@ -0,0 +1,251 @@ +// 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, ToSocketAddrs}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize}; + +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 { + pub addr: SocketAddr, + /// `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, + pub next: AtomicUsize, + pub request_ops: Vec, + pub response_ops: Vec, + /// Values of the secrets this host injects; a response header containing one is dropped. + pub secret_values: Vec>, +} + +pub struct ForwardAuthRt { + pub upstream: UpstreamRt, + pub path_and_query: String, + pub copy_headers: Vec, +} + +pub struct Runtime { + pub cfg: EdgeConfig, + pub hosts: HashMap>, + pub forward_auth: Option, + pub access_log: Option, + pub certs: Arc, +} + +impl Runtime { + pub fn host(&self, name: &str) -> Option<&Arc> { + self.hosts.get(name) + } + + pub fn acme_hosts(&self) -> Vec { + 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 { + 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 { + let err = |reason: String| EdgeError::Upstream { + address: u.address.clone(), + reason, + }; + // Resolved once at startup; Pingora peers need a socket address. + let addr = u + .address + .to_socket_addrs() + .map_err(|e| err(format!("cannot resolve: {e}")))? + .next() + .ok_or_else(|| err("resolves to no address".into()))?; + Ok(UpstreamRt { + addr, + authority: u.address.clone(), + tls: u.tls, + sni: u.sni.clone(), + healthy: AtomicBool::new(true), + }) +} + +fn header_name(name: &str) -> Result { + 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>, +) -> Result, 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 { + let names: BTreeSet = 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::, _>>()?; + 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::>()?, + }), + None => None, + }; + if forward_auth.is_none() && cfg.hosts.iter().any(|h| h.forward_auth) { + return Err(EdgeError::Config { + path: PathBuf::from(""), + 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, + }) +} diff --git a/crates/edge/src/secrets.rs b/crates/edge/src/secrets.rs new file mode 100644 index 0000000..52421f1 --- /dev/null +++ b/crates/edge/src/secrets.rs @@ -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()") + } +} + +impl fmt::Display for Secret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } +} + +/// 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 { + 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); + +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, dir: Option<&Path>) -> Result { + 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")); + } +} diff --git a/crates/edge/src/tls.rs b/crates/edge/src/tls.rs new file mode 100644 index 0000000..35bd3d6 --- /dev/null +++ b/crates/edge/src/tls.rs @@ -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>>, +} + +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> { + // 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 { + let chain: Vec> = CertificateDer::pem_slice_iter(cert_pem) + .collect::>() + .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 { + 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()) +} diff --git a/crates/edge/tests/common/mod.rs b/crates/edge/tests/common/mod.rs index b3cc2c1..ff7ccc6 100644 --- a/crates/edge/tests/common/mod.rs +++ b/crates/edge/tests/common/mod.rs @@ -13,8 +13,8 @@ use std::sync::Arc; use std::time::Duration; use ianitor_core::compile::{self, CompileOptions}; -use ianitor_core::{load, SourceFile, TlsMode}; -use ianitor_testkit::proc::{free_port, local, wait_for_port, ChildGuard, TempDir}; +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; @@ -42,7 +42,12 @@ impl Edge { /// 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) + format!( + "{}\n{}\n{}", + self.stderr(), + self.access_log(), + self.config_text + ) } pub fn exited(&mut self) -> Option { @@ -60,7 +65,13 @@ pub struct EdgeSpec<'a> { impl Default for EdgeSpec<'_> { fn default() -> Self { - EdgeSpec { site: "", hosts: Vec::new(), secrets: Vec::new(), log_level: "info", extra_args: Vec::new() } + EdgeSpec { + site: "", + hosts: Vec::new(), + secrets: Vec::new(), + log_level: "info", + extra_args: Vec::new(), + } } } @@ -70,14 +81,32 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { for d in ["certs", "state", "creds", "logs"] { std::fs::create_dir_all(dir.join(d)).unwrap(); } - let sources: Vec = 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 sources: Vec = 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/{}.crt", h.hostname)), + leaf.cert_pem, + ) + .unwrap(); std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap(); } } @@ -105,15 +134,24 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { 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)); + 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 } + 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)); + 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()); } @@ -121,5 +159,8 @@ pub fn start(spec: EdgeSpec<'_>) -> Edge { } pub fn host_file(hostname: &str, body: &str) -> (String, String) { - (format!("hosts/{hostname}.toml"), format!("hostname = \"{hostname}\"\ntls = \"domi\"\n{body}")) + ( + format!("hosts/{hostname}.toml"), + format!("hostname = \"{hostname}\"\ntls = \"domi\"\n{body}"), + ) } diff --git a/crates/edge/tests/forward_auth.rs b/crates/edge/tests/forward_auth.rs index 0f80807..85a7b78 100644 --- a/crates/edge/tests/forward_auth.rs +++ b/crates/edge/tests/forward_auth.rs @@ -11,10 +11,10 @@ mod common; -use common::{host_file, start, EdgeSpec}; +use common::{EdgeSpec, host_file, start}; use ianitor_testkit::authelia::MockAuthelia; use ianitor_testkit::client::{self, Req, WsOutcome}; -use ianitor_testkit::upstream::{closed_port, Echo, WsEcho}; +use ianitor_testkit::upstream::{Echo, WsEcho, closed_port}; fn site(auth_url: &str) -> String { format!("[forward_auth]\nurl = \"{auth_url}\"\n") @@ -29,8 +29,17 @@ async fn denial_never_reaches_the_upstream() { 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())), + 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() }); @@ -48,7 +57,10 @@ async fn denial_never_reaches_the_upstream() { 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_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; @@ -60,7 +72,10 @@ async fn denial_never_reaches_the_upstream() { 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\"")); + 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); @@ -74,16 +89,38 @@ async fn denial_never_reaches_the_upstream() { .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-*"); + 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() { + 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"); + 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(); @@ -95,10 +132,22 @@ async fn denial_never_reaches_the_upstream() { 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"); + 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")] @@ -108,7 +157,13 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() { 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()))], + hosts: vec![host_file( + "auth.test", + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", + echo.url() + ), + )], ..Default::default() }); let roots = edge.roots(); @@ -131,10 +186,19 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() { 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-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); + 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(); @@ -142,31 +206,52 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() { edge.https, "auth.test", roots.clone(), - &Req::get("auth.test", "/").header("cookie", "authelia_session=nameless").header("remote-user", "mallory"), + &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(); + 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 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()))], + 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(); + 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()); } diff --git a/crates/edge/tests/secrets.rs b/crates/edge/tests/secrets.rs index 43f9593..addc881 100644 --- a/crates/edge/tests/secrets.rs +++ b/crates/edge/tests/secrets.rs @@ -10,12 +10,15 @@ mod common; -use common::{host_file, start, spawn, EdgeSpec}; +use common::{EdgeSpec, host_file, spawn, start}; use ianitor_testkit::client::{self, Req, Resp, WsOutcome}; -use ianitor_testkit::upstream::{closed_port, Echo, WsEcho}; +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(); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); format!("sekret-{}-{nanos:x}-tail", std::process::id()) } @@ -26,7 +29,11 @@ fn assert_clean(what: &str, haystack: &[u8], secret: &str) { 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 header {n}"), + v.as_bytes(), + secret, + ); } assert_clean(&format!("{what}: response body"), &r.body, secret); } @@ -36,13 +43,32 @@ 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 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())), + 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())], @@ -57,20 +83,45 @@ async fn injected_secret_never_appears_in_a_response_or_log() { }; 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(( + "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, + 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 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(( + "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 { @@ -78,10 +129,24 @@ async fn injected_secret_never_appears_in_a_response_or_log() { } 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!( + 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() { + 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"); @@ -93,18 +158,38 @@ async fn injected_secret_never_appears_in_a_response_or_log() { 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); + 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}"); + 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!( + 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); @@ -143,15 +228,24 @@ async fn malformed_secret_is_rejected_without_echoing_it() { 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()), + &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())], + 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!( + !status.success(), + "edge must refuse a secret that is not a valid header value" + ); assert_clean("stderr", edge.stderr().as_bytes(), &secret); } diff --git a/tests/support/src/authelia.rs b/tests/support/src/authelia.rs index 82da540..67fced0 100644 --- a/tests/support/src/authelia.rs +++ b/tests/support/src/authelia.rs @@ -41,18 +41,25 @@ pub struct MockAuthelia { impl MockAuthelia { pub async fn start() -> MockAuthelia { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let m = MockAuthelia { addr: listener.local_addr().unwrap(), requests: Arc::default() }; + let m = MockAuthelia { + addr: listener.local_addr().unwrap(), + requests: Arc::default(), + }; let mm = m.clone(); tokio::spawn(async move { loop { - let Ok((stream, _)) = listener.accept().await else { continue }; + let Ok((stream, _)) = listener.accept().await else { + continue; + }; let mm = mm.clone(); tokio::spawn(async move { let svc = service_fn(move |req| { let mm = mm.clone(); async move { Ok::<_, Infallible>(mm.handle(req).await) } }); - let _ = http1::Builder::new().serve_connection(TokioIo::new(stream), svc).await; + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(stream), svc) + .await; }); } }); @@ -70,14 +77,28 @@ impl MockAuthelia { async fn handle(&self, req: Request) -> Response> { let (parts, body) = req.into_parts(); - let body = body.collect().await.map(|b| b.to_bytes()).unwrap_or_default(); + let body = body + .collect() + .await + .map(|b| b.to_bytes()) + .unwrap_or_default(); self.requests.lock().unwrap().push(Recorded { method: parts.method.to_string(), path: parts.uri.path().to_owned(), - headers: parts.headers.iter().map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())).collect(), + headers: parts + .headers + .iter() + .map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())) + .collect(), body: body.to_vec(), }); - let h = |name: &str| parts.headers.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned); + let h = |name: &str| { + parts + .headers + .get(name) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + }; let text = |status: u16, body: &str| { Response::builder() .status(status) @@ -89,9 +110,12 @@ impl MockAuthelia { if parts.method != hyper::Method::GET || parts.uri.path() != PATH { return text(404, "404 page not found"); } - let (Some(method), Some(proto), Some(host), Some(uri)) = - (h("x-forwarded-method"), h("x-forwarded-proto"), h("x-forwarded-host"), h("x-forwarded-uri")) - else { + let (Some(method), Some(proto), Some(host), Some(uri)) = ( + h("x-forwarded-method"), + h("x-forwarded-proto"), + h("x-forwarded-host"), + h("x-forwarded-uri"), + ) else { return text(400, "missing X-Forwarded headers"); }; @@ -136,7 +160,9 @@ impl MockAuthelia { .header("location", location.clone()) .header("set-cookie", "authelia_flow=1; Path=/; HttpOnly") .header("content-type", "text/html; charset=utf-8") - .body(Full::new(Bytes::from(format!("302 Found")))) + .body(Full::new(Bytes::from(format!( + "302 Found" + )))) .unwrap() } _ => text(401, "401 Unauthorized"), diff --git a/tests/support/src/client.rs b/tests/support/src/client.rs index a006bd0..873d875 100644 --- a/tests/support/src/client.rs +++ b/tests/support/src/client.rs @@ -37,7 +37,12 @@ impl Req { } 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() } + 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 { @@ -61,11 +66,18 @@ pub struct Resp { 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()) + 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() + self.headers + .iter() + .filter(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + .collect() } pub fn text(&self) -> String { @@ -81,7 +93,9 @@ fn other(e: impl std::fmt::Display) -> io::Error { pub fn tls_connector(roots: Arc) -> TlsConnector { crate::tls::install_crypto(); - let mut cfg = rustls::ClientConfig::builder().with_root_certificates(roots).with_no_client_auth(); + 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)) } @@ -96,29 +110,58 @@ async fn tls_stream( tls_connector(roots).connect(name, tcp).await } -async fn send(io: S, req: &Req) -> io::Result { - let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io)).await.map_err(other)?; +async fn send( + io: S, + req: &Req, +) -> io::Result { + 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()); + 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 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())) + .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 }) + 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, req: &Req) -> io::Result { +pub async fn https( + addr: SocketAddr, + sni: &str, + roots: Arc, + req: &Req, +) -> io::Result { tokio::time::timeout(TIMEOUT, async { let s = tls_stream(addr, sni, roots).await?; send(s, req).await @@ -157,7 +200,9 @@ pub async fn websocket( ) -> io::Result { 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)?; + 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)?, @@ -167,7 +212,9 @@ pub async fn websocket( match tokio_tungstenite::client_async(request, s).await { Ok((mut ws, resp)) => { let status = resp.status().as_u16(); - ws.send(tungstenite::Message::text(message)).await.map_err(other)?; + 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:?}"))), @@ -180,10 +227,19 @@ pub async fn websocket( let headers = resp .headers() .iter() - .map(|(n, v)| (n.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned())) + .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 })) + Ok(WsOutcome::Refused(Resp { + status, + headers, + body, + })) } Err(e) => Err(other(e)), } diff --git a/tests/support/src/proc.rs b/tests/support/src/proc.rs index dd04640..8e8eb6a 100644 --- a/tests/support/src/proc.rs +++ b/tests/support/src/proc.rs @@ -12,7 +12,11 @@ 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() + std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port() } pub fn local(port: u16) -> SocketAddr { @@ -70,12 +74,17 @@ impl Drop for TempDir { /// Locate an external tool: `$IANITOR__BIN`, then `$PATH`. pub fn find_binary(name: &str) -> Option { - let var = format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_")); + 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()) + 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`, @@ -87,11 +96,13 @@ pub fn require_binary(name: &str) -> Option { eprintln!("SKIPPED: `{name}` not found (IANITOR_ALLOW_SKIP=1)"); None } - None => panic!( - "`{name}` is needed for this test but was not found on PATH (or ${}). \ - In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead.", - format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_")) - ), + 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." + ) + } } } diff --git a/tests/support/src/tls.rs b/tests/support/src/tls.rs index 5674595..f82b196 100644 --- a/tests/support/src/tls.rs +++ b/tests/support/src/tls.rs @@ -32,15 +32,24 @@ impl TestCa { 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]; + 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) } + 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::>()).unwrap(); + let mut params = + CertificateParams::new(names.iter().map(|s| (*s).to_owned()).collect::>()) + .unwrap(); let mut dn = DistinguishedName::new(); dn.push(DnType::CommonName, names.first().copied().unwrap_or("test")); params.distinguished_name = dn; @@ -48,7 +57,10 @@ impl TestCa { 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() } + Leaf { + cert_pem: cert.pem(), + key_pem: key.serialize_pem(), + } } pub fn roots(&self) -> Arc { diff --git a/tests/support/src/upstream.rs b/tests/support/src/upstream.rs index e9c0427..75b4897 100644 --- a/tests/support/src/upstream.rs +++ b/tests/support/src/upstream.rs @@ -49,7 +49,10 @@ pub struct Recorded { 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()) + self.headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_slice()) } } @@ -80,14 +83,18 @@ impl Echo { let e = echo.clone(); tokio::spawn(async move { loop { - let Ok((stream, _)) = listener.accept().await else { continue }; + 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; + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(stream), svc) + .await; }); } }); @@ -104,7 +111,10 @@ impl Echo { /// Requests other than health checks. pub fn proxied(&self) -> Vec { - self.requests().into_iter().filter(|r| r.path != "/healthz").collect() + self.requests() + .into_iter() + .filter(|r| r.path != "/healthz") + .collect() } pub fn clear(&self) { @@ -113,13 +123,21 @@ impl Echo { async fn handle(&self, req: Request) -> Response { let (parts, body) = req.into_parts(); - let body = body.collect().await.map(|b| b.to_bytes()).unwrap_or_default(); + 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(), + 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| { @@ -133,19 +151,35 @@ impl Echo { 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::().ok()) { - return base(code).header("content-type", "text/plain").body(full(format!("status {code}"))).unwrap(); + if let Some(code) = path + .strip_prefix("/status/") + .and_then(|c| c.parse::().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(); + 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(); + return base(200) + .header("content-type", "text/plain") + .body(BodyExt::boxed(StreamBody::new(stream))) + .unwrap(); } if path == "/set-cookie" { return base(200) @@ -167,7 +201,10 @@ impl Echo { 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()); + headers.insert( + h.to_owned(), + String::from_utf8_lossy(v.as_bytes()).into_owned().into(), + ); } } for h in HASHED_HEADERS { @@ -184,7 +221,10 @@ impl Echo { "body_fnv": fnv64(&body), "headers": headers, }); - base(200).header("content-type", "application/json").body(full(json.to_string())).unwrap() + base(200) + .header("content-type", "application/json") + .body(full(json.to_string())) + .unwrap() } } @@ -198,14 +238,21 @@ pub struct WsEcho { 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 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 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 }; + 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() { -- 2.53.0 From c14fb2dea6240291ebced57d5a3d62ab680f4e39 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:02:09 +0100 Subject: [PATCH 09/27] [diff] Harness: 43-request corpus against Ianitor and Caddy, broken-compiler check --- Cargo.lock | 4 + tests/diff/Cargo.toml | 8 +- tests/diff/src/lib.rs | 720 ++++++++++++++++++++++++++++++++++++++- tests/diff/tests/diff.rs | 89 +++++ 4 files changed, 818 insertions(+), 3 deletions(-) create mode 100644 tests/diff/tests/diff.rs diff --git a/Cargo.lock b/Cargo.lock index 289dd35..be5f6ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1023,6 +1023,10 @@ version = "0.1.0" dependencies = [ "ianitor-core", "ianitor-edge", + "ianitor-testkit", + "rustls", + "serde_json", + "tokio", ] [[package]] diff --git a/tests/diff/Cargo.toml b/tests/diff/Cargo.toml index c2e986a..0689194 100644 --- a/tests/diff/Cargo.toml +++ b/tests/diff/Cargo.toml @@ -10,6 +10,10 @@ 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] -workspace = true +[lints.rust] +unsafe_code = "forbid" diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index d664c63..92d81aa 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -2,4 +2,722 @@ // 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: Ianitor edge versus Caddy on one request corpus. +//! 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 = \"{}\"\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 = 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 { + 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>), + Caddy(#[allow(dead_code)] ChildGuard), +} + +impl Drop for Target { + fn drop(&mut self) { + if let Guard::Edge(stop) = &mut self._guard { + if 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)>, + }, +} + +pub struct Case { + pub name: &'static str, + 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 { + Case { + name, + action: Action::Https { sni, req }, + headers: STD, + } +} + +/// The seed corpus: plain requests, header rules, websocket upgrades, upstream down, +/// auth denied and allowed, health checks. +pub fn corpus() -> Vec { + let p = "plain.test"; + let a = "auth.test"; + let good = ("cookie", "authelia_session=good"); + 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( + "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", "/"), + ), + Case { + name: "HTTP redirects to HTTPS", + action: Action::Http { + req: Req::get(p, "/a/b?c=d"), + }, + headers: STD, + }, + Case { + name: "HTTP unknown host", + action: Action::Http { + req: Req::get("unknown.test", "/"), + }, + headers: STD, + }, + Case { + name: "HTTP unknown ACME token", + action: Action::Http { + req: Req::get(p, "/.well-known/acme-challenge/nope"), + }, + headers: STD, + }, + Case { + name: "websocket upgrade", + action: Action::Websocket { + sni: "ws.test", + host: "ws.test", + headers: vec![], + }, + headers: &["upgrade"], + }, + Case { + name: "websocket refused when disabled", + action: Action::Websocket { + sni: "nows.test", + host: "nows.test", + headers: vec![], + }, + headers: STD, + }, + https( + "plain GET where websockets are disabled", + "nows.test", + Req::get("nows.test", "/"), + ), + 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", "authelia_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 allowed without identity strips spoofed", + a, + Req::get(a, "/me") + .header("cookie", "authelia_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), + ), + Case { + name: "websocket denied by auth", + action: Action::Websocket { + sni: "wsauth.test", + host: "wsauth.test", + headers: vec![], + }, + headers: STD, + }, + Case { + name: "websocket allowed by auth", + action: Action::Websocket { + sni: "wsauth.test", + host: "wsauth.test", + headers: vec![good], + }, + headers: &["upgrade"], + }, + 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", "/")), + ] +} + +/// What one engine answered, normalised for comparison. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Observation { + pub status: u16, + pub headers: BTreeMap, + pub body: String, +} + +fn observe(resp: &Resp, case: &Case, t: &Target) -> Observation { + let mut headers = BTreeMap::new(); + for h in case.headers { + let all = resp.header_all(h); + if !all.is_empty() { + // The two engines listen on different ports; Location carries the HTTPS port. + let v = all + .join("\n") + .replace(&format!(":{}", t.https.port()), ":"); + headers.insert((*h).to_owned(), v); + } + } + Observation { + status: resp.status, + headers, + body: String::from_utf8_lossy(&resp.body).into_owned(), + } +} + +pub async fn run_case(case: &Case, t: &Target, roots: Arc) -> Observation { + match &case.action { + Action::Https { sni, req } => match client::https(t.https, sni, roots, req).await { + Ok(r) => observe(&r, case, t), + Err(e) => Observation { + status: 0, + headers: BTreeMap::new(), + body: format!("client error: {e}"), + }, + }, + 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 } => { + match client::websocket(t.https, sni, roots, host, "/socket", headers, "ping").await { + Ok(WsOutcome::Upgraded { status, echo }) => Observation { + status, + headers: BTreeMap::new(), + body: format!("echo: {echo}"), + }, + Ok(WsOutcome::Refused(r)) => observe(&r, case, t), + Err(e) => Observation { + status: 0, + headers: BTreeMap::new(), + body: format!("client error: {e}"), + }, + } + } + } +} + +pub struct Outcome { + pub name: &'static str, + pub ianitor: Observation, + pub caddy: Observation, +} + +/// Documented, accepted differences between the engines, each with its reason. Anything +/// else is a mismatch. +pub const KNOWN_DIVERGENCES: &[(&str, &str)] = &[( + "KD-1", + "Caddy (Go net/http) adds a sniffed Content-Type when the upstream sends none; \ + Ianitor passes the upstream response unchanged (no MIME sniffing).", +)]; + +/// Content types Go's `http.DetectContentType` produces for small text and binary bodies. +const SNIFFED: [&str; 3] = [ + "text/plain; charset=utf-8", + "text/html; charset=utf-8", + "application/octet-stream", +]; + +impl Outcome { + pub fn same(&self) -> bool { + self.ianitor == self.caddy + } + + /// `Some(id)` when the only difference is a documented divergence. + pub fn known_divergence(&self) -> Option<&'static str> { + if self.same() { + return None; + } + let sniffed = self + .caddy + .headers + .get("content-type") + .is_some_and(|v| SNIFFED.contains(&v.as_str())); + if sniffed && !self.ianitor.headers.contains_key("content-type") { + let mut c = self.caddy.clone(); + c.headers.remove("content-type"); + if c == self.ianitor { + return Some("KD-1"); + } + } + None + } + + pub fn mismatch(&self) -> bool { + !self.same() && self.known_divergence().is_none() + } +} + +pub struct Report { + pub outcomes: Vec, +} + +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 mut s = format!( + "== {title}: {} cases, {} identical, {} known divergence, {} differ\n", + self.outcomes.len(), + self.outcomes.iter().filter(|o| o.same()).count(), + self.known().len(), + 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:<4} {:3} {}", o.ianitor.status, o.name); + } else { + let _ = writeln!(s, " DIFF {}", o.name); + let _ = writeln!(s, " ianitor: {:?}", short(&o.ianitor)); + let _ = writeln!(s, " caddy: {:?}", short(&o.caddy)); + } + } + for (id, why) in KNOWN_DIVERGENCES { + let _ = writeln!(s, " {id}: {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::(), + 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) -> 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") { + if 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; +} diff --git a/tests/diff/tests/diff.rs b/tests/diff/tests/diff.rs new file mode 100644 index 0000000..fcb3320 --- /dev/null +++ b/tests/diff/tests/diff.rs @@ -0,0 +1,89 @@ +// 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`. + +#![cfg(unix)] +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +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 = 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:?}" + ); +} -- 2.53.0 From e7fa5f57ec97bb908be4913c77bfe1ae9a34d03a Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:03:08 +0100 Subject: [PATCH 10/27] [tests] Lint: collapse nested ifs, format panic message --- tests/diff/src/lib.rs | 16 ++++++++-------- tests/support/src/proc.rs | 5 ++++- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index 92d81aa..137e119 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -182,10 +182,10 @@ enum Guard { impl Drop for Target { fn drop(&mut self) { - if let Guard::Edge(stop) = &mut self._guard { - if let Some(s) = stop.take() { - let _ = s.send(()); - } + if let Guard::Edge(stop) = &mut self._guard + && let Some(s) = stop.take() + { + let _ = s.send(()); } } } @@ -693,10 +693,10 @@ pub fn break_caddy(json: &str) -> String { 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") { - if let Some(h) = m.get_mut("headers").and_then(|h| h.as_object_mut()) { - h.remove("response"); - } + 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); } diff --git a/tests/support/src/proc.rs b/tests/support/src/proc.rs index 8e8eb6a..59e177b 100644 --- a/tests/support/src/proc.rs +++ b/tests/support/src/proc.rs @@ -97,7 +97,10 @@ pub fn require_binary(name: &str) -> Option { None } None => { - let var = format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_")); + 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." -- 2.53.0 From 6a7aafc859d153ea7400dcfdeec21624a175e115 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:06:40 +0100 Subject: [PATCH 11/27] [edge] ACME: end-to-end test against Pebble next to a Domi-cert host --- crates/edge/tests/acme_pebble.rs | 218 +++++++++++++++++++++++++++++++ crates/edge/tests/common/mod.rs | 5 +- 2 files changed, 222 insertions(+), 1 deletion(-) create mode 100644 crates/edge/tests/acme_pebble.rs diff --git a/crates/edge/tests/acme_pebble.rs b/crates/edge/tests/acme_pebble.rs new file mode 100644 index 0000000..dc27f3c --- /dev/null +++ b/crates/edge/tests/acme_pebble.rs @@ -0,0 +1,218 @@ +// 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. + +#![cfg(unix)] +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use std::os::unix::fs::PermissionsExt; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use 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" + ); +} diff --git a/crates/edge/tests/common/mod.rs b/crates/edge/tests/common/mod.rs index ff7ccc6..952dba0 100644 --- a/crates/edge/tests/common/mod.rs +++ b/crates/edge/tests/common/mod.rs @@ -61,6 +61,8 @@ pub struct EdgeSpec<'a> { pub secrets: Vec<(String, Vec)>, pub log_level: &'a str, pub extra_args: Vec, + /// Fixed HTTP port (e.g. one Pebble was told to validate against). + pub http_port: Option, } impl Default for EdgeSpec<'_> { @@ -71,6 +73,7 @@ impl Default for EdgeSpec<'_> { secrets: Vec::new(), log_level: "info", extra_args: Vec::new(), + http_port: None, } } } @@ -114,7 +117,7 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { std::fs::write(dir.join(&format!("creds/{name}")), value).unwrap(); } - let http = local(free_port()); + let http = local(spec.http_port.unwrap_or_else(free_port)); let https = local(free_port()); let opts = CompileOptions { http_listen: http, -- 2.53.0 From c50fcd5a5ab81d78fbbd0a2ffbf96b16bd33161a Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:09:41 +0100 Subject: [PATCH 12/27] [core] Compilers: TLS server name for IP upstreams is the IP literal --- crates/core/src/compile/edge.rs | 12 ++++-------- crates/core/src/edge_config.rs | 2 +- crates/core/tests/golden/edge.json | 8 ++++---- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/crates/core/src/compile/edge.rs b/crates/core/src/compile/edge.rs index 4afdc2a..30f643c 100644 --- a/crates/core/src/compile/edge.rs +++ b/crates/core/src/compile/edge.rs @@ -9,9 +9,7 @@ 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, UpstreamHost, -}; +use crate::{AccessLog, AuthMode, HeaderRule, HeaderValue, Model, Scheme, TlsMode, Upstream}; pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig { let site = model.site(); @@ -64,11 +62,9 @@ fn upstream(u: &Upstream) -> EdgeUpstream { EdgeUpstream { address: u.authority(), tls: u.scheme == Scheme::Https, - // Like Go's TLS client in Caddy: SNI is the host name; IP literals send none. - sni: match &u.host { - UpstreamHost::Name(n) => n.clone(), - UpstreamHost::Ip(_) => String::new(), - }, + // 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(), } } diff --git a/crates/core/src/edge_config.rs b/crates/core/src/edge_config.rs index 9dcb8ec..45a0282 100644 --- a/crates/core/src/edge_config.rs +++ b/crates/core/src/edge_config.rs @@ -54,7 +54,7 @@ pub struct EdgeUpstream { /// `host:port`, IPv6 in brackets. pub address: String, pub tls: bool, - /// SNI and certificate name when `tls` is set. + /// Server name for TLS (SNI and certificate check): the host name or IP literal. pub sni: String, } diff --git a/crates/core/tests/golden/edge.json b/crates/core/tests/golden/edge.json index a6b4249..16936cb 100644 --- a/crates/core/tests/golden/edge.json +++ b/crates/core/tests/golden/edge.json @@ -14,7 +14,7 @@ "upstream": { "address": "127.0.0.1:9091", "tls": false, - "sni": "" + "sni": "127.0.0.1" }, "path_and_query": "/api/authz/forward-auth", "copy_headers": [ @@ -34,12 +34,12 @@ { "address": "127.0.0.1:2342", "tls": false, - "sni": "" + "sni": "127.0.0.1" }, { "address": "127.0.0.1:2343", "tls": false, - "sni": "" + "sni": "127.0.0.1" } ], "forward_auth": false, @@ -87,7 +87,7 @@ { "address": "[::1]:3001", "tls": false, - "sni": "" + "sni": "::1" } ], "forward_auth": false, -- 2.53.0 From fd4b4a777551e79cdf1e6ae6df92becac9f95eea Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:09:41 +0100 Subject: [PATCH 13/27] [docs] Roadmap: answer open points 1, 2, 3 and 5; WSL note in CLAUDE.md --- CLAUDE.md | 5 +++++ docs/ROADMAP.md | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index fb73fa9..c34972f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,6 +20,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: sh .githooks/test-pre-commit.sh) + ## Rules - Commits: `[] : `. 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. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 81ca897..a0fb77f 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -107,10 +107,14 @@ 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 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] 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) -- 2.53.0 From d42c178a139612d27a074f8e194798a31a8175c9 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:36:00 +0100 Subject: [PATCH 14/27] [edge] Tests first: QC repros for 1xx, auth timeout, name resolution, Upgrade tokens, Remote-* stripping (red) --- crates/edge/tests/forward_auth.rs | 93 ++++++++++++ crates/edge/tests/upstreams.rs | 103 +++++++++++++ tests/support/src/authelia.rs | 237 +++++++++++++----------------- tests/support/src/lib.rs | 1 + tests/support/src/raw.rs | 101 +++++++++++++ tests/support/src/upstream.rs | 13 ++ 6 files changed, 414 insertions(+), 134 deletions(-) create mode 100644 crates/edge/tests/upstreams.rs create mode 100644 tests/support/src/raw.rs diff --git a/crates/edge/tests/forward_auth.rs b/crates/edge/tests/forward_auth.rs index 85a7b78..f6bfa77 100644 --- a/crates/edge/tests/forward_auth.rs +++ b/crates/edge/tests/forward_auth.rs @@ -255,3 +255,96 @@ async fn unreachable_auth_server_fails_closed() { 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}"); + } + } +} diff --git a/crates/edge/tests/upstreams.rs b/crates/edge/tests/upstreams.rs new file mode 100644 index 0000000..30afee2 --- /dev/null +++ b/crates/edge/tests/upstreams.rs @@ -0,0 +1,103 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Upstream handling: name resolution at connect time, health checks that survive odd +//! answers, websocket refusal on every Upgrade token, absolute-form requests. + +#![cfg(unix)] +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use std::time::{Duration, Instant}; + +use 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 and routed by the URI's host +/// (RFC 9112 §3.2.2), as Go/Caddy do. +#[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 = [\"{}\"]\n", echo.url()))], + ..Default::default() + }); + let r = client::http(edge.http, &Req::get("plain.test", "http://evil.test/x")).await.unwrap(); + assert_eq!(r.status, 404, "plain HTTP"); + let r = client::https(edge.https, "plain.test", edge.roots(), &Req::get("plain.test", "https://evil.test/x")) + .await + .unwrap(); + assert_eq!(r.status, 404, "HTTPS"); + let r = client::http(edge.http, &Req::get("evil.test", "http://plain.test/x?y")).await.unwrap(); + assert_eq!(r.status, 308); + assert!(echo.proxied().is_empty()); +} diff --git a/tests/support/src/authelia.rs b/tests/support/src/authelia.rs index 67fced0..e453d78 100644 --- a/tests/support/src/authelia.rs +++ b/tests/support/src/authelia.rs @@ -9,61 +9,124 @@ //! //! 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 -//! - cookie `authelia_session=nameless` → 200 without identity headers -//! - cookie `authelia_session=forbidden` → 403 +//! - cookie `authelia_session=good` → 200 with identity; `nameless` → 200 without identity; +//! `forbidden` → 403 +//! - misbehaving answers, by cookie: `continue-ok` (100 Continue, 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::convert::Infallible; use std::net::SocketAddr; -use std::sync::{Arc, Mutex}; - -use bytes::Bytes; -use http_body_util::{BodyExt, Full}; -use hyper::body::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::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, - requests: Arc>>, + server: RawServer, +} + +fn h(req: &Recorded, name: &str) -> Option { + req.header(name).map(|v| String::from_utf8_lossy(v).into_owned()) +} + +fn text(status: u16, reason: &str, body: &str) -> Vec { + 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 { + 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 + } + "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!("302 Found"); + 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 listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let m = MockAuthelia { - addr: listener.local_addr().unwrap(), - requests: Arc::default(), - }; - let mm = m.clone(); - tokio::spawn(async move { - loop { - let Ok((stream, _)) = listener.accept().await else { - continue; - }; - let mm = mm.clone(); - tokio::spawn(async move { - let svc = service_fn(move |req| { - let mm = mm.clone(); - async move { Ok::<_, Infallible>(mm.handle(req).await) } - }); - let _ = http1::Builder::new() - .serve_connection(TokioIo::new(stream), svc) - .await; - }); - } - }); - m + let server = RawServer::start(decide).await; + MockAuthelia { addr: server.addr, server } } /// The `[forward_auth] url` for the site file. @@ -72,101 +135,7 @@ impl MockAuthelia { } pub fn requests(&self) -> Vec { - self.requests.lock().unwrap().clone() - } - - async fn handle(&self, req: Request) -> Response> { - let (parts, body) = req.into_parts(); - let body = body - .collect() - .await - .map(|b| b.to_bytes()) - .unwrap_or_default(); - self.requests.lock().unwrap().push(Recorded { - method: parts.method.to_string(), - path: parts.uri.path().to_owned(), - headers: parts - .headers - .iter() - .map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())) - .collect(), - body: body.to_vec(), - }); - let h = |name: &str| { - parts - .headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - }; - let text = |status: u16, body: &str| { - Response::builder() - .status(status) - .header("content-type", "text/plain; charset=utf-8") - .body(Full::new(Bytes::from(body.to_owned()))) - .unwrap() - }; - - if parts.method != hyper::Method::GET || parts.uri.path() != PATH { - return text(404, "404 page not found"); - } - let (Some(method), Some(proto), Some(host), Some(uri)) = ( - h("x-forwarded-method"), - h("x-forwarded-proto"), - h("x-forwarded-host"), - h("x-forwarded-uri"), - ) else { - return text(400, "missing X-Forwarded headers"); - }; - - let allowed = |identity: bool| { - let mut b = Response::builder().status(200); - if identity { - b = b - .header("remote-user", "alice") - .header("remote-groups", "admins,dev") - .header("remote-email", "alice@example.org") - .header("remote-name", "Alice Example"); - } - b.body(Full::new(Bytes::new())).unwrap() - }; - - if let Some(auth) = h("authorization") { - return if auth == "Bearer good" { - allowed(true) - } else { - Response::builder() - .status(401) - .header("www-authenticate", "Basic realm=\"Authorization Required\"") - .body(Full::new(Bytes::from_static(b"401 Unauthorized"))) - .unwrap() - }; - } - let cookie = h("cookie").unwrap_or_default(); - let session = cookie - .split(';') - .filter_map(|c| c.trim().strip_prefix("authelia_session=")) - .next() - .unwrap_or(""); - match session { - "good" => allowed(true), - "nameless" => allowed(false), - "forbidden" => text(403, "403 Forbidden"), - _ if method == "GET" || method == "HEAD" => { - let rd = format!("{proto}://{host}{uri}"); - let location = format!("{PORTAL}?rd={}", percent(&rd)); - Response::builder() - .status(302) - .header("location", location.clone()) - .header("set-cookie", "authelia_flow=1; Path=/; HttpOnly") - .header("content-type", "text/html; charset=utf-8") - .body(Full::new(Bytes::from(format!( - "302 Found" - )))) - .unwrap() - } - _ => text(401, "401 Unauthorized"), - } + self.server.requests() } } diff --git a/tests/support/src/lib.rs b/tests/support/src/lib.rs index 48c86d8..6035ef3 100644 --- a/tests/support/src/lib.rs +++ b/tests/support/src/lib.rs @@ -10,6 +10,7 @@ pub mod authelia; pub mod client; pub mod proc; +pub mod raw; pub mod tls; pub mod upstream; diff --git a/tests/support/src/raw.rs b/tests/support/src/raw.rs new file mode 100644 index 0000000..89fdb36 --- /dev/null +++ b/tests/support/src/raw.rs @@ -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/. + +//! 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. + +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), + /// 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 { + 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>>, +} + +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 = 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(req) = parse(&buf) else { 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 { + self.requests.lock().unwrap().clone() + } + + pub fn url(&self) -> String { + format!("http://{}", self.addr) + } +} + +fn parse(buf: &[u8]) -> Option { + 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() }) +} diff --git a/tests/support/src/upstream.rs b/tests/support/src/upstream.rs index 75b4897..db1e741 100644 --- a/tests/support/src/upstream.rs +++ b/tests/support/src/upstream.rs @@ -121,7 +121,20 @@ impl Echo { 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) -> Response { + 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) -> Response { let (parts, body) = req.into_parts(); let body = body .collect() -- 2.53.0 From 58d03978752c504014aa62eb77e56e66b1e3bab1 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:42:25 +0100 Subject: [PATCH 15/27] [core] Tests first: wildcard headers, file name, size and upstream caps, identity stripping (red) --- crates/core/tests/compile.rs | 29 ++++++++ crates/core/tests/schema.rs | 136 +++++++++++++++++++++++++++++------ 2 files changed, 142 insertions(+), 23 deletions(-) diff --git a/crates/core/tests/compile.rs b/crates/core/tests/compile.rs index 742ba98..d67500c 100644 --- a/crates/core/tests/compile.rs +++ b/crates/core/tests/compile.rs @@ -217,3 +217,32 @@ fn caddy_output_matches_golden_file() { &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"); +} diff --git a/crates/core/tests/schema.rs b/crates/core/tests/schema.rs index 4b7a101..5469601 100644 --- a/crates/core/tests/schema.rs +++ b/crates/core/tests/schema.rs @@ -148,11 +148,11 @@ value = "max-age=31536000" #[test] fn hosts_are_sorted_by_hostname_whatever_the_file_order() { let a = SourceFile { - name: "b.toml", + name: "b.test.toml", contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }; let b = SourceFile { - name: "a.toml", + name: "a.test.toml", contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }; let m1 = load(&site(), &[a, b]).unwrap(); @@ -175,7 +175,7 @@ fn empty_site_file_is_allowed() { contents: "", }, &[SourceFile { - name: "a.toml", + name: "app.test.toml", contents: MINIMAL, }], ); @@ -236,7 +236,7 @@ fn rejects_unknown_field_in_site_file() { contents: "secrets = []\nsecret_values = { a = \"b\" }\n", }, &[SourceFile { - name: "a.toml", + name: "app.test.toml", contents: MINIMAL, }], ); @@ -334,9 +334,9 @@ fn accepts_good_hostnames() { "x-1.example.org", "0day.example.org", ] { - let r = one(&format!( - "hostname = {good:?}\nupstreams = [\"http://127.0.0.1:1\"]\n" - )); + 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:?}"); } } @@ -347,11 +347,11 @@ fn rejects_duplicate_hostnames_across_files() { &site(), &[ SourceFile { - name: "hosts/one.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, SourceFile { - name: "hosts/two.toml", + name: "other/app.test.toml", contents: MINIMAL, }, ], @@ -361,8 +361,8 @@ fn rejects_duplicate_hostnames_across_files() { errs.errors(), [ValidationError::DuplicateHostname { hostname: "app.test".into(), - first: "hosts/one.toml".into(), - second: "hosts/two.toml".into() + first: "hosts/app.test.toml".into(), + second: "other/app.test.toml".into() }] ); } @@ -373,18 +373,18 @@ fn duplicate_detection_is_independent_of_file_order() { &site(), &[ SourceFile { - name: "hosts/two.toml", + name: "other/app.test.toml", contents: MINIMAL, }, SourceFile { - name: "hosts/one.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, ], ); let errs = r.unwrap_err(); assert!( - matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/one.toml" && second == "hosts/two.toml") + matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/app.test.toml" && second == "other/app.test.toml") ); } @@ -394,11 +394,11 @@ fn rejects_duplicate_source_file_names() { &site(), &[ SourceFile { - name: "a.toml", + name: "app.test.toml", contents: MINIMAL, }, SourceFile { - name: "a.toml", + name: "app.test.toml", contents: MINIMAL, }, ], @@ -492,7 +492,7 @@ fn undefined_secret_is_reported_when_site_declares_none() { contents: "", }, &[SourceFile { - name: "a.toml", + name: "app.test.toml", contents: &format!( "{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n" ), @@ -526,7 +526,7 @@ fn rejects_bad_secret_names_in_site_file() { contents: &format!("secrets = [{bad:?}]\n"), }, &[SourceFile { - name: "a.toml", + name: "app.test.toml", contents: MINIMAL, }], ); @@ -672,7 +672,7 @@ fn forward_auth_requires_site_configuration() { contents: "", }, &[SourceFile { - name: "a.toml", + name: "app.test.toml", contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"), }], ); @@ -698,7 +698,7 @@ fn rejects_bad_forward_auth_site_config() { contents: &format!("[forward_auth]\nurl = {bad:?}\n"), }, &[SourceFile { - name: "a.toml", + name: "app.test.toml", contents: MINIMAL, }], ); @@ -737,15 +737,15 @@ fn collects_errors_from_every_file() { &site(), &[ SourceFile { - name: "a.toml", + name: "a.test.toml", contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n", }, SourceFile { - name: "b.toml", + name: "B.test.toml", contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }, SourceFile { - name: "c.toml", + name: "app.test.toml", contents: MINIMAL, }, ], @@ -780,3 +780,93 @@ fn never_panics_on_garbage() { 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 = (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 = (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}" + ); + } +} -- 2.53.0 From 60aee5d78a0f7dd0323512156210133ecb30045e Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:44:09 +0100 Subject: [PATCH 16/27] [core] Schema: reject wildcard header names, cap file size and upstreams, require .toml --- crates/core/src/compile/caddy.rs | 6 +- crates/core/src/compile/edge.rs | 3 +- crates/core/src/compile/mod.rs | 15 +++++ crates/core/src/edge_config.rs | 3 + crates/core/src/error.rs | 6 ++ crates/core/src/model.rs | 4 ++ crates/core/src/validate.rs | 78 +++++++++++++++++-------- crates/core/tests/compile.rs | 51 ++++++++++++---- crates/core/tests/golden/caddy.json | 17 +++++- crates/core/tests/golden/edge.json | 6 ++ crates/core/tests/schema.rs | 91 ++++++++++++++++++++++------- 11 files changed, 221 insertions(+), 59 deletions(-) diff --git a/crates/core/src/compile/caddy.rs b/crates/core/src/compile/caddy.rs index bb54087..2066cf7 100644 --- a/crates/core/src/compile/caddy.rs +++ b/crates/core/src/compile/caddy.rs @@ -10,7 +10,7 @@ use serde_json::{Map, Value, json}; -use super::{CompileOptions, join}; +use super::{CompileOptions, join, strip_headers}; use crate::{ AccessLog, AuthMode, ForwardAuth, HeaderRule, HeaderValue, Host, Model, Scheme, TlsMode, Upstream, @@ -204,11 +204,13 @@ fn logging(file: &str) -> Value { 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)^websocket$" } } }], + "match": [{ "header_regexp": { "Upgrade": { "pattern": "(?i)(^|,)\\s*websocket\\s*(,|$)" } } }], "handle": [{ "handler": "static_response", "status_code": 403 }] })); } diff --git a/crates/core/src/compile/edge.rs b/crates/core/src/compile/edge.rs index 30f643c..e6d7e13 100644 --- a/crates/core/src/compile/edge.rs +++ b/crates/core/src/compile/edge.rs @@ -4,7 +4,7 @@ //! Model → [`EdgeConfig`] for the Pingora data plane. -use super::{CompileOptions, join}; +use super::{CompileOptions, join, strip_headers}; use crate::edge_config::{ EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeForwardAuth, EdgeHeaderOp, EdgeHealthCheck, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue, @@ -30,6 +30,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig { 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() diff --git a/crates/core/src/compile/mod.rs b/crates/core/src/compile/mod.rs index 917d4e0..8c4e74e 100644 --- a/crates/core/src/compile/mod.rs +++ b/crates/core/src/compile/mod.rs @@ -108,6 +108,21 @@ fn check_path(p: &str) -> Result<(), &'static str> { 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 { + let mut out: Vec = 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) diff --git a/crates/core/src/edge_config.rs b/crates/core/src/edge_config.rs index 45a0282..a50d8c9 100644 --- a/crates/core/src/edge_config.rs +++ b/crates/core/src/edge_config.rs @@ -46,6 +46,9 @@ pub struct EdgeForwardAuth { pub upstream: EdgeUpstream, pub path_and_query: String, pub copy_headers: Vec, + /// 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, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index ab02502..ed088dd 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -24,6 +24,12 @@ pub enum ValidationError { 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, diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index f636ea6..72e43c2 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -221,6 +221,10 @@ impl Model { 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", diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index 2a311c6..f86c154 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -14,8 +14,8 @@ 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, Model, Scheme, SecretName, Site, TlsMode, - Upstream, UpstreamHost, + 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). @@ -192,6 +192,12 @@ pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result(f: &SourceFile<'_>) -> Result { 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::(f.contents) { return Err(E::Syntax { @@ -362,28 +368,45 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec let before = errors.len(); let f = || file.to_owned(); - if let Err(reason) = check_hostname(&raw.hostname) { - errors.push(E::InvalidHostname { + 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/.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 = Vec::new(); - for u in &raw.upstreams { + let mut seen_upstreams = BTreeSet::new(); + for u in raw.upstreams.iter().take(MAX_UPSTREAMS) { match parse_url(u, false) { Ok((up, _)) => { - if upstreams.contains(&up) { + if seen_upstreams.insert(up.clone()) { + upstreams.push(up); + } else { errors.push(E::DuplicateUpstream { file: f(), url: u.clone(), }); - } else { - upstreams.push(up); } } Err(reason) => errors.push(E::BadUpstreamUrl { @@ -410,18 +433,22 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec errors.push(E::ForwardAuthNotConfigured { file: f() }); } - // Identity headers set by forward-auth must not be overridable by a rule. - let identity: Vec = match (auth, site.and_then(|s| s.forward_auth.as_ref())) { - (AuthMode::ForwardAuth, Some(fa)) => fa - .copy_headers - .iter() - .map(|h| h.to_ascii_lowercase()) - .collect(), - (AuthMode::ForwardAuth, None) => AUTHELIA_COPY_HEADERS - .iter() - .map(|h| h.to_ascii_lowercase()) - .collect(), - _ => Vec::new(), + // 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 = 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); @@ -433,10 +460,10 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec && hc .path .bytes() - .all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}'); + .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 '}'", + "path must start with '/' and contain only visible ASCII without '{', '}' or '#'", )); return None; } @@ -570,12 +597,13 @@ fn check_rules( out } -/// RFC 9110 token. +/// 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)) + .all(|c| c.is_ascii_alphanumeric() || b"!#$%&'+-.^_`|~".contains(&c)) } fn check_header_value(v: &str) -> Result<(), &'static str> { diff --git a/crates/core/tests/compile.rs b/crates/core/tests/compile.rs index d67500c..ee55f92 100644 --- a/crates/core/tests/compile.rs +++ b/crates/core/tests/compile.rs @@ -223,26 +223,57 @@ 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}"); + 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 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_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"); + 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"); + assert!( + caddy.contains(r#"(?i)(^|,)\\s*websocket\\s*(,|$)"#), + "token-aware Upgrade matcher" + ); } diff --git a/crates/core/tests/golden/caddy.json b/crates/core/tests/golden/caddy.json index 0fd530c..2da0745 100644 --- a/crates/core/tests/golden/caddy.json +++ b/crates/core/tests/golden/caddy.json @@ -179,6 +179,21 @@ { "handler": "subroute", "routes": [ + { + "handle": [ + { + "handler": "headers", + "request": { + "delete": [ + "Remote-User", + "Remote-Groups", + "Remote-Email", + "Remote-Name" + ] + } + } + ] + }, { "handle": [ { @@ -392,7 +407,7 @@ { "header_regexp": { "Upgrade": { - "pattern": "(?i)^websocket$" + "pattern": "(?i)(^|,)\\s*websocket\\s*(,|$)" } } } diff --git a/crates/core/tests/golden/edge.json b/crates/core/tests/golden/edge.json index 16936cb..f7bb580 100644 --- a/crates/core/tests/golden/edge.json +++ b/crates/core/tests/golden/edge.json @@ -22,6 +22,12 @@ "Remote-Groups", "Remote-Email", "Remote-Name" + ], + "strip_headers": [ + "Remote-User", + "Remote-Groups", + "Remote-Email", + "Remote-Name" ] }, "hosts": [ diff --git a/crates/core/tests/schema.rs b/crates/core/tests/schema.rs index 5469601..bcd4845 100644 --- a/crates/core/tests/schema.rs +++ b/crates/core/tests/schema.rs @@ -336,7 +336,13 @@ fn accepts_good_hostnames() { ] { 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 }]); + let r = load( + &site(), + &[SourceFile { + name: &name, + contents: &contents, + }], + ); assert!(r.is_ok(), "{good}: {r:?}"); } } @@ -785,7 +791,13 @@ fn never_panics_on_garbage() { #[test] fn file_name_must_match_the_hostname() { - let r = load(&site(), &[SourceFile { name: "hosts/other.test.toml", contents: MINIMAL }]); + let r = load( + &site(), + &[SourceFile { + name: "hosts/other.test.toml", + contents: MINIMAL, + }], + ); let errs = r.unwrap_err(); assert_eq!( errs.errors(), @@ -817,14 +829,24 @@ fn rejects_wildcards_in_copy_headers() { 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 }], + &[SourceFile { + name: "app.test.toml", + contents: MINIMAL, + }], + ); + assert!( + r.unwrap_err() + .errors() + .iter() + .any(|e| matches!(e, ValidationError::InvalidHeaderName { .. })) ); - 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")); + let e = single_error(&format!( + "{MINIMAL}[health_check]\npath = \"/h#x\"\ninterval_secs = 5\n" + )); assert!(matches!(e, ValidationError::BadHealthCheck { .. }), "{e:?}"); } @@ -834,23 +856,43 @@ fn rejects_oversized_route_files() { 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 }], + &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"))); + 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 = (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 = (1..=64).map(|p| format!("\"http://127.0.0.1:{p}\"")).collect(); - assert!(one(&format!("hostname = \"app.test\"\nupstreams = [{}]\n", ups.join(", "))).is_ok()); + let ups: Vec = (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 = (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] @@ -861,11 +903,20 @@ fn identity_headers_stay_protected_with_a_custom_copy_list() { "{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 }], + &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 { .. })), + r.unwrap_err() + .errors() + .iter() + .any(|e| matches!(e, ValidationError::ProtectedHeader { .. })), "{header}" ); } -- 2.53.0 From a272e476b7d5ef62b61441099bf01b2fb0fbdaed Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:48:18 +0100 Subject: [PATCH 17/27] [edge] Fixes: skip 1xx, enforce auth timeout, resolve upstreams per connect, all Upgrade tokens, strip Remote-* --- crates/edge/src/fetch.rs | 94 +++++++++++++++++++--- crates/edge/src/forward_auth.rs | 9 ++- crates/edge/src/health.rs | 84 +++++++++++++------ crates/edge/src/http_app.rs | 44 +++++++++- crates/edge/src/proxy.rs | 111 +++++++++++++++++++------ crates/edge/src/runtime.rs | 57 ++++++++++--- crates/edge/tests/forward_auth.rs | 42 ++++++++-- crates/edge/tests/upstreams.rs | 129 +++++++++++++++++++++++++----- tests/support/src/authelia.rs | 33 ++++++-- tests/support/src/raw.rs | 21 ++++- 10 files changed, 509 insertions(+), 115 deletions(-) diff --git a/crates/edge/src/fetch.rs b/crates/edge/src/fetch.rs index f0172eb..ee9e900 100644 --- a/crates/edge/src/fetch.rs +++ b/crates/edge/src/fetch.rs @@ -3,7 +3,14 @@ // 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}; @@ -21,14 +28,17 @@ pub struct Fetched { /// 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. +const MAX_INFORMATIONAL: usize = 8; -pub fn peer(u: &UpstreamRt) -> HttpPeer { - let mut p = HttpPeer::new(u.addr, u.tls, u.sni.clone()); +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. +/// 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, @@ -36,18 +46,76 @@ pub async fn fetch( max_body: usize, timeout: Duration, ) -> Result { - let mut p = peer(u); - p.options.read_timeout = Some(timeout); - p.options.write_timeout = Some(timeout); - p.options.total_connection_timeout = Some(timeout); - let (mut http, _reused) = connector.get_http_session(&p).await?; + 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 { + 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?; - http.read_response_header().await?; - let header = http - .response_header() - .cloned() - .ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?; + + 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 { diff --git a/crates/edge/src/forward_auth.rs b/crates/edge/src/forward_auth.rs index 6f7b0a5..275714c 100644 --- a/crates/edge/src/forward_auth.rs +++ b/crates/edge/src/forward_auth.rs @@ -19,10 +19,10 @@ use std::time::Duration; use bytes::Bytes; use http::header::{self, HeaderName, HeaderValue}; -use pingora::Result; 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; @@ -82,6 +82,13 @@ pub async fn check( 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 diff --git a/crates/edge/src/health.rs b/crates/edge/src/health.rs index 648a53d..0195d99 100644 --- a/crates/edge/src/health.rs +++ b/crates/edge/src/health.rs @@ -35,25 +35,40 @@ async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool { { return false; } - match tokio::time::timeout(TIMEOUT, fetch(connector, u, req, 64 * 1024, TIMEOUT)).await { - Ok(Ok(f)) => f.header.status.is_success(), - _ => 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, path: &str, connector: &Arc) { + 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, path: String, every: Duration) { - let connector = Connector::new(None); + let connector = Arc::new(Connector::new(None)); loop { - for u in &host.upstreams { - let ok = probe(&connector, u, &path).await; - 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); - } - } - } + round(&host, &path, &connector).await; tokio::time::sleep(every).await; } } @@ -61,16 +76,39 @@ async fn watch(host: Arc, path: String, every: Duration) { #[async_trait] impl BackgroundService for HealthChecks { async fn start(&self, mut shutdown: ShutdownWatch) { - let mut tasks = Vec::new(); - for host in self.rt.hosts.values() { - if let Some(hc) = &host.cfg.health_check { - let every = Duration::from_secs(u64::from(hc.interval_secs.max(1))); - tasks.push(tokio::spawn(watch(host.clone(), hc.path.clone(), every))); + let checked: Vec<(Arc, String, Duration)> = self + .rt + .hosts + .values() + .filter_map(|h| { + h.cfg.health_check.as_ref().map(|hc| { + ( + h.clone(), + hc.path.clone(), + Duration::from_secs(u64::from(hc.interval_secs.max(1))), + ) + }) + }) + .collect(); + let mut tasks = tokio::task::JoinSet::new(); + let mut which = std::collections::HashMap::new(); + for (i, (h, p, every)) in checked.iter().enumerate() { + which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); + } + // A watcher never returns; if one ends anyway, say so and start it again. + loop { + tokio::select! { + _ = shutdown.changed() => break, + Some(done) = tasks.join_next_with_id() => { + let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() }; + if let Some(i) = which.remove(&id) { + let (h, p, every) = &checked[i]; + log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname); + which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); + } + } } } - let _ = shutdown.changed().await; - for t in tasks { - t.abort(); - } + tasks.abort_all(); } } diff --git a/crates/edge/src/http_app.rs b/crates/edge/src/http_app.rs index bae8e31..82c0492 100644 --- a/crates/edge/src/http_app.rs +++ b/crates/edge/src/http_app.rs @@ -10,8 +10,11 @@ use std::time::Instant; use async_trait::async_trait; use http::{Response, StatusCode, header}; -use pingora::apps::http_app::ServeHttp; +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}; @@ -32,7 +35,44 @@ fn empty(status: StatusCode) -> Response> { } #[async_trait] -impl ServeHttp for HttpApp { +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, + mut http: ServerSession, + shutdown: &ShutdownWatch, + ) -> Option { + 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> { let start = Instant::now(); let req = session.req_header(); diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index 9016b7f..a2d666d 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -30,18 +30,27 @@ pub struct EdgeProxy { pub struct Ctx { host: Option>, + /// Chosen upstream and its resolved addresses; connect failures move to the next address. + upstream: Option, + addrs: Vec, + addr_idx: usize, /// The Host header as the client sent it (with port, if any). host_header: String, start: Instant, } -/// Host header (HTTP/1) or :authority (HTTP/2). +/// 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.headers - .get(header::HOST) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - .or_else(|| req.uri.authority().map(|a| a.as_str().to_owned())) + 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() } @@ -89,11 +98,13 @@ fn apply( Ok(()) } -fn is_websocket_upgrade(req: &RequestHeader) -> bool { - req.headers - .get(header::UPGRADE) - .and_then(|v| v.to_str().ok()) - .is_some_and(|v| v.trim().eq_ignore_ascii_case("websocket")) +/// 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] @@ -103,6 +114,9 @@ impl ProxyHttp for EdgeProxy { fn new_ctx(&self) -> Ctx { Ctx { host: None, + upstream: None, + addrs: Vec::new(), + addr_idx: 0, host_header: String::new(), start: Instant::now(), } @@ -120,6 +134,11 @@ impl ProxyHttp for EdgeProxy { 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, @@ -171,27 +190,60 @@ impl ProxyHttp for EdgeProxy { async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result> { let host = ctx .host - .as_ref() + .clone() .ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?; - let n = host.upstreams.len(); - let first = host.next.fetch_add(1, Ordering::Relaxed); - let chosen = (0..n) - .map(|i| &host.upstreams[(first + i) % n]) - .find(|u| u.healthy.load(Ordering::Relaxed)) - .ok_or_else(|| Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream"))?; - log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, chosen.authority); - Ok(Box::new(fetch::peer(chosen))) + 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, - _c: &mut Ctx, + ctx: &mut Ctx, mut e: Box, ) -> Box { - // Like Caddy's default (no lb_try_duration): one attempt, then 502. - e.set_retry(false); + // 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 } @@ -201,6 +253,19 @@ impl ProxyHttp for EdgeProxy { 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::() + .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())?, diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index 5661836..0c0f904 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -6,7 +6,7 @@ //! parsed header names, secrets loaded, certificates loaded. Built once at startup. use std::collections::{BTreeSet, HashMap}; -use std::net::{SocketAddr, ToSocketAddrs}; +use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize}; @@ -27,7 +27,9 @@ pub enum Op { } pub struct UpstreamRt { - pub addr: SocketAddr, + /// 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, @@ -49,6 +51,8 @@ pub struct ForwardAuthRt { pub upstream: UpstreamRt, pub path_and_query: String, pub copy_headers: Vec, + /// Removed from every client request on a forward-auth host before anything else. + pub strip_headers: Vec, } pub struct Runtime { @@ -97,19 +101,25 @@ pub fn read_config(path: &Path) -> Result { } fn upstream(u: &EdgeUpstream) -> Result { - let err = |reason: String| EdgeError::Upstream { + let err = |reason: &str| EdgeError::Upstream { address: u.address.clone(), - reason, + reason: reason.to_owned(), }; - // Resolved once at startup; Pingora peers need a socket address. - let addr = u + let (host, port) = u .address - .to_socket_addrs() - .map_err(|e| err(format!("cannot resolve: {e}")))? - .next() - .ok_or_else(|| err("resolves to no address".into()))?; + .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 { - addr, + host: host.to_owned(), + port, authority: u.address.clone(), tls: u.tls, sni: u.sni.clone(), @@ -117,6 +127,26 @@ fn upstream(u: &EdgeUpstream) -> Result { }) } +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. + pub async fn resolve(&self) -> std::io::Result> { + if let Ok(ip) = self.host.parse::() { + return Ok(vec![SocketAddr::new(ip, self.port)]); + } + let addrs: Vec = tokio::net::lookup_host((self.host.as_str(), self.port)) + .await? + .collect(); + 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::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header { name: name.to_owned(), @@ -225,6 +255,11 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result>()?, + strip_headers: fa + .strip_headers + .iter() + .map(|h| header_name(h)) + .collect::>()?, }), None => None, }; diff --git a/crates/edge/tests/forward_auth.rs b/crates/edge/tests/forward_auth.rs index f6bfa77..336920f 100644 --- a/crates/edge/tests/forward_auth.rs +++ b/crates/edge/tests/forward_auth.rs @@ -266,7 +266,10 @@ async fn misbehaving_auth_answers_fail_closed() { site: &site, hosts: vec![host_file( "auth.test", - &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()), + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", + echo.url() + ), )], ..Default::default() }); @@ -275,15 +278,26 @@ async fn misbehaving_auth_answers_fail_closed() { 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 + 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"); + 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())); + 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. @@ -296,9 +310,15 @@ async fn misbehaving_auth_answers_fail_closed() { // 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"); + 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!( + t.elapsed() < std::time::Duration::from_secs(14), + "took {:?}", + t.elapsed() + ); assert!(echo.proxied().is_empty()); // Still serving afterwards. @@ -313,12 +333,18 @@ async fn remote_headers_are_stripped_even_with_a_custom_copy_list() { 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 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()), + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", + echo.url() + ), )], ..Default::default() }); diff --git a/crates/edge/tests/upstreams.rs b/crates/edge/tests/upstreams.rs index 30afee2..123113e 100644 --- a/crates/edge/tests/upstreams.rs +++ b/crates/edge/tests/upstreams.rs @@ -23,15 +23,35 @@ 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"), + 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(); + 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(); + let r = client::https( + edge.https, + "gone.test", + edge.roots(), + &Req::get("gone.test", "/"), + ) + .await + .unwrap(); assert_eq!(r.status, 502); } @@ -52,14 +72,35 @@ async fn health_checks_survive_informational_answers() { let edge = start(EdgeSpec { hosts: vec![host_file( "hc.test", - &format!("upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n", up.url()), + &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); + 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. @@ -67,37 +108,81 @@ async fn health_checks_survive_informational_answers() { 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()))], + 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"), + 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(); + 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 and routed by the URI's host -/// (RFC 9112 §3.2.2), as Go/Caddy do. +/// 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 = [\"{}\"]\n", echo.url()))], + 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, 404, "plain HTTP"); - let r = client::https(edge.https, "plain.test", edge.roots(), &Req::get("plain.test", "https://evil.test/x")) + let r = client::http(edge.http, &Req::get("plain.test", "http://evil.test/x")) .await .unwrap(); - assert_eq!(r.status, 404, "HTTPS"); - let r = client::http(edge.http, &Req::get("evil.test", "http://plain.test/x?y")).await.unwrap(); - assert_eq!(r.status, 308); + 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()); } diff --git a/tests/support/src/authelia.rs b/tests/support/src/authelia.rs index e453d78..90ac385 100644 --- a/tests/support/src/authelia.rs +++ b/tests/support/src/authelia.rs @@ -40,14 +40,18 @@ pub struct MockAuthelia { } fn h(req: &Recorded, name: &str) -> Option { - req.header(name).map(|v| String::from_utf8_lossy(v).into_owned()) + req.header(name) + .map(|v| String::from_utf8_lossy(v).into_owned()) } fn text(status: u16, reason: &str, body: &str) -> Vec { response( status, reason, - &[("Content-Type", "text/plain; charset=utf-8"), ("X-Sent-Content-Type", "text/plain; charset=utf-8")], + &[ + ("Content-Type", "text/plain; charset=utf-8"), + ("X-Sent-Content-Type", "text/plain; charset=utf-8"), + ], body.as_bytes(), ) } @@ -64,9 +68,12 @@ 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 { + 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") { @@ -76,13 +83,20 @@ fn decide(req: &Recorded) -> Reply { response( 401, "Unauthorized", - &[("WWW-Authenticate", "Basic realm=\"Authorization Required\""), ("X-Sent-Content-Type", "none")], + &[ + ("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(""); + 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), @@ -126,7 +140,10 @@ fn decide(req: &Recorded) -> Reply { impl MockAuthelia { pub async fn start() -> MockAuthelia { let server = RawServer::start(decide).await; - MockAuthelia { addr: server.addr, server } + MockAuthelia { + addr: server.addr, + server, + } } /// The `[forward_auth] url` for the site file. diff --git a/tests/support/src/raw.rs b/tests/support/src/raw.rs index 89fdb36..2b47172 100644 --- a/tests/support/src/raw.rs +++ b/tests/support/src/raw.rs @@ -27,7 +27,10 @@ pub fn response(status: u16, reason: &str, headers: &[(&str, &str)], body: &[u8] 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())); + 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 @@ -44,12 +47,17 @@ pub struct RawServer { 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 server = RawServer { + addr: listener.local_addr().unwrap(), + requests: Arc::default(), + }; let handler: Arc = Arc::new(handler); let requests = server.requests.clone(); tokio::spawn(async move { loop { - let Ok((mut stream, _)) = listener.accept().await else { continue }; + let Ok((mut stream, _)) = listener.accept().await else { + continue; + }; let handler = handler.clone(); let requests = requests.clone(); tokio::spawn(async move { @@ -97,5 +105,10 @@ fn parse(buf: &[u8]) -> Option { .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() }) + Some(Recorded { + method, + path, + headers, + body: Vec::new(), + }) } -- 2.53.0 From bcf94928c91037e87861b6e886df27b592237201 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:53:38 +0100 Subject: [PATCH 18/27] [diff] Corpus: 57 cases, all headers compared, narrow named divergences, misbehaving-auth and Upgrade-token cases --- crates/edge/tests/secrets.rs | 2 +- tests/diff/src/lib.rs | 504 ++++++++++++++++++++++++---------- tests/support/src/client.rs | 22 +- tests/support/src/upstream.rs | 3 +- 4 files changed, 381 insertions(+), 150 deletions(-) diff --git a/crates/edge/tests/secrets.rs b/crates/edge/tests/secrets.rs index addc881..c362aa3 100644 --- a/crates/edge/tests/secrets.rs +++ b/crates/edge/tests/secrets.rs @@ -147,7 +147,7 @@ async fn injected_secret_never_appears_in_a_response_or_log() { .await .unwrap() { - WsOutcome::Upgraded { status, echo } => { + WsOutcome::Upgraded { status, echo, .. } => { assert_eq!(status, 101); assert_eq!(echo, "ping"); } diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index 137e119..20b82be 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -58,7 +58,7 @@ impl Env { let auth = MockAuthelia::start().await; 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() ); 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 name: &'static str, 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 { Case { name, 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, -/// auth denied and allowed, health checks. +/// auth denied and allowed, misbehaving auth server, health checks, odd request targets. pub fn corpus() -> Vec { 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( @@ -333,6 +341,13 @@ pub fn corpus() -> Vec { 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, @@ -368,50 +383,52 @@ pub fn corpus() -> Vec { p, Req::get("unknown.test", "/"), ), - Case { - name: "HTTP redirects to HTTPS", - action: Action::Http { - req: Req::get(p, "/a/b?c=d"), - }, - headers: STD, - }, - Case { - name: "HTTP unknown host", - action: Action::Http { - req: Req::get("unknown.test", "/"), - }, - headers: STD, - }, - Case { - name: "HTTP unknown ACME token", - action: Action::Http { - req: Req::get(p, "/.well-known/acme-challenge/nope"), - }, - headers: STD, - }, - Case { - name: "websocket upgrade", - action: Action::Websocket { - sni: "ws.test", - host: "ws.test", - headers: vec![], - }, - headers: &["upgrade"], - }, - Case { - name: "websocket refused when disabled", - action: Action::Websocket { - sni: "nows.test", - host: "nows.test", - headers: vec![], - }, - headers: STD, - }, + 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", @@ -437,7 +454,7 @@ pub fn corpus() -> Vec { https( "auth forbidden", a, - Req::get(a, "/").header("cookie", "authelia_session=forbidden"), + Req::get(a, "/").header("cookie", &session("forbidden")), ), https( "auth allowed with session", @@ -451,11 +468,19 @@ pub fn corpus() -> Vec { .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", "authelia_session=nameless") + .header("cookie", &session("nameless")) .header("remote-user", "mallory"), ), https( @@ -468,24 +493,40 @@ pub fn corpus() -> Vec { a, Req::get(a, "/search?q=a+b").header(good.0, good.1), ), - Case { - name: "websocket denied by auth", - action: Action::Websocket { - sni: "wsauth.test", - host: "wsauth.test", - headers: vec![], - }, - headers: STD, - }, - Case { - name: "websocket allowed by auth", - action: Action::Websocket { - sni: "wsauth.test", - host: "wsauth.test", - headers: vec![good], - }, - headers: &["upgrade"], - }, + 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 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", @@ -497,6 +538,20 @@ pub fn corpus() -> Vec { ] } +/// 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 { @@ -505,56 +560,59 @@ pub struct Observation { pub body: String, } -fn observe(resp: &Resp, case: &Case, t: &Target) -> Observation { - let mut headers = BTreeMap::new(); - for h in case.headers { - let all = resp.header_all(h); - if !all.is_empty() { - // The two engines listen on different ports; Location carries the HTTPS port. - let v = all - .join("\n") - .replace(&format!(":{}", t.https.port()), ":"); - headers.insert((*h).to_owned(), v); +fn observe_parts(status: u16, raw: &[(String, String)], body: &[u8], t: &Target) -> Observation { + let mut headers: BTreeMap = 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()), ":"); + headers + .entry(n) + .and_modify(|e| { + e.push('\n'); + e.push_str(&v) + }) + .or_insert(v); } Observation { - status: resp.status, + status, 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) -> Observation { match &case.action { - Action::Https { sni, req } => match client::https(t.https, sni, roots, req).await { - Ok(r) => observe(&r, case, t), - Err(e) => Observation { - status: 0, - headers: BTreeMap::new(), - body: format!("client error: {e}"), - }, - }, - 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::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, echo }) => Observation { + Ok(WsOutcome::Upgraded { status, - headers: BTreeMap::new(), - body: format!("echo: {echo}"), - }, - Ok(WsOutcome::Refused(r)) => observe(&r, case, t), - Err(e) => Observation { - status: 0, - headers: BTreeMap::new(), - body: format!("client error: {e}"), - }, + headers, + echo, + }) => observe_parts(status, &headers, format!("echo: {echo}").as_bytes(), t), + Ok(WsOutcome::Refused(r)) => observe(&r, t), + Err(e) => failed(e), } } } @@ -566,19 +624,116 @@ pub struct Outcome { pub caddy: Observation, } -/// Documented, accepted differences between the engines, each with its reason. Anything -/// else is a mismatch. -pub const KNOWN_DIVERGENCES: &[(&str, &str)] = &[( - "KD-1", - "Caddy (Go net/http) adds a sniffed Content-Type when the upstream sends none; \ - Ianitor passes the upstream response unchanged (no MIME sniffing).", -)]; +/// 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, + }, +} -/// Content types Go's `http.DetectContentType` produces for small text and binary bodies. -const SNIFFED: [&str; 3] = [ - "text/plain; charset=utf-8", - "text/html; charset=utf-8", - "application/octet-stream", +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", + }, ]; impl Outcome { @@ -586,24 +741,46 @@ impl Outcome { self.ianitor == self.caddy } - /// `Some(id)` when the only difference is a documented divergence. - pub fn known_divergence(&self) -> Option<&'static str> { + /// The divergence ids that explain every difference, or `None`. + pub fn known_divergence(&self) -> Option { if self.same() { return None; } - let sniffed = self - .caddy - .headers - .get("content-type") - .is_some_and(|v| SNIFFED.contains(&v.as_str())); - if sniffed && !self.ianitor.headers.contains_key("content-type") { - let mut c = self.caddy.clone(); - c.headers.remove("content-type"); - if c == self.ianitor { - return Some("KD-1"); + 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()); } } - None + 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 { @@ -628,26 +805,37 @@ impl Report { } 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, {} 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.iter().filter(|o| o.same()).count(), - self.known().len(), + 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); + let _ = writeln!(s, " same {:3} {}", o.ianitor.status, o.name); } 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 { - let _ = writeln!(s, " DIFF {}", o.name); - let _ = writeln!(s, " ianitor: {:?}", short(&o.ianitor)); - let _ = writeln!(s, " caddy: {:?}", short(&o.caddy)); + let _ = writeln!(s, " DIFF {}", o.name); + for d in differences(&o.ianitor, &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 } @@ -721,3 +909,27 @@ pub fn break_edge(json: &str) -> String { 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 { + 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 +} diff --git a/tests/support/src/client.rs b/tests/support/src/client.rs index 873d875..f3de227 100644 --- a/tests/support/src/client.rs +++ b/tests/support/src/client.rs @@ -183,7 +183,11 @@ pub async fn http(addr: SocketAddr, req: &Req) -> io::Result { #[derive(Debug, Clone, PartialEq, Eq)] pub enum WsOutcome { /// 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. Refused(Resp), } @@ -212,6 +216,16 @@ pub async fn websocket( 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)?; @@ -220,7 +234,11 @@ pub async fn websocket( other_msg => return Err(other(format!("no echo: {other_msg:?}"))), }; let _ = ws.close(None).await; - Ok(WsOutcome::Upgraded { status, echo }) + Ok(WsOutcome::Upgraded { + status, + headers, + echo, + }) } Err(tungstenite::Error::Http(resp)) => { let status = resp.status().as_u16(); diff --git a/tests/support/src/upstream.rs b/tests/support/src/upstream.rs index db1e741..24a50a7 100644 --- a/tests/support/src/upstream.rs +++ b/tests/support/src/upstream.rs @@ -23,8 +23,9 @@ 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; 12] = [ +pub const ECHO_HEADERS: [&str; 13] = [ "host", + "x-remove-me-too", "x-forwarded-for", "x-forwarded-proto", "x-forwarded-host", -- 2.53.0 From a052c32b7707e1a29d4eeafd9369726a3b0d6b16 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:57:04 +0100 Subject: [PATCH 19/27] [repo] Hygiene: NUL-safe pre-commit hook, more key formats, 5,000,000-byte limit, QC bypass cases --- .githooks/pre-commit | 147 ++++++++++++++++++++++------------- .githooks/test-pre-commit.sh | 115 +++++++++++++++++++++++---- 2 files changed, 193 insertions(+), 69 deletions(-) diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 872895a..2f90534 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -1,65 +1,102 @@ -#!/bin/sh +#!/usr/bin/env bash # SPDX-License-Identifier: MPL-2.0 # # Ianitor pre-commit hook. Rejects staged files that must never be in git: -# - binaries (anything git itself classifies as binary) -# - private keys (PEM / OpenSSH / PKCS#8 / PGP headers, and key-store file names) -# - files over 5 MB -# - build output and dependencies (target/, node_modules/, dist/) +# - 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, WireGuard PrivateKey lines, 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/, build/, .svelte-kit/ +# 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 +# blocks the commit. # # Enable once per clone: git config core.hooksPath .githooks -# Test it: sh .githooks/test-pre-commit.sh -# Plain POSIX sh: works in Git Bash on Windows and on Linux. +# Test it: bash .githooks/test-pre-commit.sh +# Needs bash 4+ (Git Bash on Windows, any Linux). -LIMIT=5242880 # 5 MiB +set -u +LIMIT=5000000 -# Every check prints one "FAIL" line on stdout per problem (reasons go to stderr), -# so the loop can run in a pipeline subshell and still be counted here. -failures=$( - # numstat prints "--path" for files git treats as binary. - git -c core.quotePath=false diff --cached --numstat --diff-filter=ACMR | while IFS= read -r line; do - added=${line%%" "*} - rest=${line#*" "} - deleted=${rest%%" "*} - path=${rest#*" "} - if [ "$added" = "-" ] && [ "$deleted" = "-" ]; then - printf 'pre-commit: rejected %s: binary file\n' "$path" >&2 - echo FAIL - fi - done - - git -c core.quotePath=false diff --cached --name-only --diff-filter=ACMR | while IFS= read -r path; do - case "/$path" in - */target/*|*/node_modules/*|*/dist/*) - printf 'pre-commit: rejected %s: build output or dependency directory\n' "$path" >&2 - echo FAIL ;; - esac - - base=${path##*/} - case "$base" in - *.pub) ;; - *.key|*.p12|*.pfx|*.jks|*.keystore|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 - echo FAIL ;; - esac - - # Size of the staged blob, not of the working-tree file. - size=$(git cat-file -s ":$path" 2>/dev/null || echo 0) - if [ "$size" -gt "$LIMIT" ]; then - printf 'pre-commit: rejected %s: %s bytes is over the 5 MB limit\n' "$path" "$size" >&2 - echo FAIL - fi - - if git cat-file -p ":$path" 2>/dev/null | grep -E -q -e '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----'; then - printf 'pre-commit: rejected %s: contains a private key\n' "$path" >&2 - echo FAIL - fi - done +# Patterns are written so that this file does not match them itself. +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:]]*PrivateKey[[:space:]]*=[[:space:]]*[A-Za-z0-9+/]{42,43}=?[[:space:]]*$' ) +JWK_KTY='"kt[y]"[[:space:]]*:' +JWK_D='"d"[[:space:]]*:[[:space:]]*"' -case "$failures" in - *FAIL*) - printf 'pre-commit: commit blocked. Unstage the files above (git rm --cached ).\n' >&2 - exit 1 ;; -esac +failed=0 +reject() { + # %q keeps odd characters in names visible and harmless. + printf 'pre-commit: rejected %q: %s\n' "$1" "$2" >&2 + failed=1 +} + +list=$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/ianitor-pre-commit.$$") +blob=$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/ianitor-pre-commit-blob.$$") +trap 'rm -f "$list" "$blob"' EXIT + +if ! git diff --cached --raw -z --no-abbrev --no-renames --diff-filter=ACMT >"$list"; then + echo 'pre-commit: cannot list the staged files; commit blocked.' >&2 + exit 1 +fi + +# --raw -z gives ": " NUL "" NUL. +while IFS= read -r -d '' meta && IFS= read -r -d '' path; do + read -r _ mode _ sha _ <<<"${meta#:}" + lower=${path,,} + + case "/$lower" in + */target/*|*/node_modules/*|*/dist/*|*/build/*|*/.svelte-kit/*) + reject "$path" "build output or dependency directory" ;; + esac + + 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 + + if ! git cat-file blob "$sha" >"$blob" 2>/dev/null; then + reject "$path" "the staged content cannot be read" + continue + fi + size=$(wc -c <"$blob" | tr -d '[:space:]') + if ! [[ $size =~ ^[0-9]+$ ]]; then + reject "$path" "the staged size cannot be determined" + continue + fi + if (( size > LIMIT )); then + reject "$path" "$size bytes is over the 5 MB limit (5,000,000 bytes)" + fi + + textsize=$(tr -d '\000' <"$blob" | wc -c | tr -d '[:space:]') + if [ "$textsize" != "$size" ]; then + reject "$path" "binary file (contains NUL bytes)" + fi + + for pattern in "${KEY_PATTERNS[@]}"; do + if LC_ALL=C grep -a -E -q -e "$pattern" "$blob"; then + reject "$path" "contains a private key" + break + fi + done + if LC_ALL=C grep -a -E -q -e "$JWK_KTY" "$blob" && LC_ALL=C grep -a -E -q -e "$JWK_D" "$blob"; then + reject "$path" "contains a JWK private key" + fi +done <"$list" + +if [ "$failed" -ne 0 ]; then + echo 'pre-commit: commit blocked. Unstage the files above (git rm --cached ).' >&2 + exit 1 +fi exit 0 diff --git a/.githooks/test-pre-commit.sh b/.githooks/test-pre-commit.sh index 6befb3f..8cbbd33 100755 --- a/.githooks/test-pre-commit.sh +++ b/.githooks/test-pre-commit.sh @@ -1,9 +1,10 @@ -#!/bin/sh +#!/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 a normal file is accepted. -# Usage: sh .githooks/test-pre-commit.sh (Git Bash on Windows or Linux) +# 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) @@ -16,28 +17,58 @@ 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 -# expect (file must already exist) -expect() { - want=$1; what=$2; path=$3 - git add -f -- "$path" - if git commit -q -m "$what" --no-gpg-sign >/dev/null 2>"$WORK/.err"; then got=accept; else got=reject; fi +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 - # Leave the index clean for the next case. 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 (file must exist in the work tree) +expect() { + git add -f -- "$3" + commit_and_check "$1" "$2" +} + +# expect_staged +# 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 @@ -48,7 +79,15 @@ expect accept "source file" main.rs printf '\000\001\002\003binary\000' > 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 printf '%s PRIVATE KEY-----\nMIGHAgEAMBMG\n%s PRIVATE KEY-----\n' "$B" "$E" > pkcs8.pem @@ -63,9 +102,33 @@ 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 > 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 '[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 '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 @@ -75,20 +138,44 @@ 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 -head -c 6291456 /dev/zero | tr '\000' 'a' > big.txt +cp "$SRC/six-mb" big.txt expect reject "6 MB text file" big.txt -head -c 4194304 /dev/zero | tr '\000' 'a' > medium.txt -expect accept "4 MB text file" medium.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 build/" apps/web/build/index.html + +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" + printf '\nhook: %d passed, %d failed\n' "$pass" "$fail" [ "$fail" -eq 0 ] -- 2.53.0 From ecdba7775f0d3ca4a8b07f0e5462d70997ad7702 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:58:00 +0100 Subject: [PATCH 20/27] [docs] Notes: tests/support in layout, forward-auth failure modes, bash hook self-test --- CLAUDE.md | 3 ++- crates/edge/src/forward_auth.rs | 6 +++++- docs/ROADMAP.md | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c34972f..8e44b5b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. @@ -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 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: sh .githooks/test-pre-commit.sh) +One-time per clone: git config core.hooksPath .githooks (self-test: bash .githooks/test-pre-commit.sh) ## Rules - Commits: `[] : `. No AI attribution, no trailers, ever. diff --git a/crates/edge/src/forward_auth.rs b/crates/edge/src/forward_auth.rs index 275714c..4666f5a 100644 --- a/crates/edge/src/forward_auth.rs +++ b/crates/edge/src/forward_auth.rs @@ -13,7 +13,11 @@ //! 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, 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; diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a0fb77f..0b49887 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -114,7 +114,7 @@ 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] 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 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) 7. Red Panda Network donation route for a non-US individual and the receipt they issue. (phase 4, Mark) -- 2.53.0 From 2dfb0b8ecc3c88f5258a78538bc63d96e1b0dcf0 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 15:58:14 +0100 Subject: [PATCH 21/27] [tests] Windows: Linux-only test targets report one explicit skip instead of zero tests --- crates/edge/tests/acme_pebble.rs | 415 +++++++++--------- crates/edge/tests/forward_auth.rs | 673 +++++++++++++++--------------- crates/edge/tests/secrets.rs | 477 +++++++++++---------- crates/edge/tests/upstreams.rs | 341 +++++++-------- tests/diff/tests/diff.rs | 158 +++---- 5 files changed, 1065 insertions(+), 999 deletions(-) diff --git a/crates/edge/tests/acme_pebble.rs b/crates/edge/tests/acme_pebble.rs index dc27f3c..9af257d 100644 --- a/crates/edge/tests/acme_pebble.rs +++ b/crates/edge/tests/acme_pebble.rs @@ -10,209 +10,224 @@ //! //! 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)] +#[cfg(unix)] mod common; -use std::os::unix::fs::PermissionsExt; -use std::process::{Command, Stdio}; -use std::time::{Duration, Instant}; - -use 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" +#[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" + ); + } +} diff --git a/crates/edge/tests/forward_auth.rs b/crates/edge/tests/forward_auth.rs index 336920f..093678e 100644 --- a/crates/edge/tests/forward_auth.rs +++ b/crates/edge/tests/forward_auth.rs @@ -6,337 +6,245 @@ //! goes back to the client unchanged, and an allowed request carries the identity headers //! from the auth server and never the client's own. -#![cfg(unix)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#[cfg(unix)] mod common; -use 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") +#[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!() + ); } -#[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( +#[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() ), - ), - 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() } - }; + )], + ..Default::default() + }); + let roots = edge.roots(); - // 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 = 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 + ); - let r = go(Req::new("HEAD", "auth.test", "/")).await; - assert_eq!(r.status, 302); + // 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 = 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"), + let r = client::https( + edge.https, + "auth.test", + roots, + &Req::get("auth.test", "/").header("authorization", "Bearer good"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200); } - 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() - ); + #[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( @@ -352,25 +260,130 @@ async fn remote_headers_are_stripped_even_with_a_custom_copy_list() { 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"), + &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); - 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}"); + 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}"); + } } } } diff --git a/crates/edge/tests/secrets.rs b/crates/edge/tests/secrets.rs index c362aa3..2775f18 100644 --- a/crates/edge/tests/secrets.rs +++ b/crates/edge/tests/secrets.rs @@ -5,256 +5,269 @@ //! 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. -#![cfg(unix)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#[cfg(unix)] mod common; -use 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()) +#[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!() + ); } -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}"); -} +#[cfg(unix)] +mod unix { -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, - ); + 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()) } - 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( + 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 = [\"{}\"]\naccess_log = \"truncated\"\n{rule}", + "upstreams = [\"{}\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"present\"\n\ + [[request_headers]]\naction = \"set\"\nname = \"X-B\"\nsecret = \"absent\"\n", 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:?}"), + )], + 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); } - // 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 + #[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); } - // 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 common::Edge) -> std::process::ExitStatus { - for _ in 0..200 { - if let Some(s) = edge.exited() { - return s; + 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)); } - std::thread::sleep(std::time::Duration::from_millis(50)); + panic!("edge kept running:\n{}", edge.stderr()); } - panic!("edge kept running:\n{}", edge.stderr()); } diff --git a/crates/edge/tests/upstreams.rs b/crates/edge/tests/upstreams.rs index 123113e..dabb165 100644 --- a/crates/edge/tests/upstreams.rs +++ b/crates/edge/tests/upstreams.rs @@ -5,184 +5,197 @@ //! Upstream handling: name resolution at connect time, health checks that survive odd //! answers, websocket refusal on every Upgrade token, absolute-form requests. -#![cfg(unix)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#[cfg(unix)] mod common; -use std::time::{Duration, Instant}; - -use 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); +#[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!() + ); } -/// 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( +#[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", - &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 - ); -} + 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) + /// 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, 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( + assert_eq!(r.status, 400, "plain HTTP, Host differs from the target"); + let r = client::https( + edge.https, "plain.test", - &format!( - "upstreams = [\"{}\"] -", - echo.url() - ), - )], - ..Default::default() - }); - let r = client::http(edge.http, &Req::get("plain.test", "http://evil.test/x")) + edge.roots(), + &Req::get("plain.test", "https://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()); + 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")) + 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, 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()); + assert_eq!(r.status, 200); + assert!(r.text().contains("\"path\":\"/abs\""), "{}", r.text()); + } } diff --git a/tests/diff/tests/diff.rs b/tests/diff/tests/diff.rs index fcb3320..bfb78e9 100644 --- a/tests/diff/tests/diff.rs +++ b/tests/diff/tests/diff.rs @@ -5,85 +5,97 @@ //! 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`. -#![cfg(unix)] #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use ianitor_diff::{ - Env, break_caddy, break_edge, compile_pair, corpus, run_corpus, settle, start_caddy, start_edge, -}; -use ianitor_testkit::proc::require_binary; +#[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!() + ); +} -#[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; +#[cfg(unix)] +mod unix { + use ianitor_diff::{ + Env, break_caddy, break_edge, compile_pair, corpus, run_corpus, settle, start_caddy, + start_edge, }; - 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; + use ianitor_testkit::proc::require_binary; - let report = run_corpus(&ianitor, &caddy, env.roots()).await; - println!("{}", report.render("Ianitor vs Caddy")); - let statuses: Vec = 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] { + #[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!( - statuses.contains(&wanted), - "corpus covers status {wanted}: {statuses:?}" + 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 = 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:?}" ); } } - -#[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:?}" - ); -} -- 2.53.0 From ed2a1661650c80c03ffef18873cb8480a2f311c0 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 16:33:13 +0100 Subject: [PATCH 22/27] [repo] Hygiene: batched hook (300 files 1.7 s), narrower build/ and JWK rules, more key forms, bash-4 check --- .githooks/pre-commit | 165 +++++++++++++++++++++++++---------- .githooks/test-pre-commit.sh | 73 +++++++++++++++- 2 files changed, 191 insertions(+), 47 deletions(-) diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 2f90534..969166c 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -4,31 +4,45 @@ # 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, WireGuard PrivateKey lines, and key-store file names +# 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/, build/, .svelte-kit/ +# - build output and dependencies: target/, node_modules/, dist/, .svelte-kit/ anywhere; +# build/ at the repository root, in apps//, 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 -# blocks the commit. +# 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 -# Needs bash 4+ (Git Bash on Windows, any Linux). + +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. +# 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:]]*PrivateKey[[:space:]]*=[[:space:]]*[A-Za-z0-9+/]{42,43}=?[[:space:]]*$' + '^[[:space:]]*(-[[:space:]]*)?["'\'']?private_?key["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9+/]{42,43}=?["'\'']?[[:space:]]*,?[[:space:]]*$' ) -JWK_KTY='"kt[y]"[[:space:]]*:' -JWK_D='"d"[[: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() { @@ -36,25 +50,59 @@ reject() { printf 'pre-commit: rejected %q: %s\n' "$1" "$2" >&2 failed=1 } - -list=$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/ianitor-pre-commit.$$") -blob=$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/ianitor-pre-commit-blob.$$") -trap 'rm -f "$list" "$blob"' EXIT - -if ! git diff --cached --raw -z --no-abbrev --no-renames --diff-filter=ACMT >"$list"; then - echo 'pre-commit: cannot list the staged files; commit blocked.' >&2 +die() { + echo "pre-commit: $1; commit blocked." >&2 exit 1 -fi +} + +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// 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 ": " NUL "" NUL. while IFS= read -r -d '' meta && IFS= read -r -d '' path; do - read -r _ mode _ sha _ <<<"${meta#:}" + read -r -a f <<<"${meta#:}" + mode=${f[1]} sha=${f[3]} lower=${path,,} case "/$lower" in - */target/*|*/node_modules/*|*/dist/*|*/build/*|*/.svelte-kit/*) + */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 @@ -65,35 +113,60 @@ while IFS= read -r -d '' meta && IFS= read -r -d '' path; do # Submodule entries have no blob to inspect. [ "$mode" = 160000 ] && continue + staged[$path]=$sha + paths+=("$path") + shas+=("$sha") +done <"$tmp/list" - if ! git cat-file blob "$sha" >"$blob" 2>/dev/null; then - reject "$path" "the staged content cannot be read" - continue - fi - size=$(wc -c <"$blob" | tr -d '[:space:]') - if ! [[ $size =~ ^[0-9]+$ ]]; then - reject "$path" "the staged size cannot be determined" - continue - fi - if (( size > LIMIT )); then - reject "$path" "$size bytes is over the 5 MB limit (5,000,000 bytes)" - fi - - textsize=$(tr -d '\000' <"$blob" | wc -c | tr -d '[:space:]') - if [ "$textsize" != "$size" ]; then - reject "$path" "binary file (contains NUL bytes)" - fi - - for pattern in "${KEY_PATTERNS[@]}"; do - if LC_ALL=C grep -a -E -q -e "$pattern" "$blob"; then - reject "$path" "contains a private key" - break +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 - done - if LC_ALL=C grep -a -E -q -e "$JWK_KTY" "$blob" && LC_ALL=C grep -a -E -q -e "$JWK_D" "$blob"; then - reject "$path" "contains a JWK private key" - fi -done <"$list" + 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 ).' >&2 diff --git a/.githooks/test-pre-commit.sh b/.githooks/test-pre-commit.sh index 8cbbd33..a7a239c 100755 --- a/.githooks/test-pre-commit.sh +++ b/.githooks/test-pre-commit.sh @@ -111,6 +111,9 @@ 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 @@ -120,9 +123,33 @@ 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 @@ -163,7 +190,23 @@ 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 build/" apps/web/build/index.html +expect reject "file under apps//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 @@ -177,5 +220,33 @@ expect_staged reject "PEM key in a file named with a newline" "$(printf 'new\nli 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 ] -- 2.53.0 From ee8c3047403305bc9c979e1364f9ec4459acff86 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 16:39:28 +0100 Subject: [PATCH 23/27] [tests] Mock Authelia: record request bodies (Content-Length and chunked) so body assertions can fail --- tests/support/src/raw.rs | 130 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 128 insertions(+), 2 deletions(-) diff --git a/tests/support/src/raw.rs b/tests/support/src/raw.rs index 2b47172..a35b07b 100644 --- a/tests/support/src/raw.rs +++ b/tests/support/src/raw.rs @@ -3,7 +3,8 @@ // 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. +//! 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}; @@ -69,7 +70,13 @@ impl RawServer { 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()); match handler(&req) { 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( + stream: &mut S, + req: &Recorded, + mut have: Vec, +) -> Option> { + 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 { let end = buf.windows(4).position(|w| w == b"\r\n\r\n")?; let head = std::str::from_utf8(&buf[..end]).ok()?; @@ -112,3 +190,51 @@ fn parse(buf: &[u8]) -> Option { 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)> = 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.53.0 From 8c04b0f4bd5ae01ccb62cba1e7ea4be66fca053d Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 16:39:29 +0100 Subject: [PATCH 24/27] [edge] Upstreams: 3 s deadline on name lookups, 502 on timeout --- crates/edge/src/runtime.rs | 98 ++++++++++++++++++++++++++++++++++---- 1 file changed, 88 insertions(+), 10 deletions(-) diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index 0c0f904..f3fcb09 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -10,6 +10,7 @@ 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::{ @@ -127,23 +128,100 @@ fn upstream(u: &EdgeUpstream) -> Result { }) } +/// 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> { - if let Ok(ip) = self.host.parse::() { - return Ok(vec![SocketAddr::new(ip, self.port)]); - } - let addrs: Vec = tokio::net::lookup_host((self.host.as_str(), self.port)) - .await? - .collect(); - if addrs.is_empty() { + 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( + host: &str, + port: u16, + deadline: Duration, + lookup: F, +) -> std::io::Result> +where + F: FnOnce(String, u16) -> Fut, + Fut: Future>>, +{ + if let Ok(ip) = host.parse::() { + 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::NotFound, - "name resolves to no address", + std::io::ErrorKind::TimedOut, + format!("name lookup took longer than {deadline:?}"), )); } - Ok(addrs) + }; + if addrs.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + "name resolves to no address", + )); + } + Ok(addrs) +} + +#[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); } } -- 2.53.0 From 27b0a165b2bc18bf86e98be9c10f2d9071189952 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 16:41:41 +0100 Subject: [PATCH 25/27] [edge] Fetch: accept up to 1000 informational heads (Go has no count limit); KD-10 beyond --- crates/edge/src/fetch.rs | 6 ++++-- tests/diff/src/lib.rs | 24 ++++++++++++++++++++++++ tests/support/src/authelia.rs | 10 +++++++++- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/edge/src/fetch.rs b/crates/edge/src/fetch.rs index ee9e900..c6700eb 100644 --- a/crates/edge/src/fetch.rs +++ b/crates/edge/src/fetch.rs @@ -28,8 +28,10 @@ pub struct Fetched { /// 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. -const MAX_INFORMATIONAL: usize = 8; +/// 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()); diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index 20b82be..8e10311 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -505,6 +505,21 @@ pub fn corpus() -> Vec { 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, @@ -734,6 +749,15 @@ pub const KNOWN_DIVERGENCES: &[Divergence] = &[ }, 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 { diff --git a/tests/support/src/authelia.rs b/tests/support/src/authelia.rs index 90ac385..6293ebe 100644 --- a/tests/support/src/authelia.rs +++ b/tests/support/src/authelia.rs @@ -11,7 +11,8 @@ //! - `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), `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), //! `switch` (101 Switching Protocols), `hang` (never answers) //! - 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 } + 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); -- 2.53.0 From 0c42138d747fee2ae67d59d6e77227082add9fb1 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 16:42:45 +0100 Subject: [PATCH 26/27] [edge] Lint: resolver tests at the end of runtime.rs --- crates/edge/src/runtime.rs | 84 +++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index f3fcb09..b54af59 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -183,48 +183,6 @@ where Ok(addrs) } -#[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); - } -} - fn header_name(name: &str) -> Result { HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header { name: name.to_owned(), @@ -362,3 +320,45 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result Date: Sat, 7 Nov 2026 16:46:25 +0100 Subject: [PATCH 27/27] [docs] Roadmap: Phase 1 status and handover --- docs/ROADMAP.md | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 0b49887..78defcd 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -121,10 +121,38 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit ## 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 `.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. -- 2.53.0