From 8aa288e3ad23d86fbaa611b8ac8294c56ec9a676 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:57:36 -0500 Subject: [PATCH 1/4] test: canonicalization fuzz targets, differential and regression tests (issue #19) Adds, with no change to production code: - fuzz/ (cargo-fuzz, outside the root workspace): canon_path, canon_host, canon_origin and canon_headers, with a small seed corpus. The invariants live in crates/ap-core/tests/common/invariants.rs and are shared with the cargo tests. - crates/ap-core/tests/canon_differential.rs: fixed-seed generator over the issue classes, checked against the http and url parsers. - crates/ap-core/tests/canon_regression.rs: table-driven cases for every class in the issue. - crates/ap-proxy/src/canon_diff_tests.rs: pipeline test with the mock upstream, asserting the policy-matched path is byte-identical to the path the upstream receives. - Matrix rows C1-1..C1-7 (sidecar, 41 -> 48) and PT-18, PT-19 (passthrough, 16 -> 18). Known failing at this commit, on purpose (the fix is the next commit): the tests reproduce three findings: (1) canonical_host accepts a hex last label such as 127.0.0.0x1, which url reads as IPv4; (2) path_ambiguous accepts ..;x dot segments and %255c, %2500, %25%32%66; (3) paths with non-ASCII bytes, braces or a double quote are matched raw but forwarded percent-encoded. Run on macmini: cargo test -p ap-core --tests fails generated_paths, generated_hosts. --- .github/workflows/fuzz.yml | 59 ++ crates/ap-core/Cargo.toml | 3 + crates/ap-core/tests/canon_differential.rs | 223 ++++++++ crates/ap-core/tests/canon_regression.rs | 518 ++++++++++++++++++ crates/ap-core/tests/common/invariants.rs | 214 ++++++++ crates/ap-core/tests/common/mod.rs | 2 + crates/ap-proxy/src/canon_diff_tests.rs | 117 ++++ crates/ap-proxy/src/lib.rs | 2 + crates/ap-proxy/tests/matrix.rs | 2 +- crates/ap-proxy/tests/matrix_passthrough.rs | 2 +- fuzz/.gitignore | 3 + fuzz/Cargo.toml | 46 ++ fuzz/corpus/canon_headers/cl-dup | 2 + fuzz/corpus/canon_headers/cl-te | 2 + fuzz/corpus/canon_headers/conn-nominates-key | 1 + fuzz/corpus/canon_headers/crlf-value | 2 + fuzz/corpus/canon_headers/key-dup | 2 + fuzz/corpus/canon_headers/key-ok | 1 + fuzz/corpus/canon_headers/obs-fold | 2 + fuzz/corpus/canon_headers/surrogate-dup | 2 + fuzz/corpus/canon_headers/surrogate-ok | 1 + fuzz/corpus/canon_headers/te-list | 1 + fuzz/corpus/canon_host/bad-punycode | 1 + fuzz/corpus/canon_host/decimal | 1 + fuzz/corpus/canon_host/hex-tail | 1 + fuzz/corpus/canon_host/idn-unicode | 1 + fuzz/corpus/canon_host/ipv6-mapped | 1 + fuzz/corpus/canon_host/mixed-case | 1 + fuzz/corpus/canon_host/octal | 1 + fuzz/corpus/canon_host/ok | 1 + fuzz/corpus/canon_host/punycode | 1 + fuzz/corpus/canon_host/trailing-dot | 1 + fuzz/corpus/canon_origin/absolute-form | Bin 0 -> 39 bytes fuzz/corpus/canon_origin/h2-absolute | 2 + fuzz/corpus/canon_origin/h2-mismatch | 2 + fuzz/corpus/canon_origin/no-host | Bin 0 -> 3 bytes fuzz/corpus/canon_origin/ok | Bin 0 -> 21 bytes fuzz/corpus/canon_origin/trailing-dot | Bin 0 -> 19 bytes fuzz/corpus/canon_origin/two-hosts | Bin 0 -> 33 bytes fuzz/corpus/canon_origin/userinfo | Bin 0 -> 20 bytes fuzz/corpus/canon_path/dot-param | 1 + fuzz/corpus/canon_path/double-encoded-slash | 1 + fuzz/corpus/canon_path/empty-key | 1 + fuzz/corpus/canon_path/empty-segment | 1 + fuzz/corpus/canon_path/encoded-backslash | 1 + fuzz/corpus/canon_path/forwarder-reencodes | 1 + fuzz/corpus/canon_path/key-repeated | 1 + fuzz/corpus/canon_path/key-reserved | 1 + fuzz/corpus/canon_path/non-ascii | 1 + fuzz/corpus/canon_path/ok-no-rest | 1 + fuzz/corpus/canon_path/ok-plain | 1 + fuzz/corpus/canon_path/param-plain | 1 + .../canon_path/triple-encoded-backslash | 1 + fuzz/fuzz_targets/canon_headers.rs | 22 + fuzz/fuzz_targets/canon_host.rs | 12 + fuzz/fuzz_targets/canon_origin.rs | 20 + fuzz/fuzz_targets/canon_path.rs | 12 + tests/matrix/matrix.py | 178 +++++- tests/matrix/passthrough.py | 86 ++- 59 files changed, 1558 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/fuzz.yml create mode 100644 crates/ap-core/tests/canon_differential.rs create mode 100644 crates/ap-core/tests/canon_regression.rs create mode 100644 crates/ap-core/tests/common/invariants.rs create mode 100644 crates/ap-core/tests/common/mod.rs create mode 100644 crates/ap-proxy/src/canon_diff_tests.rs create mode 100644 fuzz/.gitignore create mode 100644 fuzz/Cargo.toml create mode 100644 fuzz/corpus/canon_headers/cl-dup create mode 100644 fuzz/corpus/canon_headers/cl-te create mode 100644 fuzz/corpus/canon_headers/conn-nominates-key create mode 100644 fuzz/corpus/canon_headers/crlf-value create mode 100644 fuzz/corpus/canon_headers/key-dup create mode 100644 fuzz/corpus/canon_headers/key-ok create mode 100644 fuzz/corpus/canon_headers/obs-fold create mode 100644 fuzz/corpus/canon_headers/surrogate-dup create mode 100644 fuzz/corpus/canon_headers/surrogate-ok create mode 100644 fuzz/corpus/canon_headers/te-list create mode 100644 fuzz/corpus/canon_host/bad-punycode create mode 100644 fuzz/corpus/canon_host/decimal create mode 100644 fuzz/corpus/canon_host/hex-tail create mode 100644 fuzz/corpus/canon_host/idn-unicode create mode 100644 fuzz/corpus/canon_host/ipv6-mapped create mode 100644 fuzz/corpus/canon_host/mixed-case create mode 100644 fuzz/corpus/canon_host/octal create mode 100644 fuzz/corpus/canon_host/ok create mode 100644 fuzz/corpus/canon_host/punycode create mode 100644 fuzz/corpus/canon_host/trailing-dot create mode 100644 fuzz/corpus/canon_origin/absolute-form create mode 100644 fuzz/corpus/canon_origin/h2-absolute create mode 100644 fuzz/corpus/canon_origin/h2-mismatch create mode 100644 fuzz/corpus/canon_origin/no-host create mode 100644 fuzz/corpus/canon_origin/ok create mode 100644 fuzz/corpus/canon_origin/trailing-dot create mode 100644 fuzz/corpus/canon_origin/two-hosts create mode 100644 fuzz/corpus/canon_origin/userinfo create mode 100644 fuzz/corpus/canon_path/dot-param create mode 100644 fuzz/corpus/canon_path/double-encoded-slash create mode 100644 fuzz/corpus/canon_path/empty-key create mode 100644 fuzz/corpus/canon_path/empty-segment create mode 100644 fuzz/corpus/canon_path/encoded-backslash create mode 100644 fuzz/corpus/canon_path/forwarder-reencodes create mode 100644 fuzz/corpus/canon_path/key-repeated create mode 100644 fuzz/corpus/canon_path/key-reserved create mode 100644 fuzz/corpus/canon_path/non-ascii create mode 100644 fuzz/corpus/canon_path/ok-no-rest create mode 100644 fuzz/corpus/canon_path/ok-plain create mode 100644 fuzz/corpus/canon_path/param-plain create mode 100644 fuzz/corpus/canon_path/triple-encoded-backslash create mode 100644 fuzz/fuzz_targets/canon_headers.rs create mode 100644 fuzz/fuzz_targets/canon_host.rs create mode 100644 fuzz/fuzz_targets/canon_origin.rs create mode 100644 fuzz/fuzz_targets/canon_path.rs diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 0000000..9830a1e --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,59 @@ +name: fuzz + +# Bounded cargo-fuzz runs for request canonicalization (issue #19). The default `ci` workflow is +# manual only and never builds fuzz/; this one has its own triggers: +# - pull requests that touch canonicalization or the fuzz crate: a short run per target; +# - nightly: a longer run per target; +# - manual dispatch: the run time is an input. +on: + pull_request: + paths: + - crates/ap-core/src/canon.rs + - crates/ap-core/tests/common/** + - fuzz/** + - .github/workflows/fuzz.yml + schedule: + - cron: "17 3 * * *" + workflow_dispatch: + inputs: + seconds: + description: Seconds per fuzz target + default: "300" + +permissions: + contents: read + +jobs: + fuzz: + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + target: [canon_path, canon_host, canon_origin, canon_headers] + env: + SECONDS_PER_TARGET: ${{ github.event_name == 'pull_request' && '45' || github.event.inputs.seconds || '300' }} + steps: + - uses: actions/checkout@v4 + + - uses: dtolnay/rust-toolchain@nightly + + - name: Install cargo-fuzz + run: cargo install cargo-fuzz --locked --version 0.13.2 + + - name: Fuzz ${{ matrix.target }} for a bounded time + working-directory: fuzz + shell: bash + run: | + cargo +nightly fuzz run ${{ matrix.target }} -- \ + -max_total_time="$SECONDS_PER_TARGET" -timeout=10 -rss_limit_mb=2048 -max_len=4096 \ + 2>&1 | tee fuzz.log + # libFuzzer exits non-zero on a crash; the summary line is the evidence either way. + grep -E "^#[0-9]+.*(DONE|pulse)" fuzz.log | tail -1 || true + + - name: Upload crash artifacts + if: failure() + uses: actions/upload-artifact@v4 + with: + name: fuzz-artifacts-${{ matrix.target }} + path: fuzz/artifacts/${{ matrix.target }} diff --git a/crates/ap-core/Cargo.toml b/crates/ap-core/Cargo.toml index cfbf2db..a0ab4fc 100644 --- a/crates/ap-core/Cargo.toml +++ b/crates/ap-core/Cargo.toml @@ -10,3 +10,6 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "0.8" http = "1" + +[dev-dependencies] +url = "2" diff --git a/crates/ap-core/tests/canon_differential.rs b/crates/ap-core/tests/canon_differential.rs new file mode 100644 index 0000000..9be42fa --- /dev/null +++ b/crates/ap-core/tests/canon_differential.rs @@ -0,0 +1,223 @@ +//! Differential test for request canonicalization. +//! +//! A fixed-seed generator produces paths, hosts and headers from the classes in issue #19. Each +//! input goes through the shared invariants (`common/invariants.rs`), which compare our verdict +//! with the `http` and `url` parsers and check that an accepted input is never rewritten. The seed +//! is fixed, so a failure reproduces; the same invariants run under cargo-fuzz for open-ended input. + +mod common; +use common::invariants::*; + +/// xorshift64*: deterministic, no dependency. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + fn pick<'a>(&mut self, xs: &[&'a str]) -> &'a str { + xs[self.below(xs.len())] + } +} + +const SEED: u64 = 0x19_C0FF_EE_5EED; +const KEY: &str = "apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +const PATH_ATOMS: &[&str] = &[ + "a", "v1", "echo", "x", "..", ".", "...", "%2e", "%2E", "%2f", "%2F", "%5c", "%5C", "%00", + "%25", "%252f", "%252e", "%2525", "%", "%zz", "%e", ";", "a;b", "..;", ".;", "..;x", ";..", + "\\", "{", "}", "|", "^", "\"", "<", ">", "`", "[", "]", "@", ":", "*", "~", "é", "ap", "apk_", + "?", "#", "+", "=", "&", "!", "$", "'", "(", ")", ",", "-", "_", +]; +const SEPS: &[&str] = &["/", "/", "/", "", "//", "/"]; + +fn gen_path(r: &mut Rng) -> String { + let mut p = String::new(); + for _ in 0..(1 + r.below(6)) { + p.push_str(r.pick(SEPS)); + p.push_str(r.pick(PATH_ATOMS)); + } + p +} + +fn gen_ap_path(r: &mut Rng) -> String { + let key = match r.below(6) { + 0 => String::new(), + 1 => KEY.to_uppercase(), + 2 => KEY[..KEY.len() - 1].to_string(), + 3 => format!("{KEY}{}", r.pick(PATH_ATOMS)), + _ => KEY.to_string(), + }; + let route = r.pick(&["up", "", "UP", "up;x", "up%2f", "..", "ap", "a b", "r-1"]); + format!("/ap/{key}/{route}{}", gen_path(r)) +} + +#[test] +fn generated_paths_hold_the_invariants() { + let mut r = Rng(SEED); + let mut accepted = 0; + for _ in 0..40_000 { + let p = if r.below(2) == 0 { + gen_path(&mut r) + } else { + gen_ap_path(&mut r) + }; + check_path(&p); + if !ap_core::canon::path_ambiguous(&p) { + accepted += 1; + } + } + assert!(accepted > 1000, "generator never reached the accept side"); +} + +const HOST_ATOMS: &[&str] = &[ + "api", + "example", + "com", + "EXAMPLE", + "xn--e1afmkfd", + "xn--a-", + "xn--", + "xn--zz", + "127", + "0", + "1", + "0x7f", + "0177", + "300", + "2130706433", + "-a", + "a-", + "a_b", + "é", + "a", + "[::1]", + "::1", + "@", + "u@h", + ":443", + "", + " ", + "a b", + "ı", + "ß", + "İ", + "k", + "K", +]; + +fn gen_host(r: &mut Rng) -> String { + let n = 1 + r.below(4); + let labels: Vec<&str> = (0..n).map(|_| r.pick(HOST_ATOMS)).collect(); + let mut h = labels.join("."); + match r.below(8) { + 0 => h.push('.'), + 1 => h.push_str(":443"), + _ => {} + } + h +} + +#[test] +fn generated_hosts_hold_the_invariants() { + let mut r = Rng(SEED ^ 1); + let mut accepted = 0; + for _ in 0..40_000 { + let h = gen_host(&mut r); + check_host(&h); + if ap_core::canon::canonical_host(&h).is_ok() { + accepted += 1; + } + } + assert!(accepted > 100, "generator never reached the accept side"); +} + +#[test] +fn generated_request_targets_hold_the_invariants() { + let mut r = Rng(SEED ^ 2); + let expected = "127.0.0.1:8443"; + for _ in 0..20_000 { + let target = match r.below(5) { + 0 => format!( + "http://{}{}", + r.pick(&[expected, "evil.test", "u@127.0.0.1:8443"]), + gen_path(&mut r) + ), + 1 => format!("https://{}/x", r.pick(&[expected, "EVIL.test"])), + 2 => gen_path(&mut r), + 3 => format!("//{expected}/x"), + _ => expected.to_string(), + }; + let n = r.below(4); + let hosts: Vec> = (0..n) + .map(|_| { + r.pick(&[ + expected, + "evil.test", + "127.0.0.1:8443 ", + "127.0.0.1:8443,evil.test", + "u@127.0.0.1:8443", + "127.0.0.1.:8443", + "[::ffff:127.0.0.1]:8443", + ]) + .as_bytes() + .to_vec() + }) + .collect(); + check_origin(&target, &hosts, r.below(2) == 0, expected); + } +} + +const HDR_NAMES: &[&str] = &[ + "x-ap-caller-key", + "authorization", + "content-length", + "transfer-encoding", + "connection", + "host", + "X-AP-Caller-Key", + "Authorization", + "Content-Length", + "x-other", +]; + +fn gen_value(r: &mut Rng) -> Vec { + let sur = format!("Bearer aps_{}", &KEY[4..]); + let v: Vec = match r.below(14) { + 0 => KEY.as_bytes().to_vec(), + 1 => sur.into_bytes(), + 2 => b"5".to_vec(), + 3 => b"5, 5".to_vec(), + 4 => b"+5".to_vec(), + 5 => b"chunked".to_vec(), + 6 => b"CHUNKED".to_vec(), + 7 => b"chunked, chunked".to_vec(), + 8 => b"identity".to_vec(), + 9 => b"close, X-AP-Caller-Key".to_vec(), + 10 => b"keep-alive, Host".to_vec(), + 11 => b"a\r\nX-Injected: 1".to_vec(), + 12 => b"a\r\n folded".to_vec(), + _ => vec![0xff, b'a'], + }; + v +} + +#[test] +fn generated_headers_hold_the_invariants() { + let mut r = Rng(SEED ^ 3); + for _ in 0..30_000 { + let n = r.below(6); + let pairs: Vec<(Vec, Vec)> = (0..n) + .map(|_| (r.pick(HDR_NAMES).as_bytes().to_vec(), gen_value(&mut r))) + .collect(); + check_headers(&pairs, "x-ap-caller-key"); + } +} diff --git a/crates/ap-core/tests/canon_regression.rs b/crates/ap-core/tests/canon_regression.rs new file mode 100644 index 0000000..5f6bc70 --- /dev/null +++ b/crates/ap-core/tests/canon_regression.rs @@ -0,0 +1,518 @@ +//! Table-driven regression cases for the classes listed in issue #19. Each table names the class +//! and the input; the matrix rows in `tests/matrix` repeat the wire-level ones end to end. + +use ap_core::canon::*; +use ap_core::error::Code; +use http::{HeaderMap, HeaderName, HeaderValue, Uri, Version}; +use std::str::FromStr; + +const KEY: &str = "apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; +const AUTH: &str = "127.0.0.1:8443"; + +fn hm(pairs: &[(&str, &str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append( + HeaderName::from_str(k).unwrap(), + HeaderValue::from_str(v).unwrap(), + ); + } + h +} + +fn ambiguous_all(class: &str, paths: &[&str]) { + for p in paths { + assert!(path_ambiguous(p), "{class}: {p:?} must be refused"); + } +} + +#[test] +fn path_encoding_classes_are_refused() { + ambiguous_all( + "double percent-encoding", + &[ + "/v1/%252f", + "/v1/%252F", + "/v1/%252e%252e/x", + "/v1/%252E", + "/v1/%25%32%66", + "/v1/%25252f", + ], + ); + ambiguous_all( + "encoded slash", + &["/v1%2fx", "/v1%2Fx", "/v1/a%2f..%2fb", "/%2f"], + ); + ambiguous_all( + "encoded and literal backslash", + &["/v1%5cx", "/v1%5Cx", "/v1\\x", "/v1/..\\x", "/\\"], + ); + ambiguous_all( + "encoded dot and NUL", + &[ + "/v1/%2e", + "/v1/%2E%2e/x", + "/v1/.%2e/x", + "/v1/%00", + "/v1/a%00b", + ], + ); + ambiguous_all( + "dot segments", + &["/v1/..", "/v1/.", "/v1/a/../b", "/./x", "/v1/a/./b", "/.."], + ); + ambiguous_all( + "triple and partial double encoding", + &[ + "/v1/%255c", + "/v1/%255C", + "/v1/%2500", + "/v1/%25%32%66", + "/v1/%25%32%65", + ], + ); + ambiguous_all( + "bytes the forwarder would percent-encode (matched is not what is sent)", + &[ + "/v1/{", + "/v1/}", + "/v1/\"", + "/v1/<", + "/v1/>", + "/v1/`", + "/v1/é", + "/v1/\u{7f}", + ], + ); + ambiguous_all("empty interior segment", &["//x", "/v1//x", "/a///b"]); +} + +#[test] +fn ordinary_paths_pass_unchanged() { + for p in [ + "/", + "/v1/messages", + "/v1/", + "/a.b/c-d_e~f", + "/v1/a..b", + "/v1/...", + "/v1/.hidden", + "/v1/%41", + "/v1/100%25", + "/v1/a%20b", + "/v1/%e2%82%ac", + "/v1/%zz", + "/v1/%", + ] { + assert!(!path_ambiguous(p), "{p:?} must pass"); + } +} + +#[test] +fn path_parameters_on_dot_segments_are_refused() { + // A servlet container reads `..;x` as `..`. A prefix grant on `/v1/` would then cover + // `/v1/..;/admin` at the policy while the upstream resolves it to `/admin`. + ambiguous_all( + "dot segment carrying a path parameter", + &[ + "/v1/..;/admin", + "/v1/..;x/admin", + "/v1/.;/x", + "/v1/.;x", + "/v1/..;", + "/..;/x", + "/v1/..;a=b;c/x", + ], + ); +} + +#[test] +fn ordinary_path_parameters_pass_and_are_not_rewritten() { + // `;` on a real segment is data. It is forwarded byte for byte, never stripped. + for p in ["/v1/a;b", "/v1/a;b=c/d", "/v1/;x", "/v1/a;", "/v1/;;"] { + assert!(!path_ambiguous(p), "{p:?} must pass"); + let full = format!("/ap/{KEY}/up{p}"); + let ap = parse_ap_path(&full).unwrap(); + assert_eq!(ap.route_path, p, "route path must keep `;` bytes"); + } +} + +#[test] +fn caller_key_path_form_table() { + let k = KEY; + let upper = KEY.to_uppercase(); + let short = &KEY[..KEY.len() - 1]; + let ok: Vec<(String, &str, String)> = vec![ + (format!("/ap/{k}/up/v1/x"), "up", "/v1/x".into()), + (format!("/ap/{k}/up"), "up", "/".into()), + (format!("/ap/{k}/up/"), "up", "/".into()), + // the key and prefix appearing again later are data, not a second parse + (format!("/ap/{k}/up/ap/{k}/x"), "up", format!("/ap/{k}/x")), + (format!("/ap/{k}/up/ap/up/x"), "up", "/ap/up/x".into()), + (format!("/ap/{k}/ap/{k}/x"), "ap", format!("/{k}/x")), + // route names and rest are returned raw + (format!("/ap/{k}/up;x/y"), "up;x", "/y".into()), + (format!("/ap/{k}/UP/y"), "UP", "/y".into()), + ]; + for (path, route, rest) in &ok { + let ap = parse_ap_path(path).unwrap_or_else(|c| panic!("{path}: {c:?}")); + assert_eq!( + (ap.caller_key, ap.route, ap.route_path.as_str()), + (k, *route, rest.as_str()) + ); + } + let bad_key: Vec = vec![ + "/ap/".into(), + "/ap//up/x".into(), + "/ap/up/x".into(), + format!("/ap/{k}"), + format!("/ap/{upper}/up/x"), + format!("/ap/{short}/up/x"), + format!("/ap/{k}0/up/x"), + format!("/ap/{k}%2f/up/x"), + format!("/ap/{k}?/up/x"), + format!("/ap/{k}#/up/x"), + format!("/ap/{k};x/up/x"), + format!("/ap/{k} /up/x"), + format!("/ap/ {k}/up/x"), + format!("/ap/{}/up/x", k[..4].to_string() + &"g".repeat(64)), + format!("/ap/apk_{}/up/x", "é".repeat(32)), + format!("/AP/{k}/up/x"), + format!("/ap{k}/up/x"), + format!("//ap/{k}/up/x"), + format!("/x/ap/{k}/up/x"), + "/ap".into(), + String::new(), + ]; + for p in &bad_key { + assert_eq!(parse_ap_path(p), Err(Code::CallerRejected), "{p:?}"); + } + assert_eq!(parse_ap_path(&format!("/ap/{k}/")), Err(Code::RouteUnknown)); + assert_eq!( + parse_ap_path(&format!("/ap/{k}//x")), + Err(Code::RouteUnknown) + ); +} + +#[test] +fn over_long_segments_are_not_truncated_or_panicking() { + let long = "a".repeat(100_000); + let p = format!("/ap/{KEY}/up/{long}/{long}"); + let ap = parse_ap_path(&p).unwrap(); + assert_eq!(ap.route_path.len(), long.len() * 2 + 2); + assert!(!path_ambiguous(&p)); + let long_route = format!("/ap/{KEY}/{long}/x"); + assert_eq!(parse_ap_path(&long_route).unwrap().route, long); + // The header-mode splitter caps the route name at 32 bytes and refuses past it. + assert_eq!( + parse_route_path(&format!("/{}/x", "a".repeat(33))), + Err(Code::RouteUnknown) + ); + assert!(parse_route_path(&format!("/{}/x", "a".repeat(32))).is_ok()); + // A refusal still wins when the over-long input also carries an ambiguity at the very end. + assert!(path_ambiguous(&format!("/{long}/.."))); +} + +#[test] +fn host_name_classes() { + let ok = [ + "api.example.com", + "xn--e1afmkfd.xn--p1ai", + "a.b", + "1.1.1.1.example.com", + &format!("{}.com", "a".repeat(63)), + ]; + for h in ok { + assert!(canonical_host(h).is_ok(), "{h}"); + } + let bad: &[(&str, &str)] = &[ + ("mixed case", "Api.Example.com"), + ("upper", "API.EXAMPLE.COM"), + ("trailing dot", "api.example.com."), + ("double trailing dot", "api.example.com.."), + ("leading dot", ".example.com"), + ("empty label", "a..example.com"), + ("unicode", "bücher.example"), + ("cyrillic homoglyph", "ex\u{0430}mple.com"), + ("fullwidth", "example.com"), + ("dotless i", "ıdentity.example.com"), + ("sharp s", "straße.example"), + ("decomposed", "u\u{0308}ber.example"), + ("ideographic full stop", "example。com"), + ("zero width", "exa\u{200b}mple.com"), + ("space", "exa mple.com"), + ("underscore", "a_b.example.com"), + ("userinfo", "u@example.com"), + ("port", "example.com:443"), + ("path", "example.com/x"), + ("percent", "exa%6dple.com"), + ("label 64", &format!("{}.com", "a".repeat(64))), + ("name over 253", &format!("{}.com", "a.".repeat(130))), + ("empty", ""), + ("single label", "localhost"), + ("leading hyphen", "-a.example.com"), + ("trailing hyphen", "a-.example.com"), + ]; + for (class, h) in bad { + assert!(canonical_host(h).is_err(), "{class}: {h:?}"); + } +} + +#[test] +fn ip_literal_classes() { + let bad = [ + "127.0.0.1", + "0.0.0.0", + "255.255.255.255", + "127.1", + "127.0.1", + "0x7f.0.0.1", + "0x7f000001", + "0177.0.0.1", + "0177.0.0.01", + "0300.0250.0.1", + "017700000001", + "2130706433", + "4294967295", + "1.1.1.1.", + "::1", + "::", + "[::1]", + "[::]", + "::ffff:127.0.0.1", + "[::ffff:127.0.0.1]", + "[::ffff:7f00:1]", + "fe80::1%25eth0", + "[fe80::1%25eth0]", + "0:0:0:0:0:0:0:1", + "1.2.3", + "1.2.3.4.5", + "example.1", + "example.0x1", + "a.b.0177", + ]; + for h in bad { + assert!(canonical_host(h).is_err(), "{h}"); + } +} + +#[test] +fn host_header_and_request_target_table() { + let uri = |s: &str| Uri::from_str(s).unwrap(); + let h1 = Version::HTTP_11; + let h2 = Version::HTTP_2; + let good = hm(&[("host", AUTH)]); + assert_eq!(check_origin_form(&uri("/x"), &good, h1, AUTH), Ok(())); + + let host = |v: &str| hm(&[("host", v)]); + for (class, v) in [ + ("mixed case", "LOCALHOST:8443"), + ("trailing dot", "127.0.0.1.:8443"), + ("no port", "127.0.0.1"), + ("wrong port", "127.0.0.1:8444"), + ("userinfo", "u@127.0.0.1:8443"), + ("userinfo suffix", "127.0.0.1:8443@evil.test"), + ("comma list", "127.0.0.1:8443,evil.test"), + ("trailing space", "127.0.0.1:8443 "), + ("leading space", " 127.0.0.1:8443"), + ("IPv6 mapped", "[::ffff:127.0.0.1]:8443"), + ("decimal IP", "2130706433:8443"), + ("octal IP", "0177.0.0.1:8443"), + ("hex IP", "0x7f.0.0.1:8443"), + ("IPv6 loopback", "[::1]:8443"), + ("punycode", "xn--e1afmkfd.xn--p1ai"), + ("empty", ""), + ] { + assert!( + check_origin_form(&uri("/x"), &host(v), h1, AUTH).is_err(), + "{class}: {v:?}" + ); + } + // Two Host headers, even equal, are refused: which one is read depends on the reader. + let two = hm(&[("host", AUTH), ("host", AUTH)]); + assert_eq!( + check_origin_form(&uri("/x"), &two, h1, AUTH), + Err(Code::HostRejected) + ); + assert_eq!( + check_origin_form(&uri("/x"), &two, h2, AUTH), + Err(Code::HostRejected) + ); + // No Host on HTTP/1. + assert_eq!( + check_origin_form(&uri("/x"), &HeaderMap::new(), h1, AUTH), + Err(Code::HostRejected) + ); + // Absolute form: refused over HTTP/1 even when it matches Host exactly. + for t in [ + format!("http://{AUTH}/x"), + format!("https://{AUTH}/x"), + "http://evil.test/x".to_string(), + format!("http://u:p@{AUTH}/x"), + ] { + assert_eq!( + check_origin_form(&uri(&t), &good, h1, AUTH), + Err(Code::AbsoluteForm), + "{t}" + ); + } + // Absolute form vs Host mismatch over HTTP/2: the authority must equal the route. + assert_eq!( + check_origin_form(&uri("https://evil.test/x"), &good, h2, AUTH), + Err(Code::HostRejected) + ); + assert_eq!( + check_origin_form( + &uri(&format!("https://{AUTH}/x")), + &host("evil.test"), + h2, + AUTH + ), + Err(Code::HostRejected) + ); + assert_eq!( + check_origin_form(&uri(&format!("https://{AUTH}/x")), &good, h2, AUTH), + Ok(()) + ); +} + +#[test] +fn unicode_and_idn_never_reach_the_matcher() { + // `http::Uri` refuses non-ASCII in a target and in an authority, so a Unicode form of a + // path or host cannot be normalised into a match: it never parses. + for t in [ + "/v1/é", + "/v1/\u{ff0e}\u{ff0e}/x", + "/v1/\u{2024}\u{2024}", + "/v1/\u{ff0f}x", + "/v1/e\u{301}", + ] { + // `http::Uri` accepts these bytes, so the refusal has to come from `path_ambiguous`: + // the forwarder would percent-encode them, and what was matched must be what is sent. + match Uri::from_str(t) { + Err(_) => {} + Ok(u) => assert!(path_ambiguous(u.path()), "{t:?} passes the path check"), + } + } + assert!(Uri::from_str("http://exämple.com/x").is_err()); + // Overlong UTF-8 for `.` and `/` is plain ASCII on the wire: opaque bytes, not a dot. + assert!(!path_ambiguous("/v1/%C0%AE%C0%AE/x")); + // Header values with obs-text are not valid UTF-8 text for our readers. + let h = { + let mut h = HeaderMap::new(); + h.append( + HeaderName::from_static("x-ap-caller-key"), + HeaderValue::from_bytes(b"apk_\xff").unwrap(), + ); + h + }; + assert_eq!( + caller_key_from_header(&h, "x-ap-caller-key"), + Err(Code::CallerRejected) + ); +} + +#[test] +fn crlf_and_control_bytes_cannot_enter_a_header_value() { + for v in [ + &b"a\r\nX-Injected: 1"[..], + b"a\nb", + b"a\rb", + b"a\r\n folded", + b"a\r\n\tfolded", + b"\0", + b"a\0b", + b"a\x7fb", + b"a\x01b", + ] { + assert!(HeaderValue::from_bytes(v).is_err(), "{v:?}"); + } + assert!( + HeaderValue::from_bytes(b"a\tb").is_ok(), + "HTAB is legal inside a value" + ); + for n in [&b"x y"[..], b"x\r\ny", b"x:y", b"", b"x\0"] { + assert!(HeaderName::from_bytes(n).is_err(), "{n:?}"); + } +} + +#[test] +fn duplicate_and_conflicting_headers_table() { + let k = "x-ap-caller-key"; + // caller key + assert_eq!( + caller_key_from_header(&hm(&[(k, KEY)]), k), + Ok(KEY.to_string()) + ); + for h in [ + hm(&[(k, KEY), (k, KEY)]), + hm(&[(k, KEY), ("X-AP-Caller-Key", KEY)]), + hm(&[(k, &KEY.to_uppercase())]), + hm(&[(k, &format!("{KEY} "))]), + hm(&[(k, &format!("{KEY},{KEY}"))]), + HeaderMap::new(), + ] { + assert_eq!( + caller_key_from_header(&h, k), + Err(Code::CallerRejected), + "{h:?}" + ); + } + // surrogate + let sur = format!("Bearer aps_{}", &KEY[4..]); + assert!(surrogate_from_headers(&hm(&[("authorization", &sur)]), "authorization").is_ok()); + assert_eq!( + surrogate_from_headers( + &hm(&[("authorization", &sur), ("authorization", &sur)]), + "authorization" + ), + Err(Code::SurrogateAmbiguous) + ); + for bad in [ + sur.to_lowercase(), + sur.replace("Bearer", "bearer"), + format!("{sur} "), + format!(" {sur}"), + format!("{sur}, {sur}"), + ] { + assert_eq!( + surrogate_from_headers(&hm(&[("authorization", &bad)]), "authorization"), + Err(Code::SurrogateMalformed), + "{bad:?}" + ); + } + // framing + let refused: &[&[(&str, &str)]] = &[ + &[("content-length", "5"), ("content-length", "5")], + &[("content-length", "5, 5")], + &[("content-length", "+5")], + &[("content-length", "5 ")], + &[("content-length", "0x5")], + &[("content-length", "")], + &[("content-length", "5"), ("transfer-encoding", "chunked")], + &[ + ("transfer-encoding", "chunked"), + ("transfer-encoding", "chunked"), + ], + &[("transfer-encoding", "chunked, chunked")], + &[("transfer-encoding", "gzip, chunked")], + &[("transfer-encoding", "identity")], + &[("connection", "close, Content-Length")], + &[("connection", "Transfer-Encoding")], + &[("connection", "x-ap-caller-key")], + &[("connection", "host")], + &[("connection", "authorization")], + ]; + for h in refused { + assert!(framing_refused(&hm(h), k), "{h:?}"); + } + let fine: &[&[(&str, &str)]] = &[ + &[], + &[("content-length", "5")], + &[("transfer-encoding", "CHUNKED")], + &[("connection", "keep-alive")], + ]; + for h in fine { + assert!(!framing_refused(&hm(h), k), "{h:?}"); + } +} diff --git a/crates/ap-core/tests/common/invariants.rs b/crates/ap-core/tests/common/invariants.rs new file mode 100644 index 0000000..12b681a --- /dev/null +++ b/crates/ap-core/tests/common/invariants.rs @@ -0,0 +1,214 @@ +//! Invariant checks for request canonicalization. +//! +//! One source of truth for two callers: the deterministic differential test +//! (`tests/canon_differential.rs`) and the cargo-fuzz targets (`fuzz/fuzz_targets/*.rs`, which +//! include this file by path). Every function panics with the offending input when an +//! invariant breaks, so a fuzz crash and a test failure both name the input. +//! +//! The rules checked here are the ones in `canon.rs`: one pass before any decision, forward +//! exactly what was checked, refuse ambiguity instead of normalising it. +#![allow(dead_code)] + +use ap_core::canon::{ + caller_key_from_header, canonical_host, check_origin_form, framing_refused, is_caller_key, + parse_ap_path, parse_route_path, path_ambiguous, surrogate_from_headers, +}; +use ap_core::error::Code; +use http::{HeaderMap, HeaderName, HeaderValue, Uri, Version}; +use std::str::FromStr; + +/// The caller key and route split must be exact, and must agree with the header-mode splitter. +pub fn check_ap_path(p: &str) { + match parse_ap_path(p) { + Ok(ap) => { + assert!(is_caller_key(ap.caller_key), "key shape: {p:?}"); + assert!( + !ap.route.is_empty() && !ap.route.contains('/'), + "route shape: {p:?}" + ); + assert!(ap.route_path.starts_with('/'), "route_path: {p:?}"); + // The split loses nothing and invents nothing: the pieces rebuild the input, except + // that `/ap//` and `/ap///` both give route_path `/`. + let tail = if ap.route_path == "/" { + "" + } else { + ap.route_path.as_str() + }; + let rebuilt = format!("/ap/{}/{}{}", ap.caller_key, ap.route, tail); + assert!( + p == rebuilt || p == format!("{rebuilt}/"), + "split does not rebuild the input: {p:?} -> {ap:?}" + ); + // Passthrough strips `/ap/` and splits the rest with `parse_route_path`. + let suffix = &p["/ap/".len() + ap.caller_key.len()..]; + if let Ok((route, rel)) = parse_route_path(suffix) { + assert_eq!( + route, ap.route, + "two splitters disagree on the route: {p:?}" + ); + assert_eq!( + rel, ap.route_path, + "two splitters disagree on the path: {p:?}" + ); + } + } + Err(code) => assert!( + matches!(code, Code::CallerRejected | Code::RouteUnknown), + "unexpected refusal {code:?} for {p:?}" + ), + } +} + +/// An accepted path must be one that the `http` crate and the WHATWG `url` crate (which the +/// forwarder builds the upstream URL with) both read as the same bytes. A parser that would +/// rewrite it (dot segments, backslash, percent-encoding of non-ASCII or of `{`, `}`, `"`) is a +/// parser that disagrees with the policy check, and what was matched is not what is sent. +pub fn check_path_against_parsers(p: &str) { + let Ok(uri) = Uri::from_str(p) else { return }; + // The pipeline matches `uri.path()`, never the raw target. + let path = uri.path(); + if path_ambiguous(path) { + return; + } + let Ok(url) = url::Url::parse(&format!("https://example.test{path}")) else { + panic!("url refuses an accepted path: {path:?}"); + }; + assert_eq!( + url.path(), + path, + "url::Url rewrote a path that path_ambiguous accepted" + ); +} + +/// Everything about a request path that must hold for any string. +pub fn check_path(p: &str) { + check_ap_path(p); + check_path_against_parsers(p); +} + +/// An accepted host is already the canonical spelling: the `url` crate's host parser returns +/// the identical domain, never an IP, never a rewritten name (it may refuse a malformed `xn--` +/// label, see below). +pub fn check_host(h: &str) { + if canonical_host(h).is_err() { + return; + } + assert!(h.is_ascii(), "non-ASCII host accepted: {h:?}"); + assert!( + h.parse::().is_err(), + "IP literal accepted: {h:?}" + ); + match url::Host::parse(h) { + Ok(url::Host::Domain(d)) => assert_eq!(d, h, "url rewrote an accepted host: {h:?}"), + // A malformed `xn--` label is not a valid IDNA name. `canonical_host` keeps it byte for + // byte and the egress allowlist compares bytes, so nothing is rewritten; the `url` crate + // refuses it. That is the one accepted disagreement. + Err(_) if h.split('.').any(|l| l.starts_with("xn--")) => {} + other => panic!("url reads accepted host {h:?} as {other:?}"), + } + let auth = http::uri::Authority::from_str(h).expect("authority"); + assert_eq!(auth.host(), h, "http::Authority disagrees on host {h:?}"); + assert!(auth.port().is_none(), "port in accepted host {h:?}"); +} + +/// Build a header map from raw pairs. Pairs that `http` itself refuses are dropped, which is +/// what the wire parser does before our code runs. +pub fn header_map(pairs: &[(Vec, Vec)]) -> HeaderMap { + let mut m = HeaderMap::new(); + for (k, v) in pairs { + if let (Ok(k), Ok(v)) = (HeaderName::from_bytes(k), HeaderValue::from_bytes(v)) { + m.append(k, v); + } + } + m +} + +/// Caller-key, surrogate and framing decisions over arbitrary headers. +pub fn check_headers(pairs: &[(Vec, Vec)], key_header: &str) { + let h = header_map(pairs); + + if let Ok(k) = caller_key_from_header(&h, key_header) { + let vals: Vec<_> = h.get_all(key_header).iter().collect(); + assert_eq!(vals.len(), 1, "caller key accepted from several values"); + assert_eq!(vals[0].as_bytes(), k.as_bytes()); + assert!(is_caller_key(&k)); + } + + if let Ok(s) = surrogate_from_headers(&h, "authorization") { + let vals: Vec<_> = h.get_all("authorization").iter().collect(); + assert_eq!(vals.len(), 1, "surrogate accepted from several values"); + assert_eq!(vals[0].as_bytes(), format!("Bearer {s}").as_bytes()); + } + + if !framing_refused(&h, key_header) { + let cl: Vec<_> = h.get_all("content-length").iter().collect(); + let te: Vec<_> = h.get_all("transfer-encoding").iter().collect(); + assert!(cl.is_empty() || te.is_empty(), "CL with TE accepted"); + assert!(cl.len() <= 1, "several Content-Length accepted"); + if let Some(v) = cl.first() { + assert!( + !v.as_bytes().is_empty() && v.as_bytes().iter().all(u8::is_ascii_digit), + "non-digit Content-Length accepted: {v:?}" + ); + } + if !te.is_empty() { + assert!( + te.len() == 1 && te[0].as_bytes().eq_ignore_ascii_case(b"chunked"), + "Transfer-Encoding other than one chunked accepted" + ); + } + for v in h.get_all("connection") { + let s = v.to_str().expect("non-UTF-8 Connection accepted"); + for t in s.split(',') { + let t = t.trim().to_ascii_lowercase(); + assert!( + !matches!( + t.as_str(), + "content-length" | "transfer-encoding" | "host" | "authorization" + ) && t != key_header, + "Connection nominates {t}" + ); + } + } + } +} + +/// The request target and Host check. When it accepts, the Host that was compared is the Host +/// that the rest of the pipeline sees: one value, byte-identical to the route authority. +pub fn check_origin(target: &str, hosts: &[Vec], http2: bool, expected: &str) { + let Ok(uri) = Uri::from_str(target) else { + return; + }; + let mut h = HeaderMap::new(); + for v in hosts { + if let Ok(v) = HeaderValue::from_bytes(v) { + h.append(http::header::HOST, v); + } + } + let version = if http2 { + Version::HTTP_2 + } else { + Version::HTTP_11 + }; + if check_origin_form(&uri, &h, version, expected).is_err() { + return; + } + let vals: Vec<_> = h.get_all(http::header::HOST).iter().collect(); + assert!(vals.len() <= 1, "several Host values accepted"); + for v in &vals { + assert_eq!(v.as_bytes(), expected.as_bytes(), "Host differs from route"); + } + match uri.authority() { + Some(a) => { + assert!(http2, "absolute form accepted over HTTP/1"); + assert_eq!(a.as_str(), expected, "URI authority differs from route"); + } + None => { + assert!(uri.scheme().is_none(), "scheme without authority accepted"); + if !http2 { + assert_eq!(vals.len(), 1, "HTTP/1 request accepted without a Host"); + } + } + } + assert!(!expected.contains('@')); +} diff --git a/crates/ap-core/tests/common/mod.rs b/crates/ap-core/tests/common/mod.rs new file mode 100644 index 0000000..a7719db --- /dev/null +++ b/crates/ap-core/tests/common/mod.rs @@ -0,0 +1,2 @@ +//! Shared test helpers. +pub mod invariants; diff --git a/crates/ap-proxy/src/canon_diff_tests.rs b/crates/ap-proxy/src/canon_diff_tests.rs new file mode 100644 index 0000000..fdaf9c1 --- /dev/null +++ b/crates/ap-proxy/src/canon_diff_tests.rs @@ -0,0 +1,117 @@ +//! Differential test for the sidecar pipeline: for every accepted request, the path that the +//! policy matched is byte-identical to the path the upstream received; every other request is +//! refused before anything is sent. Inputs come from a fixed-seed generator over the classes in +//! issue #19. The mock upstream is the one the other pipeline tests use. + +use std::sync::atomic::Ordering; + +use axum::body::{to_bytes, Body}; +use axum::extract::Request; + +use crate::pipeline::handle; +use crate::test_support::{ + register_session, start_upstream, Fixture, CAP, IDENTITY, LISTEN, ROUTE, +}; + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + fn pick<'a>(&mut self, xs: &[&'a str]) -> &'a str { + xs[self.below(xs.len())] + } +} + +const ATOMS: &[&str] = &[ + "a", "v1", "msg", "..", ".", "...", "%2e", "%2E", "%2f", "%5c", "%00", "%25", "%252f", "%255c", + "%2500", "%", "%zz", ";", "a;b", "..;", ".;x", "\\", "{", "}", "|", "^", "\"", "<", ">", "`", + "[", "]", "@", ":", "*", "~", "é", "\u{ff0e}", "%C3%A9", "%41", "+", "=", "&", "!", "$", "'", + "(", ")", ",", "-", "_", "ap", "up", "%20", " ", +]; +const SEPS: &[&str] = &["/", "/", "/", "", "//"]; + +fn gen(r: &mut Rng) -> String { + let mut p = String::new(); + for _ in 0..(1 + r.below(5)) { + p.push_str(r.pick(SEPS)); + p.push_str(r.pick(ATOMS)); + } + p +} + +#[tokio::test] +async fn matched_path_is_the_forwarded_path() { + let up = start_upstream().await; + let f = Fixture::new("canon-diff", &up); + let surrogate = register_session(&f.app, IDENTITY, "sess-1", 1); + let mut r = Rng(0x19_C0FF_EE_5EED); + let (mut forwarded, mut refused, mut unparsed) = (0, 0, 0); + let mut mismatches: Vec = Vec::new(); + + for i in 0..600 { + // `/echo2` makes the mock upstream answer with the request target it received. + let p = format!("{}/echo2", gen(&mut r)); + let again = match r.below(4) { + 0 => format!("/ap/{}/{ROUTE}", f.caller), + _ => String::new(), + }; + let target = format!("/ap/{}/{ROUTE}{again}{p}", f.caller); + let Ok(req) = Request::builder() + .method("GET") + .uri(&target) + .header("host", LISTEN) + .header("authorization", format!("Bearer {surrogate}")) + .body(Body::empty()) + else { + unparsed += 1; + continue; + }; + let hits_before = up.hits.load(Ordering::SeqCst); + let audit_before = f.audit_text().lines().count(); + let resp = handle(std::sync::Arc::clone(&f.app), req).await; + let status = resp.status(); + let body = to_bytes(resp.into_body(), 1 << 20).await.expect("body"); + if status != 200 { + refused += 1; + if status != 502 { + assert_eq!( + up.hits.load(Ordering::SeqCst), + hits_before, + "#{i} {target:?}: refused with {status} but upstream was contacted" + ); + } + continue; + } + forwarded += 1; + let seen: serde_json::Value = serde_json::from_slice(&body).expect("echo2 json"); + let got = seen["path"].as_str().expect("path").to_string(); + let want = format!("{again}{p}"); + let text = f.audit_text(); + let line = text.lines().nth(audit_before).expect("audit line"); + let rec: serde_json::Value = serde_json::from_str(line).expect("audit json"); + let matched = rec["path"].as_str().expect("audit path").to_string(); + if got != want || matched != want { + mismatches.push(format!( + "request {target:?}: policy matched {matched:?}, upstream got {got:?}" + )); + } + } + assert!( + mismatches.is_empty(), + "matched path differs from forwarded path:\n{}", + mismatches.join("\n") + ); + assert!(forwarded > 50, "too few accepted requests: {forwarded}"); + assert!(refused > 50, "too few refused requests: {refused}"); + eprintln!("canon diff: forwarded={forwarded} refused={refused} unparsed={unparsed} cap={CAP}"); +} diff --git a/crates/ap-proxy/src/lib.rs b/crates/ap-proxy/src/lib.rs index cf83ea2..ebc7790 100644 --- a/crates/ap-proxy/src/lib.rs +++ b/crates/ap-proxy/src/lib.rs @@ -32,6 +32,8 @@ use axum::Router; use audit_sink::AuditSink; use pipeline::App; +#[cfg(test)] +mod canon_diff_tests; #[cfg(test)] mod test_support; #[cfg(test)] diff --git a/crates/ap-proxy/tests/matrix.rs b/crates/ap-proxy/tests/matrix.rs index fec0b19..a9263b7 100644 --- a/crates/ap-proxy/tests/matrix.rs +++ b/crates/ap-proxy/tests/matrix.rs @@ -63,7 +63,7 @@ fn matrix() { "matrix reported a FAIL row" ); assert!( - stdout.contains("summary: 41 PASS of 41 rows"), + stdout.contains("summary: 48 PASS of 48 rows"), "not every registered row passed:\n{stdout}" ); } diff --git a/crates/ap-proxy/tests/matrix_passthrough.rs b/crates/ap-proxy/tests/matrix_passthrough.rs index 079aee1..29cb54d 100644 --- a/crates/ap-proxy/tests/matrix_passthrough.rs +++ b/crates/ap-proxy/tests/matrix_passthrough.rs @@ -11,7 +11,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; /// Rows registered in `tests/matrix/passthrough.py`. -const ROWS: usize = 16; +const ROWS: usize = 18; /// Directory holding the built binary. `CARGO_BIN_EXE_auth-proxy` is set by cargo for this package's /// binaries, so it holds up when cargo keeps test executables in a separate build directory. diff --git a/fuzz/.gitignore b/fuzz/.gitignore new file mode 100644 index 0000000..735ae0d --- /dev/null +++ b/fuzz/.gitignore @@ -0,0 +1,3 @@ +target +artifacts +coverage diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml new file mode 100644 index 0000000..1863d1f --- /dev/null +++ b/fuzz/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "auth-proxy-fuzz" +version = "0.0.0" +publish = false +edition = "2021" + +[package.metadata] +cargo-fuzz = true + +# Not a member of the root workspace: `cargo build --workspace` never sees this crate, and the +# nightly-only libFuzzer dependency stays out of the default build. +[workspace] + +[dependencies] +libfuzzer-sys = "0.4" +ap-core = { path = "../crates/ap-core" } +http = "1" +url = "2" + +[[bin]] +name = "canon_path" +path = "fuzz_targets/canon_path.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "canon_host" +path = "fuzz_targets/canon_host.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "canon_origin" +path = "fuzz_targets/canon_origin.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "canon_headers" +path = "fuzz_targets/canon_headers.rs" +test = false +doc = false +bench = false diff --git a/fuzz/corpus/canon_headers/cl-dup b/fuzz/corpus/canon_headers/cl-dup new file mode 100644 index 0000000..364d3f2 --- /dev/null +++ b/fuzz/corpus/canon_headers/cl-dup @@ -0,0 +1,2 @@ +content-length:5 +content-length:5 \ No newline at end of file diff --git a/fuzz/corpus/canon_headers/cl-te b/fuzz/corpus/canon_headers/cl-te new file mode 100644 index 0000000..1cb7b68 --- /dev/null +++ b/fuzz/corpus/canon_headers/cl-te @@ -0,0 +1,2 @@ +content-length:5 +transfer-encoding:chunked \ No newline at end of file diff --git a/fuzz/corpus/canon_headers/conn-nominates-key b/fuzz/corpus/canon_headers/conn-nominates-key new file mode 100644 index 0000000..f2fe49e --- /dev/null +++ b/fuzz/corpus/canon_headers/conn-nominates-key @@ -0,0 +1 @@ +connection:close, X-AP-Caller-Key \ No newline at end of file diff --git a/fuzz/corpus/canon_headers/crlf-value b/fuzz/corpus/canon_headers/crlf-value new file mode 100644 index 0000000..781467f --- /dev/null +++ b/fuzz/corpus/canon_headers/crlf-value @@ -0,0 +1,2 @@ +x-a:v +x-injected: 1 \ No newline at end of file diff --git a/fuzz/corpus/canon_headers/key-dup b/fuzz/corpus/canon_headers/key-dup new file mode 100644 index 0000000..b15ac80 --- /dev/null +++ b/fuzz/corpus/canon_headers/key-dup @@ -0,0 +1,2 @@ +x-ap-caller-key:apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef +x-ap-caller-key:apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef \ No newline at end of file diff --git a/fuzz/corpus/canon_headers/key-ok b/fuzz/corpus/canon_headers/key-ok new file mode 100644 index 0000000..4b84f2f --- /dev/null +++ b/fuzz/corpus/canon_headers/key-ok @@ -0,0 +1 @@ +x-ap-caller-key:apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef \ No newline at end of file diff --git a/fuzz/corpus/canon_headers/obs-fold b/fuzz/corpus/canon_headers/obs-fold new file mode 100644 index 0000000..e48a49f --- /dev/null +++ b/fuzz/corpus/canon_headers/obs-fold @@ -0,0 +1,2 @@ +x-a:v + folded \ No newline at end of file diff --git a/fuzz/corpus/canon_headers/surrogate-dup b/fuzz/corpus/canon_headers/surrogate-dup new file mode 100644 index 0000000..d8f010e --- /dev/null +++ b/fuzz/corpus/canon_headers/surrogate-dup @@ -0,0 +1,2 @@ +authorization:Bearer aps_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef +authorization:Bearer aps_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef \ No newline at end of file diff --git a/fuzz/corpus/canon_headers/surrogate-ok b/fuzz/corpus/canon_headers/surrogate-ok new file mode 100644 index 0000000..2caf0d8 --- /dev/null +++ b/fuzz/corpus/canon_headers/surrogate-ok @@ -0,0 +1 @@ +authorization:Bearer aps_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef \ No newline at end of file diff --git a/fuzz/corpus/canon_headers/te-list b/fuzz/corpus/canon_headers/te-list new file mode 100644 index 0000000..6f7ea69 --- /dev/null +++ b/fuzz/corpus/canon_headers/te-list @@ -0,0 +1 @@ +transfer-encoding:chunked, chunked \ No newline at end of file diff --git a/fuzz/corpus/canon_host/bad-punycode b/fuzz/corpus/canon_host/bad-punycode new file mode 100644 index 0000000..b925c52 --- /dev/null +++ b/fuzz/corpus/canon_host/bad-punycode @@ -0,0 +1 @@ +xn--a-.com \ No newline at end of file diff --git a/fuzz/corpus/canon_host/decimal b/fuzz/corpus/canon_host/decimal new file mode 100644 index 0000000..d141b6d --- /dev/null +++ b/fuzz/corpus/canon_host/decimal @@ -0,0 +1 @@ +2130706433 \ No newline at end of file diff --git a/fuzz/corpus/canon_host/hex-tail b/fuzz/corpus/canon_host/hex-tail new file mode 100644 index 0000000..027546c --- /dev/null +++ b/fuzz/corpus/canon_host/hex-tail @@ -0,0 +1 @@ +127.0.0.0x1 \ No newline at end of file diff --git a/fuzz/corpus/canon_host/idn-unicode b/fuzz/corpus/canon_host/idn-unicode new file mode 100644 index 0000000..80199ae --- /dev/null +++ b/fuzz/corpus/canon_host/idn-unicode @@ -0,0 +1 @@ +bücher.example \ No newline at end of file diff --git a/fuzz/corpus/canon_host/ipv6-mapped b/fuzz/corpus/canon_host/ipv6-mapped new file mode 100644 index 0000000..9679399 --- /dev/null +++ b/fuzz/corpus/canon_host/ipv6-mapped @@ -0,0 +1 @@ +[::ffff:127.0.0.1] \ No newline at end of file diff --git a/fuzz/corpus/canon_host/mixed-case b/fuzz/corpus/canon_host/mixed-case new file mode 100644 index 0000000..b1d12bf --- /dev/null +++ b/fuzz/corpus/canon_host/mixed-case @@ -0,0 +1 @@ +Api.Example.com \ No newline at end of file diff --git a/fuzz/corpus/canon_host/octal b/fuzz/corpus/canon_host/octal new file mode 100644 index 0000000..098e157 --- /dev/null +++ b/fuzz/corpus/canon_host/octal @@ -0,0 +1 @@ +0177.0.0.1 \ No newline at end of file diff --git a/fuzz/corpus/canon_host/ok b/fuzz/corpus/canon_host/ok new file mode 100644 index 0000000..7576a4f --- /dev/null +++ b/fuzz/corpus/canon_host/ok @@ -0,0 +1 @@ +api.example.com \ No newline at end of file diff --git a/fuzz/corpus/canon_host/punycode b/fuzz/corpus/canon_host/punycode new file mode 100644 index 0000000..3b6e206 --- /dev/null +++ b/fuzz/corpus/canon_host/punycode @@ -0,0 +1 @@ +xn--e1afmkfd.xn--p1ai \ No newline at end of file diff --git a/fuzz/corpus/canon_host/trailing-dot b/fuzz/corpus/canon_host/trailing-dot new file mode 100644 index 0000000..b46c5f0 --- /dev/null +++ b/fuzz/corpus/canon_host/trailing-dot @@ -0,0 +1 @@ +api.example.com. \ No newline at end of file diff --git a/fuzz/corpus/canon_origin/absolute-form b/fuzz/corpus/canon_origin/absolute-form new file mode 100644 index 0000000000000000000000000000000000000000..28cd8fb7645f5564f3fb82269d960d1e1338b526 GIT binary patch literal 39 gcmZR`C@Cqh($_aMGS@QzLPIMH6BA?o3NBOu0JeV!jsO4v literal 0 HcmV?d00001 diff --git a/fuzz/corpus/canon_origin/h2-absolute b/fuzz/corpus/canon_origin/h2-absolute new file mode 100644 index 0000000..db2f13b --- /dev/null +++ b/fuzz/corpus/canon_origin/h2-absolute @@ -0,0 +1,2 @@ +https://127.0.0.1:8443/x +127.0.0.1:8443 \ No newline at end of file diff --git a/fuzz/corpus/canon_origin/h2-mismatch b/fuzz/corpus/canon_origin/h2-mismatch new file mode 100644 index 0000000..d563d90 --- /dev/null +++ b/fuzz/corpus/canon_origin/h2-mismatch @@ -0,0 +1,2 @@ +https://evil.test/x +127.0.0.1:8443 \ No newline at end of file diff --git a/fuzz/corpus/canon_origin/no-host b/fuzz/corpus/canon_origin/no-host new file mode 100644 index 0000000000000000000000000000000000000000..c82a2a870f139d5cec7b7f6dfc6fd1a4641d89c7 GIT binary patch literal 3 KcmZS3uK)l5*#M{j literal 0 HcmV?d00001 diff --git a/fuzz/corpus/canon_origin/ok b/fuzz/corpus/canon_origin/ok new file mode 100644 index 0000000000000000000000000000000000000000..dab995853bb51902534786a13f14efd9b36bb801 GIT binary patch literal 21 acmZS3FEiAy;4(Ba*E0Y@Ln{jt6Jr1`j|55p literal 0 HcmV?d00001 diff --git a/fuzz/corpus/canon_origin/trailing-dot b/fuzz/corpus/canon_origin/trailing-dot new file mode 100644 index 0000000000000000000000000000000000000000..3276c07dd5ef44e73580aefdcb320675c9979c32 GIT binary patch literal 19 YcmZS3ui!E?GS@QzLPI?(3lkG#03#;@q5uE@ literal 0 HcmV?d00001 diff --git a/fuzz/corpus/canon_origin/two-hosts b/fuzz/corpus/canon_origin/two-hosts new file mode 100644 index 0000000000000000000000000000000000000000..7d132f65ccbb08c8d93a6cd6f66f70055d8a997c GIT binary patch literal 33 ZcmZS3ui!E?GS@QzLPIMH6BA=JE&ynA20#D+ literal 0 HcmV?d00001 diff --git a/fuzz/corpus/canon_origin/userinfo b/fuzz/corpus/canon_origin/userinfo new file mode 100644 index 0000000000000000000000000000000000000000..033f0da1db265f55c7152fbc0dcfa958b3977d99 GIT binary patch literal 20 ZcmZS3uiz?mFf=mPGXO$ED+?17V*o551StRj literal 0 HcmV?d00001 diff --git a/fuzz/corpus/canon_path/dot-param b/fuzz/corpus/canon_path/dot-param new file mode 100644 index 0000000..0c27137 --- /dev/null +++ b/fuzz/corpus/canon_path/dot-param @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up/v1/..;/admin \ No newline at end of file diff --git a/fuzz/corpus/canon_path/double-encoded-slash b/fuzz/corpus/canon_path/double-encoded-slash new file mode 100644 index 0000000..a006b4d --- /dev/null +++ b/fuzz/corpus/canon_path/double-encoded-slash @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up/v1/%252f \ No newline at end of file diff --git a/fuzz/corpus/canon_path/empty-key b/fuzz/corpus/canon_path/empty-key new file mode 100644 index 0000000..5f39c47 --- /dev/null +++ b/fuzz/corpus/canon_path/empty-key @@ -0,0 +1 @@ +/ap//up/x \ No newline at end of file diff --git a/fuzz/corpus/canon_path/empty-segment b/fuzz/corpus/canon_path/empty-segment new file mode 100644 index 0000000..86d59da --- /dev/null +++ b/fuzz/corpus/canon_path/empty-segment @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up//x \ No newline at end of file diff --git a/fuzz/corpus/canon_path/encoded-backslash b/fuzz/corpus/canon_path/encoded-backslash new file mode 100644 index 0000000..57831c5 --- /dev/null +++ b/fuzz/corpus/canon_path/encoded-backslash @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up/v1%5cx \ No newline at end of file diff --git a/fuzz/corpus/canon_path/forwarder-reencodes b/fuzz/corpus/canon_path/forwarder-reencodes new file mode 100644 index 0000000..00d67ae --- /dev/null +++ b/fuzz/corpus/canon_path/forwarder-reencodes @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up/a{b}"c \ No newline at end of file diff --git a/fuzz/corpus/canon_path/key-repeated b/fuzz/corpus/canon_path/key-repeated new file mode 100644 index 0000000..184bf95 --- /dev/null +++ b/fuzz/corpus/canon_path/key-repeated @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/x \ No newline at end of file diff --git a/fuzz/corpus/canon_path/key-reserved b/fuzz/corpus/canon_path/key-reserved new file mode 100644 index 0000000..ed557d9 --- /dev/null +++ b/fuzz/corpus/canon_path/key-reserved @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef%2f/up/x \ No newline at end of file diff --git a/fuzz/corpus/canon_path/non-ascii b/fuzz/corpus/canon_path/non-ascii new file mode 100644 index 0000000..144aa6f --- /dev/null +++ b/fuzz/corpus/canon_path/non-ascii @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up/café \ No newline at end of file diff --git a/fuzz/corpus/canon_path/ok-no-rest b/fuzz/corpus/canon_path/ok-no-rest new file mode 100644 index 0000000..e5afdd9 --- /dev/null +++ b/fuzz/corpus/canon_path/ok-no-rest @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up \ No newline at end of file diff --git a/fuzz/corpus/canon_path/ok-plain b/fuzz/corpus/canon_path/ok-plain new file mode 100644 index 0000000..cec0388 --- /dev/null +++ b/fuzz/corpus/canon_path/ok-plain @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up/v1/messages \ No newline at end of file diff --git a/fuzz/corpus/canon_path/param-plain b/fuzz/corpus/canon_path/param-plain new file mode 100644 index 0000000..5db598f --- /dev/null +++ b/fuzz/corpus/canon_path/param-plain @@ -0,0 +1 @@ +/v1/a;b=c/d \ No newline at end of file diff --git a/fuzz/corpus/canon_path/triple-encoded-backslash b/fuzz/corpus/canon_path/triple-encoded-backslash new file mode 100644 index 0000000..2c3afdc --- /dev/null +++ b/fuzz/corpus/canon_path/triple-encoded-backslash @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up/v1/%255c \ No newline at end of file diff --git a/fuzz/fuzz_targets/canon_headers.rs b/fuzz/fuzz_targets/canon_headers.rs new file mode 100644 index 0000000..e057bea --- /dev/null +++ b/fuzz/fuzz_targets/canon_headers.rs @@ -0,0 +1,22 @@ +//! Header names and values read before the policy match: caller key, surrogate, framing. +//! +//! Input: one header per line, `name:value` (value bytes are raw, CR and NUL included). Lines +//! that `http` itself refuses are dropped, as the wire parser would. +#![no_main] + +#[path = "../../crates/ap-core/tests/common/invariants.rs"] +mod invariants; + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let pairs: Vec<(Vec, Vec)> = data + .split(|b| *b == b'\n') + .take(16) + .filter_map(|line| { + let i = line.iter().position(|b| *b == b':')?; + Some((line[..i].to_vec(), line[i + 1..].to_vec())) + }) + .collect(); + invariants::check_headers(&pairs, "x-ap-caller-key"); +}); diff --git a/fuzz/fuzz_targets/canon_host.rs b/fuzz/fuzz_targets/canon_host.rs new file mode 100644 index 0000000..3bfca89 --- /dev/null +++ b/fuzz/fuzz_targets/canon_host.rs @@ -0,0 +1,12 @@ +//! Host normalisation: `canonical_host` accepts only the byte-exact lowercase DNS spelling, never +//! an IP in any spelling the `url` crate reads as one. +#![no_main] + +#[path = "../../crates/ap-core/tests/common/invariants.rs"] +mod invariants; + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + invariants::check_host(&String::from_utf8_lossy(data)); +}); diff --git a/fuzz/fuzz_targets/canon_origin.rs b/fuzz/fuzz_targets/canon_origin.rs new file mode 100644 index 0000000..dd5d1eb --- /dev/null +++ b/fuzz/fuzz_targets/canon_origin.rs @@ -0,0 +1,20 @@ +//! Request target and Host header (`check_origin_form`). +//! +//! Input: byte 0 bit 0 selects HTTP/2; line 1 is the request target; every later line is one Host +//! header value (at most four). The route authority is fixed. +#![no_main] + +#[path = "../../crates/ap-core/tests/common/invariants.rs"] +mod invariants; + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let Some((first, rest)) = data.split_first() else { + return; + }; + let mut lines = rest.split(|b| *b == b'\n'); + let target = String::from_utf8_lossy(lines.next().unwrap_or_default()).into_owned(); + let hosts: Vec> = lines.take(4).map(<[u8]>::to_vec).collect(); + invariants::check_origin(&target, &hosts, first & 1 == 1, "127.0.0.1:8443"); +}); diff --git a/fuzz/fuzz_targets/canon_path.rs b/fuzz/fuzz_targets/canon_path.rs new file mode 100644 index 0000000..4902d17 --- /dev/null +++ b/fuzz/fuzz_targets/canon_path.rs @@ -0,0 +1,12 @@ +//! Request path: `parse_ap_path` (the `/ap///...` form), the header-mode +//! route splitter, `path_ambiguous`, and agreement with the `http` and `url` parsers. +#![no_main] + +#[path = "../../crates/ap-core/tests/common/invariants.rs"] +mod invariants; + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + invariants::check_path(&String::from_utf8_lossy(data)); +}); diff --git a/tests/matrix/matrix.py b/tests/matrix/matrix.py index 703302e..def1cf1 100644 --- a/tests/matrix/matrix.py +++ b/tests/matrix/matrix.py @@ -39,7 +39,10 @@ ] P1_IDS = ["P1-01", "P1-02", "P1-03", "P1-04", "P1-05", "P1-06", "P1-07", "P1-08", "P1-09", "P1-10", "P1-11", "P1-12", "P1-13"] -EXPECTED = GATE_IDS + P1_IDS +# Canonicalization rows (issue #19): one per class of input, wire level, nothing reaches upstream +# unless the forwarded path is byte-identical to the path the policy matched. +CANON_IDS = ["C1-1", "C1-2", "C1-3", "C1-4", "C1-5", "C1-6", "C1-7"] +EXPECTED = GATE_IDS + P1_IDS + CANON_IDS def case(cid, row, name, instance="main"): @@ -754,6 +757,176 @@ def _(e): return st1 == 413 and st2 == 400, f"oversize_put={st1} invalid_session={st2}" +# ================================================================ C1 canonicalization classes (issue #19) +def audit_count(e): + return sum(1 for _ in open(e.audit_file, "rb")) if os.path.exists(e.audit_file) else 0 + + +def audit_paths_since(e, before): + with open(e.audit_file, "rb") as f: + new = f.read().splitlines()[before:] + return [json.loads(line).get("path") for line in new if line.strip()] + + +def canon_probe(e, line, headers, raw=None): + """Send one request, return (status, code, upstream log, audit paths written by it).""" + e.ureset() + before = audit_count(e) + if raw is not None: + st, _, b = e.raw(raw) + else: + st, _, b = e.raw_req(line, headers) + return st, code_of(b), e.ulog(), audit_paths_since(e, before) + + +def canon_refused(e, label, line, headers, codes=None, raw=None, statuses=range(400, 500)): + """Refused: a 4xx (a parse error from the HTTP layer counts), nothing at any upstream.""" + st, code, lg, _ = canon_probe(e, line, headers, raw) + ok = st in statuses and not lg and (codes is None or code in codes) + return ok, f"[{label}: {st}/{code}/{len(lg)}]" + + +def canon_forwarded_identical(e, label, line, headers, want_path): + """Forwarded: the upstream saw exactly `want_path`, and the audit line (what the policy + matched) carries the same bytes.""" + st, _, lg, seen = canon_probe(e, line, headers) + got = lg[0]["path"].split("?")[0] if lg else None + audit_ok = bool(seen) and seen[-1] == want_path + ok = st == 200 and len(lg) == 1 and got == want_path and audit_ok + return ok, f"[{label}: {st} upstream={got!r} audit={seen[-1:]}]" + + +def canon_run(checks): + ok_all, out = True, [] + for ok, d in checks: + ok_all = ok_all and ok + out.append(d) + return ok_all, " ".join(out) + + +@case("C1-1", "C1", "double-encoded, encoded slash and backslash, NUL: refused as path_ambiguous") +def _(e): + s = e.mint("agent-1", ("c-up",)) + au = [("Host", e.authority()), ("Authorization", f"Bearer {s}")] + paths = ["/v1/%252f", "/v1/%252F", "/v1/%252e%252e/x", "/v1/%255c", "/v1/%2500", "/v1/%25%32%66", + "/v1%2fecho", "/v1/%2Fecho", "/v1/a%5cb", "/v1/a%5Cb", "/v1/a%00b", "/v1/a\\b"] + return canon_run([canon_refused(e, p, f"GET {e.ap('up', p)} HTTP/1.1", au, {"path_ambiguous"}) + for p in paths]) + + +@case("C1-2", "C1", "`;` path parameters: on dot segments refused, on ordinary segments forwarded byte for byte") +def _(e): + s = e.mint("agent-1", ("c-up",)) + au = [("Host", e.authority()), ("Authorization", f"Bearer {s}")] + checks = [canon_refused(e, p, f"GET {e.ap('up', p)} HTTP/1.1", au, {"path_ambiguous"}) + for p in ["/v1/..;/admin", "/v1/..;x/admin", "/v1/.;/x", "/v1/..;a=b/x"]] + for p in ["/v1/a;b=c", "/v1/a;b/echo", "/v1/;x/echo"]: + checks.append(canon_forwarded_identical(e, p, f"GET {e.ap('up', p)} HTTP/1.1", au, p)) + return canon_run(checks) + + +@case("C1-3", "C1", "Unicode and bytes the forwarder would rewrite are refused; percent-encoded UTF-8 is forwarded unchanged") +def _(e): + s = e.mint("agent-1", ("c-up",)) + au = [("Host", e.authority()), ("Authorization", f"Bearer {s}")] + checks = [] + for label, p in [("e-acute", "/v1/caf\u00e9"), ("fullwidth dot", "/v1/\uff0e\uff0e/x"), + ("combining", "/v1/e\u0301"), ("brace", "/v1/{x}"), ("quote", '/v1/a"b'), + ("angle", "/v1/a"), ("backtick", "/v1/a`b")]: + checks.append(canon_refused(e, label, f"GET {e.ap('up', p)} HTTP/1.1", au, None)) + for p in ["/v1/caf%C3%A9", "/v1/%41", "/v1/100%25"]: + checks.append(canon_forwarded_identical(e, p, f"GET {e.ap('up', p)} HTTP/1.1", au, p)) + return canon_run(checks) + + +@case("C1-4", "C1", "Host spellings: case, trailing dot, IPv6, decimal/octal/hex IP, punycode, Unicode, empty") +def _(e): + s = e.mint("agent-1", ("c-up",)) + au = [("Authorization", f"Bearer {s}")] + line = f"GET {e.ap('up', '/v1/echo')} HTTP/1.1" + p = e.port + hosts = [("mixed case", f"LOCALHOST:{p}"), ("trailing dot", f"127.0.0.1.:{p}"), + ("IPv6 loopback", f"[::1]:{p}"), ("IPv4-mapped IPv6", f"[::ffff:127.0.0.1]:{p}"), + ("decimal IP", f"2130706433:{p}"), ("octal IP", f"0177.0.0.1:{p}"), + ("hex IP", f"0x7f.0.0.1:{p}"), ("hex tail IP", f"127.0.0.0x1:{p}"), + ("short IP", f"127.1:{p}"), ("punycode", f"xn--e1afmkfd.xn--p1ai:{p}"), + ("Unicode", f"b\u00fccher.example:{p}"), ("no port", "127.0.0.1"), ("empty", ""), + ("authority plus path", f"127.0.0.1:{p}/x"), ("comma list", f"127.0.0.1:{p},evil.test")] + return canon_run([canon_refused(e, label, line, [("Host", h)] + au, {"host_rejected"}) + for label, h in hosts]) + + +@case("C1-5", "C1", "absolute-form request target vs Host: refused whether it matches or not") +def _(e): + s = e.mint("agent-1", ("c-up",)) + a = e.authority() + au = [("Authorization", f"Bearer {s}")] + path = e.ap("up", "/v1/echo") + checks = [] + for label, target, host in [ + ("http matching", f"http://{a}{path}", a), ("https matching", f"https://{a}{path}", a), + ("foreign target", f"http://evil.test{path}", a), ("foreign Host", f"http://{a}{path}", "evil.test"), + ("target case", f"http://{a.upper()}{path}", a), ("userinfo", f"http://u@{a}{path}", a)]: + checks.append(canon_refused(e, label, f"GET {target} HTTP/1.1", [("Host", host)] + au, {"absolute_form"})) + checks.append(canon_refused(e, "authority-form //", f"GET //evil.test{path} HTTP/1.1", [("Host", a)] + au, None)) + return canon_run(checks) + + +@case("C1-6", "C1", "CRLF in values, obsolete folding, NUL and duplicate headers: refused, nothing upstream") +def _(e): + s = e.mint("agent-1", ("c-up",)) + a = e.authority() + req = e.ap("up", "/v1/echo") + base = f"GET {req} HTTP/1.1\r\nHost: {a}\r\n".encode() + sur = f"Authorization: Bearer {s}\r\n".encode() + checks = [] + for label, extra in [("bare CR in value", b"X-A: a\rb\r\n"), ("NUL in value", b"X-A: a\x00b\r\n"), + ("obs-fold continuation", b"X-A: a\r\n b\r\n"), + ("obs-fold tab", b"X-A: a\r\n\tb\r\n"), + ("space before colon", b"X-A : a\r\n"), + ("fold on Host", b"Host: x\r\n y\r\n")]: + checks.append(canon_refused(e, label, None, None, raw=base + sur + extra + b"\r\n", statuses=range(400, 500))) + dup = [("two Authorization", [("Authorization", f"Bearer {s}"), ("Authorization", f"Bearer {s}")]), + ("two Host", [("Host", a), ("Host", a)]), + ("two Content-Length", [("Authorization", f"Bearer {s}"), ("Content-Length", "0"), ("Content-Length", "0")]), + ("CL and TE", [("Authorization", f"Bearer {s}"), ("Content-Length", "0"), ("Transfer-Encoding", "chunked")])] + for label, hs in dup: + hh = hs if any(k == "Host" for k, _ in hs) else [("Host", a)] + hs + checks.append(canon_refused(e, label, f"GET {req} HTTP/1.1", hh, None)) + # Bare LF ends a header line for the parser, so what follows is a real header and is seen as + # one: the proxy parses once and forwards what it parsed, no second reading is possible. + e.ureset() + st, _, _ = e.raw(base + sur + b"X-A: a\nX-Injected: 1\r\n\r\n") + lg = e.ulog() + hs = dict(lg[0]["headers"]) if lg else {} + ok = (not lg and 400 <= st < 500) or (st == 200 and hs.get("x-a") == "a" and hs.get("x-injected") == "1") + checks.append((ok, f"[bare LF: {st}/{len(lg)} x-a={hs.get('x-a')!r}]")) + return canon_run(checks) + + +@case("C1-7", "C1", "caller key path form: empty, reserved characters, repeated key and prefix, over-long segment") +def _(e): + s = e.mint("agent-1", ("c-up",)) + k = e.keys["agent-1"] + au = [("Host", e.authority()), ("Authorization", f"Bearer {s}")] + checks = [] + for label, path in [("empty key", "/ap//up/v1/echo"), ("no key", "/ap/up/v1/echo"), + ("key %2f", f"/ap/{k}%2f/up/v1/echo"), ("key ;", f"/ap/{k};x/up/v1/echo"), + ("key ?", f"/ap/{k}?x/up/v1/echo"), ("key upper", f"/ap/{k.upper()}/up/v1/echo"), + ("key short", f"/ap/{k[:-1]}/up/v1/echo"), ("key long", f"/ap/{k}0/up/v1/echo"), + ("prefix case", f"/AP/{k}/up/v1/echo"), ("double prefix", f"/ap/ap/{k}/up/v1/echo")]: + checks.append(canon_refused(e, label, f"GET {path} HTTP/1.1", au, {"caller_rejected"}, statuses=[401])) + # The key and prefix appearing again later are plain path data: matched and forwarded as is. + again = f"/v1/echo/ap/{k}/up/x" + checks.append(canon_forwarded_identical(e, "repeated", f"GET {e.ap('up', again)} HTTP/1.1", au, again)) + long_ok = "/v1/" + "a" * 4000 + checks.append(canon_forwarded_identical(e, "4000-byte segment", f"GET {e.ap('up', long_ok)} HTTP/1.1", au, long_ok)) + checks.append(canon_refused(e, "300000-byte segment", f"GET {e.ap('up', '/v1/' + 'a' * 300000)} HTTP/1.1", au, + None, statuses=range(400, 500))) + return canon_run(checks) + + + # ================================================================ driver def run_instance(e, instance, results): """Start the processes this instance needs, run its cases in table order, stop them.""" @@ -831,11 +1004,12 @@ def main(): passed = sum(1 for r in results if r["verdict"] == "PASS") gate = sum(1 for r in results if r["id"] in GATE_IDS and r["verdict"] == "PASS") probe_target = sum(1 for r in results if r["id"] in P1_IDS and r["verdict"] == "PASS") + canon = sum(1 for r in results if r["id"] in CANON_IDS and r["verdict"] == "PASS") if a.json: with open(a.json, "w") as f: json.dump({"bin": bindir, "results": results, "missing": missing}, f, indent=1) print(f"\nrows: {len(results)} run, {len(EXPECTED)} expected, missing={missing or 'none'} extra={extra or 'none'}") - print(f"gate: {gate} PASS of {len(GATE_IDS)}; phase 1: {probe_target} PASS of {len(P1_IDS)}") + print(f"gate: {gate} PASS of {len(GATE_IDS)}; phase 1: {probe_target} PASS of {len(P1_IDS)}; canonicalization: {canon} PASS of {len(CANON_IDS)}") print(f"summary: {passed} PASS of {len(EXPECTED)} rows; work dir {work}") return 0 if (passed == len(EXPECTED) and not missing and not extra) else 1 diff --git a/tests/matrix/passthrough.py b/tests/matrix/passthrough.py index cc55f91..e2b9ec9 100644 --- a/tests/matrix/passthrough.py +++ b/tests/matrix/passthrough.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Black-box matrix for the Muse gated passthrough, stage 1 (docs/design/muse-gated-passthrough.md, -section 7). Separate from matrix.py, whose 41 rows are unchanged. +section 7). Separate from matrix.py, whose first 41 rows are unchanged. passthrough.py --bin DIR [--work DIR] [--json OUT] @@ -34,7 +34,7 @@ CASES = [] # (id, row, name, instance, fn) EXPECTED = ["PT-01", "PT-02", "PT-03", "PT-04", "PT-05", "PT-06", "PT-07", "PT-08", "PT-09", - "PT-10a", "PT-12", "PT-13", "PT-14", "PT-15", "PT-16", "PT-17"] + "PT-10a", "PT-12", "PT-13", "PT-14", "PT-15", "PT-16", "PT-17", "PT-18", "PT-19"] def case(cid, row, name, instance="main"): @@ -611,6 +611,88 @@ def pt14(c): return r["status"] == 200 and not socks, f"status={r['status']} sockets={socks}" +def canon_refused(c, label, raw, codes=None, statuses=range(400, 500)): + """Refused: a 4xx (an HTTP-layer parse error counts) and nothing at the upstream.""" + r = exchange(c.port, raw) + n = len(c.ulog()) + ok = r["status"] in statuses and n == 0 and (codes is None or code_of(r) in codes) + return ok, f"[{label}: {r['status']}/{code_of(r)}/{n}]" + + +def canon_identical(c, label, raw, want_path): + """Forwarded: the upstream saw exactly `want_path`, with the caller key nowhere in it.""" + r = exchange(c.port, raw) + up = c.ulog() + got = up[0]["path"].split("?")[0] if up else None + ok = r["status"] == 200 and len(up) == 1 and got == want_path + return ok, f"[{label}: {r['status']} upstream={got!r}]" + + +def run_all(checks): + ok = True + out = [] + for good, d in checks: + ok &= good + out.append(d) + return ok, " ".join(out) + + +@case("PT-18", "issue 19", "path forms with the caller key: encodings, `;`, Unicode, empty and reserved keys, repeated key; matched path is the forwarded path") +def pt18(c): + k = c.key + key_hdr = [("Authorization", c.auth)] + + def get(path, key=k): + return build("GET", f"/ap/{key}{path}", key_hdr) + + checks = [] + for p in ["/discord/v1/%252f", "/discord/v1/%255c", "/discord/v1/%2500", "/discord/v1%2fx", + "/discord/v1/%5cx", "/discord/v1/..;/x", "/discord/v1/.;/x", "/discord/v1/{x}", '/discord/v1/a"b', + "/discord/v1/caf\u00e9", "/discord/v1/\uff0e\uff0e/x"]: + checks.append(canon_refused(c, p, get(p), None if not p.isascii() else {"path_ambiguous"})) + for label, key in [("empty key", ""), ("key %2f", k + "%2f"), ("key ;", k + ";x"), + ("key upper", k.upper()), ("key short", k[:-1]), ("key long", k + "0")]: + checks.append(canon_refused(c, label, build("GET", f"/ap/{key}/discord/v1/x", key_hdr), {"caller_rejected"}, + statuses=[401])) + for p in ["/v1/a;b=c", "/v1/caf%C3%A9", f"/v1/echo/ap/{k}/discord/x", "/v1/" + "a" * 4000]: + checks.append(canon_identical(c, p[:24], get("/discord" + p), p)) + n = len(c.ulog()) + r = exchange(c.port, build("GET", f"/ap/{k}/discord/v1/" + "a" * 300000, key_hdr)) + checks.append((400 <= r["status"] < 500 and len(c.ulog()) == n, f"[300000-byte segment: {r['status']}]")) + return run_all(checks) + + +@case("PT-19", "issue 19", "public Host spellings, absolute form, CRLF and folded headers, duplicate and conflicting headers") +def pt19(c): + path = "/discord/v1/x" + good = c.good() + checks = [] + for label, host in [("mixed case", AUTHORITY.upper()), ("trailing dot", AUTHORITY + "."), + ("with port", AUTHORITY + ":443"), ("IPv6", "[::1]"), ("IPv4-mapped", "[::ffff:127.0.0.1]"), + ("decimal IP", "2130706433"), ("octal IP", "0177.0.0.1"), ("hex IP", "0x7f.0.0.1"), + ("punycode", "xn--e1afmkfd.xn--p1ai"), ("Unicode", "b\u00fccher.example"), + ("userinfo", "u@" + AUTHORITY), ("empty", "")]: + checks.append(canon_refused(c, label, build("GET", path, good, host=host), {"host_rejected"})) + for label, target, host in [("absolute matching", f"http://{AUTHORITY}{path}", AUTHORITY), + ("absolute https", f"https://{AUTHORITY}{path}", AUTHORITY), + ("absolute foreign", f"http://evil.test{path}", AUTHORITY), + ("absolute foreign Host", f"http://{AUTHORITY}{path}", "evil.test")]: + checks.append(canon_refused(c, label, build("GET", target, good, host=host), {"absolute_form"})) + base = f"GET {path} HTTP/1.1\r\nHost: {AUTHORITY}\r\n{KEY_HEADER}: {c.key}\r\nAuthorization: {c.auth}\r\n".encode() + for label, extra in [("bare CR", b"X-A: a\rb\r\n"), ("NUL", b"X-A: a\x00b\r\n"), + ("obs-fold", b"X-A: a\r\n b\r\n"), ("obs-fold tab", b"X-A: a\r\n\tb\r\n"), + ("space before colon", b"X-A : a\r\n")]: + checks.append(canon_refused(c, label, base + extra + b"\r\n")) + for label, hs in [("two caller keys", [(KEY_HEADER, c.key), (KEY_HEADER, c.key)]), + ("two Authorization", [(KEY_HEADER, c.key), ("Authorization", c.auth), ("Authorization", c.auth)]), + ("two Content-Length", c.good([("Content-Length", "0"), ("Content-Length", "0")])), + ("CL and TE", c.good([("Content-Length", "0"), ("Transfer-Encoding", "chunked")])), + ("Connection nominates key", c.good([("Connection", KEY_HEADER)]))]: + checks.append(canon_refused(c, label, build("GET", path, hs))) + return run_all(checks) + + + # ------------------------------------------------------------------ driver def run_instance(c, instance, results): cases = [x for x in CASES if x[3] == instance] From 5e40bb5e36b3e80e4d9f6af75b8bc31908c9594d Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:04:44 -0500 Subject: [PATCH 2/4] fix: close three canonicalization gaps found by the issue #19 tests 1. canonical_host accepted a hex last label (127.0.0.0x1, a.0x7f). The url crate and inet_aton read these as IPv4. The numeric-TLD rule now covers 0x. 2. path_ambiguous accepted dot segments carrying a ; parameter (/v1/..;/admin, read as .. by servlet containers) and double encodings other than %252e/%252f (%255c, %2500, %25%32%66). Dot segments are now judged on the part before ;, and percent-decoding is applied up to three times looking for %2e %2f %5c %00. 3. Paths with non-ASCII bytes, DEL, space, " < > backtick { } were matched raw but sent percent-encoded by the url crate, so the matched path was not the forwarded path. They are now refused as path_ambiguous. Also: invariants.rs skips paths that do not start with / (url maps an empty path to /); the seed literal is grouped for clippy; PT-06 needle /ap/ becomes /ap/apk_ so a repeated prefix in a forwarded path is not read as a leaked key (real keys stay needles of their own). Verified on macmini: cargo test -p ap-core --tests and ap-proxy canon_diff pass; sidecar matrix 48/48, passthrough matrix 18/18; fmt and clippy clean. --- Cargo.lock | 1 + crates/ap-core/src/canon.rs | 71 ++++++++++++++++++---- crates/ap-core/tests/canon_differential.rs | 2 +- crates/ap-core/tests/common/invariants.rs | 3 +- crates/ap-proxy/src/canon_diff_tests.rs | 2 +- tests/matrix/matrix.py | 38 +++++++++--- tests/matrix/passthrough.py | 34 ++++++++--- 7 files changed, 119 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c7179eb..0cbc420 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -44,6 +44,7 @@ dependencies = [ "serde", "serde_json", "toml", + "url", ] [[package]] diff --git a/crates/ap-core/src/canon.rs b/crates/ap-core/src/canon.rs index 09f5a96..cd993d1 100644 --- a/crates/ap-core/src/canon.rs +++ b/crates/ap-core/src/canon.rs @@ -38,11 +38,14 @@ pub fn canonical_host(h: &str) -> Result<(), &'static str> { return Err("bad label (userinfo, port, trailing dot or non-LDH)"); } } - // An all-numeric last label is an IPv4 spelling the IpAddr parser misses (127.1, 0x7f.0.0.1). - if labels - .last() - .is_some_and(|l| l.bytes().all(|b| b.is_ascii_digit())) - { + // A last label that is all digits, or `0x` and hex digits, is an IPv4 spelling the IpAddr + // parser misses (127.1, 0x7f.0.0.1, 127.0.0.0x1). The WHATWG URL parser, and inet_aton + // behind getaddrinfo, read every one of them as an address. Uppercase `0X` never gets here. + if labels.last().is_some_and(|l| { + l.bytes().all(|b| b.is_ascii_digit()) + || l.strip_prefix("0x") + .is_some_and(|h| h.bytes().all(|b| b.is_ascii_hexdigit())) + }) { return Err("numeric TLD (IPv4 spelling)"); } Ok(()) @@ -94,9 +97,12 @@ pub fn check_origin_form( /// True when the raw, still-encoded path could be read two ways. /// -/// Flags `..` and `.` segments, empty interior segments (`//`), `%2e` and `%2f` -/// in any case, `%5c`, `%00`, backslash, and `%25` followed by `2e` or `2f` -/// (double encoding). +/// Flags `..` and `.` segments (also with a `;` parameter, as in `..;x`, which a servlet +/// container reads as `..`), empty interior segments (`//`), `%2e` and `%2f` in any case, `%5c`, +/// `%00`, backslash, double encoding of any of those (`%252f`, `%255c`, `%2500`, `%25%32%66`, up +/// to three layers), and bytes the forwarder would percent-encode (non-ASCII, controls, space, +/// DEL, `"`, `<`, `>`, backtick, `{`, `}`), because for those the path that was matched would +/// not be the path that is sent. pub fn path_ambiguous(p: &str) -> bool { let lower = p.to_ascii_lowercase(); if ["%2e", "%2f", "%5c", "%00"] @@ -106,16 +112,57 @@ pub fn path_ambiguous(p: &str) -> bool { { return true; } + if p.bytes() + .any(|b| b <= 0x20 || b >= 0x7f || b"\"<>`{}".contains(&b)) + { + return true; + } if lower.match_indices("%25").any(|(i, _)| { let rest = &lower[i + 3..]; rest.starts_with("2e") || rest.starts_with("2f") - }) { + }) || encodes_separator_in_layers(lower.as_bytes()) + { return true; } let segs: Vec<&str> = p.split('/').skip(1).collect(); - segs.iter() - .enumerate() - .any(|(i, s)| *s == "." || *s == ".." || (s.is_empty() && i + 1 != segs.len())) + segs.iter().enumerate().any(|(i, s)| { + let name = s.split(';').next().unwrap_or_default(); + name == "." || name == ".." || (s.is_empty() && i + 1 != segs.len()) + }) +} + +/// True when percent-decoding `lower` (already ASCII-lowercased) one to three times exposes +/// `%2e`, `%2f`, `%5c` or `%00`: a second or third decoder would then read a dot, slash, +/// backslash or NUL that the first layer hid. +fn encodes_separator_in_layers(lower: &[u8]) -> bool { + let mut cur = lower.to_vec(); + for _ in 0..3 { + let mut out = Vec::with_capacity(cur.len()); + let mut i = 0; + while i < cur.len() { + let hex = |b: u8| (b as char).to_digit(16); + if cur[i] == b'%' && i + 2 < cur.len() { + if let (Some(h), Some(l)) = (hex(cur[i + 1]), hex(cur[i + 2])) { + out.push(u8::try_from(h * 16 + l).unwrap_or(b'%')); + i += 3; + continue; + } + } + out.push(cur[i].to_ascii_lowercase()); + i += 1; + } + if [&b"%2e"[..], b"%2f", b"%5c", b"%00"] + .iter() + .any(|s| out.windows(s.len()).any(|w| w == *s)) + { + return true; + } + if !out.contains(&b'%') { + return false; + } + cur = out; + } + false } /// The parts of a `/ap///` path. diff --git a/crates/ap-core/tests/canon_differential.rs b/crates/ap-core/tests/canon_differential.rs index 9be42fa..84651ea 100644 --- a/crates/ap-core/tests/canon_differential.rs +++ b/crates/ap-core/tests/canon_differential.rs @@ -28,7 +28,7 @@ impl Rng { } } -const SEED: u64 = 0x19_C0FF_EE_5EED; +const SEED: u64 = 0x19C0_FFEE_5EED; const KEY: &str = "apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; const PATH_ATOMS: &[&str] = &[ diff --git a/crates/ap-core/tests/common/invariants.rs b/crates/ap-core/tests/common/invariants.rs index 12b681a..886d23a 100644 --- a/crates/ap-core/tests/common/invariants.rs +++ b/crates/ap-core/tests/common/invariants.rs @@ -67,7 +67,8 @@ pub fn check_path_against_parsers(p: &str) { let Ok(uri) = Uri::from_str(p) else { return }; // The pipeline matches `uri.path()`, never the raw target. let path = uri.path(); - if path_ambiguous(path) { + // Every route starts with `/ap/` or `/`; `*` and an empty path never reach a route. + if !path.starts_with('/') || path_ambiguous(path) { return; } let Ok(url) = url::Url::parse(&format!("https://example.test{path}")) else { diff --git a/crates/ap-proxy/src/canon_diff_tests.rs b/crates/ap-proxy/src/canon_diff_tests.rs index fdaf9c1..53c2b09 100644 --- a/crates/ap-proxy/src/canon_diff_tests.rs +++ b/crates/ap-proxy/src/canon_diff_tests.rs @@ -54,7 +54,7 @@ async fn matched_path_is_the_forwarded_path() { let up = start_upstream().await; let f = Fixture::new("canon-diff", &up); let surrogate = register_session(&f.app, IDENTITY, "sess-1", 1); - let mut r = Rng(0x19_C0FF_EE_5EED); + let mut r = Rng(0x19C0_FFEE_5EED); let (mut forwarded, mut refused, mut unparsed) = (0, 0, 0); let mut mismatches: Vec = Vec::new(); diff --git a/tests/matrix/matrix.py b/tests/matrix/matrix.py index def1cf1..e9b333f 100644 --- a/tests/matrix/matrix.py +++ b/tests/matrix/matrix.py @@ -793,7 +793,19 @@ def canon_forwarded_identical(e, label, line, headers, want_path): got = lg[0]["path"].split("?")[0] if lg else None audit_ok = bool(seen) and seen[-1] == want_path ok = st == 200 and len(lg) == 1 and got == want_path and audit_ok - return ok, f"[{label}: {st} upstream={got!r} audit={seen[-1:]}]" + return ok, f"[{label[:30]}: {st} upstream={(got or '')[:40]!r} audit_same={audit_ok}]" + + +def canon_framing(e, label, line, headers): + """Framing conflicts that the HTTP layer may settle itself: either refused, or forwarded with + one framing header only (it parsed once and decided), never both Content-Length and TE.""" + st, _, lg, _ = canon_probe(e, line, headers) + if not lg: + return 400 <= st < 500, f"[{label}: refused {st}]" + names = [k for k, _ in lg[0]["headers"]] + ok = st == 200 and len(lg) == 1 and names.count("content-length") <= 1 and not ( + "content-length" in names and "transfer-encoding" in names) + return ok, f"[{label}: forwarded {st} cl={names.count('content-length')} te={names.count('transfer-encoding')}]" def canon_run(checks): @@ -886,13 +898,18 @@ def _(e): ("space before colon", b"X-A : a\r\n"), ("fold on Host", b"Host: x\r\n y\r\n")]: checks.append(canon_refused(e, label, None, None, raw=base + sur + extra + b"\r\n", statuses=range(400, 500))) - dup = [("two Authorization", [("Authorization", f"Bearer {s}"), ("Authorization", f"Bearer {s}")]), - ("two Host", [("Host", a), ("Host", a)]), - ("two Content-Length", [("Authorization", f"Bearer {s}"), ("Content-Length", "0"), ("Content-Length", "0")]), - ("CL and TE", [("Authorization", f"Bearer {s}"), ("Content-Length", "0"), ("Transfer-Encoding", "chunked")])] - for label, hs in dup: + for label, hs in [("two Authorization", [("Authorization", f"Bearer {s}"), ("Authorization", f"Bearer {s}")]), + ("two Host", [("Host", a), ("Host", a)])]: hh = hs if any(k == "Host" for k, _ in hs) else [("Host", a)] + hs checks.append(canon_refused(e, label, f"GET {req} HTTP/1.1", hh, None)) + au2 = [("Host", a), ("Authorization", f"Bearer {s}")] + checks.append(canon_refused(e, "two different Content-Length", f"GET {req} HTTP/1.1", + au2 + [("Content-Length", "0"), ("Content-Length", "5")], None)) + for label, hs in [("two equal Content-Length", [("Content-Length", "0"), ("Content-Length", "0")]), + ("CL and TE", [("Content-Length", "0"), ("Transfer-Encoding", "chunked")]), + ("TE twice", [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "chunked")]), + ("TE list", [("Transfer-Encoding", "gzip, chunked")])]: + checks.append(canon_framing(e, label, f"GET {req} HTTP/1.1", au2 + hs)) # Bare LF ends a header line for the parser, so what follows is a real header and is seen as # one: the proxy parses once and forwards what it parsed, no second reading is possible. e.ureset() @@ -900,7 +917,7 @@ def _(e): lg = e.ulog() hs = dict(lg[0]["headers"]) if lg else {} ok = (not lg and 400 <= st < 500) or (st == 200 and hs.get("x-a") == "a" and hs.get("x-injected") == "1") - checks.append((ok, f"[bare LF: {st}/{len(lg)} x-a={hs.get('x-a')!r}]")) + checks.append((ok, f"[bare LF: {st}/{len(lg)} seen={sorted(k for k in hs if k.startswith('x-'))}]")) return canon_run(checks) @@ -915,9 +932,10 @@ def _(e): ("key ?", f"/ap/{k}?x/up/v1/echo"), ("key upper", f"/ap/{k.upper()}/up/v1/echo"), ("key short", f"/ap/{k[:-1]}/up/v1/echo"), ("key long", f"/ap/{k}0/up/v1/echo"), ("prefix case", f"/AP/{k}/up/v1/echo"), ("double prefix", f"/ap/ap/{k}/up/v1/echo")]: - checks.append(canon_refused(e, label, f"GET {path} HTTP/1.1", au, {"caller_rejected"}, statuses=[401])) - # The key and prefix appearing again later are plain path data: matched and forwarded as is. - again = f"/v1/echo/ap/{k}/up/x" + checks.append(canon_refused(e, label, f"GET {path} HTTP/1.1", au, {"caller_rejected", "path_ambiguous"})) + # A key-shaped string and the prefix appearing again later are plain path data: matched and + # forwarded as is. (A fresh random key, so the audit file holds no real credential.) + again = f"/v1/echo/ap/apk_{secrets.token_hex(32)}/up/x" checks.append(canon_forwarded_identical(e, "repeated", f"GET {e.ap('up', again)} HTTP/1.1", au, again)) long_ok = "/v1/" + "a" * 4000 checks.append(canon_forwarded_identical(e, "4000-byte segment", f"GET {e.ap('up', long_ok)} HTTP/1.1", au, long_ok)) diff --git a/tests/matrix/passthrough.py b/tests/matrix/passthrough.py index e2b9ec9..bbe3cb9 100644 --- a/tests/matrix/passthrough.py +++ b/tests/matrix/passthrough.py @@ -474,7 +474,7 @@ def pt06(c): alive = r["status"] == 200 out.append(f"alive-after-panic:{alive}") e.stop_proxy() # flush every file - needles = [c.auth.split(" ", 1)[1].encode(), c.key.encode(), c.path_token.encode(), b"/ap/"] + needles = [c.auth.split(" ", 1)[1].encode(), c.key.encode(), c.path_token.encode(), b"/ap/apk_"] hits, scanned = [], [] for root, _d, files in os.walk(e.work): rel = os.path.relpath(root, e.work) @@ -613,6 +613,7 @@ def pt14(c): def canon_refused(c, label, raw, codes=None, statuses=range(400, 500)): """Refused: a 4xx (an HTTP-layer parse error counts) and nothing at the upstream.""" + c.e.ureset() r = exchange(c.port, raw) n = len(c.ulog()) ok = r["status"] in statuses and n == 0 and (codes is None or code_of(r) in codes) @@ -621,11 +622,26 @@ def canon_refused(c, label, raw, codes=None, statuses=range(400, 500)): def canon_identical(c, label, raw, want_path): """Forwarded: the upstream saw exactly `want_path`, with the caller key nowhere in it.""" + c.e.ureset() r = exchange(c.port, raw) up = c.ulog() got = up[0]["path"].split("?")[0] if up else None ok = r["status"] == 200 and len(up) == 1 and got == want_path - return ok, f"[{label}: {r['status']} upstream={got!r}]" + return ok, f"[{label[:30]}: {r['status']} upstream={(got or '')[:40]!r}]" + + +def canon_framing(c, label, raw): + """Framing conflicts the HTTP layer may settle itself: refused, or forwarded with one framing + header only. Never both Content-Length and Transfer-Encoding upstream.""" + c.e.ureset() + r = exchange(c.port, raw) + up = c.ulog() + if not up: + return 400 <= r["status"] < 500, f"[{label}: refused {r['status']}]" + names = [k for k, _ in up[0]["headers"]] + ok = (r["status"] == 200 and names.count("content-length") <= 1 + and not ("content-length" in names and "transfer-encoding" in names)) + return ok, f"[{label}: forwarded {r['status']} cl={names.count('content-length')} te={names.count('transfer-encoding')}]" def run_all(checks): @@ -652,9 +668,9 @@ def get(path, key=k): checks.append(canon_refused(c, p, get(p), None if not p.isascii() else {"path_ambiguous"})) for label, key in [("empty key", ""), ("key %2f", k + "%2f"), ("key ;", k + ";x"), ("key upper", k.upper()), ("key short", k[:-1]), ("key long", k + "0")]: - checks.append(canon_refused(c, label, build("GET", f"/ap/{key}/discord/v1/x", key_hdr), {"caller_rejected"}, - statuses=[401])) - for p in ["/v1/a;b=c", "/v1/caf%C3%A9", f"/v1/echo/ap/{k}/discord/x", "/v1/" + "a" * 4000]: + checks.append(canon_refused(c, label, build("GET", f"/ap/{key}/discord/v1/x", key_hdr), + {"caller_rejected", "path_ambiguous"})) + for p in ["/v1/a;b=c", "/v1/caf%C3%A9", "/v1/echo/ap/discord/x", "/v1/" + "a" * 4000]: checks.append(canon_identical(c, p[:24], get("/discord" + p), p)) n = len(c.ulog()) r = exchange(c.port, build("GET", f"/ap/{k}/discord/v1/" + "a" * 300000, key_hdr)) @@ -685,10 +701,14 @@ def pt19(c): checks.append(canon_refused(c, label, base + extra + b"\r\n")) for label, hs in [("two caller keys", [(KEY_HEADER, c.key), (KEY_HEADER, c.key)]), ("two Authorization", [(KEY_HEADER, c.key), ("Authorization", c.auth), ("Authorization", c.auth)]), - ("two Content-Length", c.good([("Content-Length", "0"), ("Content-Length", "0")])), - ("CL and TE", c.good([("Content-Length", "0"), ("Transfer-Encoding", "chunked")])), + ("two different Content-Length", c.good([("Content-Length", "0"), ("Content-Length", "5")])), ("Connection nominates key", c.good([("Connection", KEY_HEADER)]))]: checks.append(canon_refused(c, label, build("GET", path, hs))) + for label, hs in [("two equal Content-Length", [("Content-Length", "0"), ("Content-Length", "0")]), + ("CL and TE", [("Content-Length", "0"), ("Transfer-Encoding", "chunked")]), + ("TE twice", [("Transfer-Encoding", "chunked"), ("Transfer-Encoding", "chunked")]), + ("TE list", [("Transfer-Encoding", "gzip, chunked")])]: + checks.append(canon_framing(c, label, build("GET", path, c.good(hs)))) return run_all(checks) From 93b2982537af9baeb5785584a5fb05d33388289e Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:13:45 -0500 Subject: [PATCH 3/4] docs: fuzz/README for the canonicalization targets Fuzz run on macmini (nightly 1.102, cargo-fuzz 0.13.2, 300 s per target, seeds from fuzz/corpus): canon_path 17,335,327 execs, canon_host 30,400,105, canon_origin 51,598,522, canon_headers 23,182,834; 0 crashes. Against the pre-fix canon.rs from an empty corpus, canon_host and canon_path each crash within 60 s. --- fuzz/README.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 fuzz/README.md diff --git a/fuzz/README.md b/fuzz/README.md new file mode 100644 index 0000000..0e7c16f --- /dev/null +++ b/fuzz/README.md @@ -0,0 +1,25 @@ +# Canonicalization fuzz targets + +cargo-fuzz targets for request canonicalization (`crates/ap-core/src/canon.rs`), issue #19. This +crate is outside the root workspace, so `cargo build --workspace` and `cargo test --workspace` never +build it. It needs a nightly toolchain and `cargo install cargo-fuzz --locked`. + +| Target | Input | What it checks | +|---|---|---| +| `canon_path` | a request path | `parse_ap_path` (the `/ap///...` form), the header-mode route splitter, `path_ambiguous`, and that an accepted path is byte-identical under the `http` and `url` parsers | +| `canon_host` | a host name | `canonical_host` accepts only the byte-exact lowercase DNS spelling, never something `url` reads as an IP | +| `canon_origin` | byte 0 bit 0 = HTTP/2, line 1 = target, later lines = Host values | `check_origin_form`: an accepted request has one Host equal to the route authority | +| `canon_headers` | one `name:value` per line | caller key, surrogate and framing rules over raw header bytes | + +The invariants are in `crates/ap-core/tests/common/invariants.rs`, shared with the cargo tests +(`canon_differential`, `canon_regression`), so a fuzz crash and a test failure name the same input. + +``` +cd fuzz +cargo +nightly fuzz run canon_path -- -max_total_time=300 +``` + +`corpus//` holds a small hand-written seed set, one file per class in the issue. A crash is +written to `artifacts//`; copy it into a regression case in +`crates/ap-core/tests/canon_regression.rs` when fixing it. CI runs each target for 45 seconds on pull +requests that touch `canon.rs` and for 300 seconds nightly (`.github/workflows/fuzz.yml`). From f956c1f1c59c9aa77249f637f60eda7bc7957f30 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:43:31 -0500 Subject: [PATCH 4/4] fix: decode-to-fixed-point path ambiguity check (layered, mixed-case, encoded ';', overlong UTF-8) Review round 2 on PR 27. path_ambiguous now percent-decodes layer by layer to a fixed point (max 4, still decodable => refuse) and refuses bytes produced by a decode that are . / \ NUL controls (any layer) or ; (layer 2+), %u escapes, invalid/overlong UTF-8, and dot segments (before any ;) in every layer. Adds regression tables, fuzz seeds, an independent decode oracle in the shared invariants, wider generator atoms, matrix rows, and asserts no upstream hit on every non-200 in the real-forwarder differential. Verified on macmini: fmt, clippy (default, stage1-probe, matrix-upstream), cargo test --workspace, stage1-probe lib (75), release hook greps, sidecar matrix 48/48, passthrough matrix 18/18, four fuzz targets 300s each, 0 crashes. --- crates/ap-core/src/canon.rs | 110 +++++++++++------- crates/ap-core/tests/canon_differential.rs | 85 +++++++++++++- crates/ap-core/tests/canon_regression.rs | 110 +++++++++++++++++- crates/ap-core/tests/common/invariants.rs | 74 ++++++++++++ crates/ap-proxy/src/canon_diff_tests.rs | 87 ++++++++++++-- fuzz/corpus/canon_path/double-pct | 1 + fuzz/corpus/canon_path/encoded-ctl | 1 + fuzz/corpus/canon_path/encoded-del | 1 + fuzz/corpus/canon_path/encoded-semi-dot | 1 + fuzz/corpus/canon_path/encoded-semi-dotdot | 1 + fuzz/corpus/canon_path/encoded-semi-dots-enc | 1 + fuzz/corpus/canon_path/encoded-semi-mid | 1 + fuzz/corpus/canon_path/encoded-semi-nested | 1 + fuzz/corpus/canon_path/encoded-semi-slash | 1 + fuzz/corpus/canon_path/five-layer-dot | 1 + fuzz/corpus/canon_path/iis-unicode | 1 + .../corpus/canon_path/layered-backslash-upper | 1 + fuzz/corpus/canon_path/layered-dots-upper | 1 + fuzz/corpus/canon_path/layered-nul | 1 + fuzz/corpus/canon_path/layered-slash-upper | 1 + fuzz/corpus/canon_path/overlong-dot | 1 + fuzz/corpus/canon_path/overlong-slash | 1 + fuzz/corpus/canon_path/partial-escape | 1 + fuzz/corpus/canon_path/valid-utf8 | 1 + tests/matrix/matrix.py | 11 +- tests/matrix/passthrough.py | 6 +- 26 files changed, 437 insertions(+), 65 deletions(-) create mode 100644 fuzz/corpus/canon_path/double-pct create mode 100644 fuzz/corpus/canon_path/encoded-ctl create mode 100644 fuzz/corpus/canon_path/encoded-del create mode 100644 fuzz/corpus/canon_path/encoded-semi-dot create mode 100644 fuzz/corpus/canon_path/encoded-semi-dotdot create mode 100644 fuzz/corpus/canon_path/encoded-semi-dots-enc create mode 100644 fuzz/corpus/canon_path/encoded-semi-mid create mode 100644 fuzz/corpus/canon_path/encoded-semi-nested create mode 100644 fuzz/corpus/canon_path/encoded-semi-slash create mode 100644 fuzz/corpus/canon_path/five-layer-dot create mode 100644 fuzz/corpus/canon_path/iis-unicode create mode 100644 fuzz/corpus/canon_path/layered-backslash-upper create mode 100644 fuzz/corpus/canon_path/layered-dots-upper create mode 100644 fuzz/corpus/canon_path/layered-nul create mode 100644 fuzz/corpus/canon_path/layered-slash-upper create mode 100644 fuzz/corpus/canon_path/overlong-dot create mode 100644 fuzz/corpus/canon_path/overlong-slash create mode 100644 fuzz/corpus/canon_path/partial-escape create mode 100644 fuzz/corpus/canon_path/valid-utf8 diff --git a/crates/ap-core/src/canon.rs b/crates/ap-core/src/canon.rs index cd993d1..543b7c2 100644 --- a/crates/ap-core/src/canon.rs +++ b/crates/ap-core/src/canon.rs @@ -95,74 +95,96 @@ pub fn check_origin_form( } } +/// Most percent-decode layers examined. A path that is still decodable after this many is +/// refused, because a decoder stack deeper than the limit could still expose a separator. +const MAX_DECODE_LAYERS: usize = 4; + /// True when the raw, still-encoded path could be read two ways. /// -/// Flags `..` and `.` segments (also with a `;` parameter, as in `..;x`, which a servlet -/// container reads as `..`), empty interior segments (`//`), `%2e` and `%2f` in any case, `%5c`, -/// `%00`, backslash, double encoding of any of those (`%252f`, `%255c`, `%2500`, `%25%32%66`, up -/// to three layers), and bytes the forwarder would percent-encode (non-ASCII, controls, space, -/// DEL, `"`, `<`, `>`, backtick, `{`, `}`), because for those the path that was matched would -/// not be the path that is sent. +/// The rule is one decode-to-fixed-point walk. The path is percent-decoded layer by layer (hex +/// digits in either case, so `%2E` and `%2e`, and a layer-1 byte that spells a new escape such as +/// `%2%45`, are all handled by value, never by text match). Any byte that a decode produces is +/// refused when it is `.`, `/`, `\`, NUL or a control character (a single decode of those is +/// already ambiguous), or `;` from the second layer on. `%u` escapes, a decoded layer that is not +/// valid UTF-8 (overlong forms such as `%c0%ae` included) and a path still decodable after +/// [`MAX_DECODE_LAYERS`] layers are refused. A `.` or `..` segment is refused in every layer, +/// also with a path parameter (`..;x`, and `..%3b`, which a decode-then-strip stack reads as +/// `..;`). Raw empty interior segments (`//`), backslash and bytes the forwarder would +/// percent-encode (non-ASCII, controls, space, DEL, `"`, `<`, `>`, backtick, `{`, `}`) are +/// refused too, because for those the matched path would not be the path that is sent. pub fn path_ambiguous(p: &str) -> bool { - let lower = p.to_ascii_lowercase(); - if ["%2e", "%2f", "%5c", "%00"] - .iter() - .any(|s| lower.contains(s)) - || p.contains('\\') + if p.contains('\\') + || p.bytes() + .any(|b| b <= 0x20 || b >= 0x7f || b"\"<>`{}".contains(&b)) { return true; } - if p.bytes() - .any(|b| b <= 0x20 || b >= 0x7f || b"\"<>`{}".contains(&b)) + let segs: Vec<&str> = p.split('/').skip(1).collect(); + if segs + .iter() + .enumerate() + .any(|(i, s)| s.is_empty() && i + 1 != segs.len()) { return true; } - if lower.match_indices("%25").any(|(i, _)| { - let rest = &lower[i + 3..]; - rest.starts_with("2e") || rest.starts_with("2f") - }) || encodes_separator_in_layers(lower.as_bytes()) - { + let mut cur = p.as_bytes().to_vec(); + if dot_segment(&cur) { return true; } - let segs: Vec<&str> = p.split('/').skip(1).collect(); - segs.iter().enumerate().any(|(i, s)| { - let name = s.split(';').next().unwrap_or_default(); - name == "." || name == ".." || (s.is_empty() && i + 1 != segs.len()) - }) -} - -/// True when percent-decoding `lower` (already ASCII-lowercased) one to three times exposes -/// `%2e`, `%2f`, `%5c` or `%00`: a second or third decoder would then read a dot, slash, -/// backslash or NUL that the first layer hid. -fn encodes_separator_in_layers(lower: &[u8]) -> bool { - let mut cur = lower.to_vec(); - for _ in 0..3 { + for depth in 1..=MAX_DECODE_LAYERS { let mut out = Vec::with_capacity(cur.len()); + let mut decoded = false; let mut i = 0; while i < cur.len() { - let hex = |b: u8| (b as char).to_digit(16); - if cur[i] == b'%' && i + 2 < cur.len() { - if let (Some(h), Some(l)) = (hex(cur[i + 1]), hex(cur[i + 2])) { - out.push(u8::try_from(h * 16 + l).unwrap_or(b'%')); + if cur[i] == b'%' { + if cur + .get(i + 1) + .is_some_and(|c| c.eq_ignore_ascii_case(&b'u')) + && cur.len() >= i + 6 + && cur[i + 2..i + 6].iter().all(u8::is_ascii_hexdigit) + { + return true; + } + if let Some(b) = hex_pair(&cur, i) { + if b < 0x20 + || b == 0x7f + || matches!(b, b'.' | b'/' | b'\\') + || (depth >= 2 && b == b';') + { + return true; + } + out.push(b); + decoded = true; i += 3; continue; } } - out.push(cur[i].to_ascii_lowercase()); + out.push(cur[i]); i += 1; } - if [&b"%2e"[..], b"%2f", b"%5c", b"%00"] - .iter() - .any(|s| out.windows(s.len()).any(|w| w == *s)) - { - return true; - } - if !out.contains(&b'%') { + if !decoded { return false; } + if std::str::from_utf8(&out).is_err() || dot_segment(&out) { + return true; + } cur = out; } - false + (0..cur.len()).any(|i| cur[i] == b'%' && hex_pair(&cur, i).is_some()) +} + +fn hex_pair(b: &[u8], i: usize) -> Option { + let d = |j: usize| b.get(j).and_then(|c| (*c as char).to_digit(16)); + u8::try_from(d(i + 1)? * 16 + d(i + 2)?).ok() +} + +/// A `.` or `..` segment, ignoring any `;` path parameter (a servlet container reads `..;x` +/// as `..`). +fn dot_segment(p: &[u8]) -> bool { + p.split(|&c| c == b'/').skip(1).any(|s| { + let name = s.split(|&c| c == b';').next().unwrap_or_default(); + name == b"." || name == b".." + }) } /// The parts of a `/ap///` path. diff --git a/crates/ap-core/tests/canon_differential.rs b/crates/ap-core/tests/canon_differential.rs index 84651ea..7247dd2 100644 --- a/crates/ap-core/tests/canon_differential.rs +++ b/crates/ap-core/tests/canon_differential.rs @@ -32,10 +32,87 @@ const SEED: u64 = 0x19C0_FFEE_5EED; const KEY: &str = "apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; const PATH_ATOMS: &[&str] = &[ - "a", "v1", "echo", "x", "..", ".", "...", "%2e", "%2E", "%2f", "%2F", "%5c", "%5C", "%00", - "%25", "%252f", "%252e", "%2525", "%", "%zz", "%e", ";", "a;b", "..;", ".;", "..;x", ";..", - "\\", "{", "}", "|", "^", "\"", "<", ">", "`", "[", "]", "@", ":", "*", "~", "é", "ap", "apk_", - "?", "#", "+", "=", "&", "!", "$", "'", "(", ")", ",", "-", "_", + "a", + "v1", + "echo", + "x", + "..", + ".", + "...", + "%2e", + "%2E", + "%2f", + "%2F", + "%5c", + "%5C", + "%00", + "%25", + "%252f", + "%252e", + "%2525", + "%", + "%zz", + "%e", + ";", + "a;b", + "..;", + ".;", + "..;x", + ";..", + "\\", + "{", + "}", + "|", + "^", + "\"", + "<", + ">", + "`", + "[", + "]", + "@", + ":", + "*", + "~", + "é", + "ap", + "apk_", + "?", + "#", + "+", + "=", + "&", + "!", + "$", + "'", + "(", + ")", + ",", + "-", + "_", + "%3b", + "%3B", + "%253b", + "..%3b", + ".%3b", + "..%3B", + ".%3b.", + "%25%32%46", + "%25%32%45", + "%25%35%43", + "%2%45", + "%c0%ae", + "%c0%af", + "%e0%80%ae", + "%ff", + "%u002e", + "%0a", + "%250a", + "%25%30%30", + "%2525252e", + "%41", + "%C3%A9", + "%20", ]; const SEPS: &[&str] = &["/", "/", "/", "", "//", "/"]; diff --git a/crates/ap-core/tests/canon_regression.rs b/crates/ap-core/tests/canon_regression.rs index 5f6bc70..d527556 100644 --- a/crates/ap-core/tests/canon_regression.rs +++ b/crates/ap-core/tests/canon_regression.rs @@ -87,6 +87,106 @@ fn path_encoding_classes_are_refused() { ambiguous_all("empty interior segment", &["//x", "/v1//x", "/a///b"]); } +#[test] +fn layered_and_mixed_case_encodings_are_refused() { + ambiguous_all( + "layered encodings, any hex case", + &[ + "/v1/%25%32%46admin", + "/v1/%25%32%66admin", + "/v1/%25%32%45%25%32%45/admin", + "/v1/%25%32%65%25%32%65/admin", + "/v1/%25%35%43admin", + "/v1/%25%35%63admin", + "/v1/%2%45", + "/v1/%2%65/x", + "/v1/%2%46x", + "/v1/%252E%252e/x", + "/v1/%25252e", + "/v1/%25%32%35%32%66", + "/v1/%252525252e%252525252e/admin", + "/v1/%2525252525x", + "/v1/%25%33%62", + "/v1/%2525%33%62", + ], + ); + ambiguous_all( + "encoded NUL and control characters, any layer", + &[ + "/v1/%00", + "/v1/%0a", + "/v1/%0D", + "/v1/%1f", + "/v1/%7f", + "/v1/%7F", + "/v1/%2500", + "/v1/%250a", + "/v1/%25%30%30", + "/v1/%25%30%61", + "/v1/%25%37%46", + ], + ); + ambiguous_all( + "overlong, invalid and IIS-style UTF-8", + &[ + "/v1/%c0%ae", + "/v1/%C0%AE%C0%AE/x", + "/v1/%c0%af", + "/v1/%c1%9c", + "/v1/%e0%80%ae", + "/v1/%e0%80%af", + "/v1/%f0%80%80%ae", + "/v1/%ff", + "/v1/%80", + "/v1/%c3", + "/v1/%ed%a0%80", + "/v1/%u002e", + "/v1/%U002E", + "/v1/%u002f", + "/v1/%u005c", + ], + ); +} + +#[test] +fn encoded_semicolon_on_dot_segments_is_refused() { + ambiguous_all( + "encoded `;` makes a dot segment carry a parameter", + &[ + "/v1/..%3b/admin", + "/v1/..%3B/admin", + "/v1/.%3b/x", + "/v1/.%3B", + "/v1/..%3bx/admin", + "/v1/..%3Bx", + "/v1/.%3b.", + "/v1/.%3b./x", + "/v1/..%3b%2f", + "/v1/..%3b%2fadmin", + "/v1/%2e%2e%3b/admin", + "/v1/%2e%2e%3B", + "/v1/..%253b/admin", + "/v1/..%253B/admin", + "/v1/.%253b/x", + "/v1/..%25%33%62/x", + "/..%3b/x", + "/v1/a/..%3b/b", + "/v1/..%3b%3b/x", + ], + ); + // `;` in every segment of a path that has no dot segment is data and passes. + for p in [ + "/a;b/c;d/e;f", + "/;/;/;", + "/v1/%3bx", + "/v1/a%3bb", + "/v1/a%3b", + "/v1/%3b..", + ] { + assert!(!path_ambiguous(p), "{p:?} must pass"); + } +} + #[test] fn ordinary_paths_pass_unchanged() { for p in [ @@ -103,6 +203,12 @@ fn ordinary_paths_pass_unchanged() { "/v1/%e2%82%ac", "/v1/%zz", "/v1/%", + "/v1/%2", + "/v1/%c3%a9", + "/v1/%C3%A9", + "/v1/%f0%9f%98%80", + "/v1/%2541", + "/v1/100%25%25", ] { assert!(!path_ambiguous(p), "{p:?} must pass"); } @@ -395,8 +501,8 @@ fn unicode_and_idn_never_reach_the_matcher() { } } assert!(Uri::from_str("http://exämple.com/x").is_err()); - // Overlong UTF-8 for `.` and `/` is plain ASCII on the wire: opaque bytes, not a dot. - assert!(!path_ambiguous("/v1/%C0%AE%C0%AE/x")); + // Overlong UTF-8 for `.` and `/` is read as a dot by lenient decoders: refused. + assert!(path_ambiguous("/v1/%C0%AE%C0%AE/x")); // Header values with obs-text are not valid UTF-8 text for our readers. let h = { let mut h = HeaderMap::new(); diff --git a/crates/ap-core/tests/common/invariants.rs b/crates/ap-core/tests/common/invariants.rs index 886d23a..cfd4b1b 100644 --- a/crates/ap-core/tests/common/invariants.rs +++ b/crates/ap-core/tests/common/invariants.rs @@ -84,6 +84,7 @@ pub fn check_path_against_parsers(p: &str) { /// Everything about a request path that must hold for any string. pub fn check_path(p: &str) { check_ap_path(p); + check_decode_oracle(p); check_path_against_parsers(p); } @@ -213,3 +214,76 @@ pub fn check_origin(target: &str, hosts: &[Vec], http2: bool, expected: &str } assert!(!expected.contains('@')); } + +/// Independent oracle for the layered-decode rule. It decodes to a fixed point with a different +/// implementation (char-level, each byte carrying the depth that produced it) and states what +/// must be refused: a dot, slash, backslash, NUL or control byte produced by any decode, a +/// semicolon produced from the second layer on, a `.`/`..` segment (before any `;`) in any +/// layer, and an escape still decodable after four layers. If the oracle demands refusal, +/// `path_ambiguous` must refuse; the reverse is not asserted because the production rule also +/// refuses bytes the forwarder would re-encode, `%u` escapes and invalid UTF-8. +pub fn check_decode_oracle(p: &str) { + if oracle_must_refuse(p) { + assert!( + path_ambiguous(p), + "decode oracle demands refusal but path_ambiguous accepted {p:?}" + ); + } +} + +fn oracle_must_refuse(p: &str) -> bool { + // (byte, depth that produced it; 0 = literal) + let mut layer: Vec<(u8, usize)> = p.bytes().map(|b| (b, 0)).collect(); + for depth in 1..=4 { + if has_dot_segment(&layer) { + return true; + } + let mut next = Vec::new(); + let mut changed = false; + let mut i = 0; + while i < layer.len() { + let esc = (layer[i].0 == b'%' && i + 2 < layer.len()) + .then(|| { + let hex: String = layer[i + 1..i + 3].iter().map(|x| x.0 as char).collect(); + (hex.len() == 2 && hex.chars().all(|c| c.is_ascii_hexdigit())) + .then(|| u8::from_str_radix(&hex, 16).unwrap()) + }) + .flatten(); + match esc { + Some(b) => { + if matches!(b, 0 | b'.' | b'/' | b'\\') || b < 0x20 || b == 0x7f { + return true; + } + if b == b';' && depth >= 2 { + return true; + } + next.push((b, depth)); + changed = true; + i += 3; + } + None => { + next.push(layer[i]); + i += 1; + } + } + } + if !changed { + return false; + } + layer = next; + } + has_dot_segment(&layer) + || (0..layer.len()).any(|i| { + layer[i].0 == b'%' + && layer.len() > i + 2 + && layer[i + 1].0.is_ascii_hexdigit() + && layer[i + 2].0.is_ascii_hexdigit() + }) +} + +fn has_dot_segment(layer: &[(u8, usize)]) -> bool { + let text: String = layer.iter().map(|x| x.0 as char).collect(); + text.split('/') + .skip(1) + .any(|seg| matches!(seg.split(';').next(), Some(".") | Some(".."))) +} diff --git a/crates/ap-proxy/src/canon_diff_tests.rs b/crates/ap-proxy/src/canon_diff_tests.rs index 53c2b09..219d092 100644 --- a/crates/ap-proxy/src/canon_diff_tests.rs +++ b/crates/ap-proxy/src/canon_diff_tests.rs @@ -33,10 +33,77 @@ impl Rng { } const ATOMS: &[&str] = &[ - "a", "v1", "msg", "..", ".", "...", "%2e", "%2E", "%2f", "%5c", "%00", "%25", "%252f", "%255c", - "%2500", "%", "%zz", ";", "a;b", "..;", ".;x", "\\", "{", "}", "|", "^", "\"", "<", ">", "`", - "[", "]", "@", ":", "*", "~", "é", "\u{ff0e}", "%C3%A9", "%41", "+", "=", "&", "!", "$", "'", - "(", ")", ",", "-", "_", "ap", "up", "%20", " ", + "a", + "v1", + "msg", + "..", + ".", + "...", + "%2e", + "%2E", + "%2f", + "%5c", + "%00", + "%25", + "%252f", + "%255c", + "%2500", + "%", + "%zz", + ";", + "a;b", + "..;", + ".;x", + "\\", + "{", + "}", + "|", + "^", + "\"", + "<", + ">", + "`", + "[", + "]", + "@", + ":", + "*", + "~", + "é", + "\u{ff0e}", + "%C3%A9", + "%41", + "+", + "=", + "&", + "!", + "$", + "'", + "(", + ")", + ",", + "-", + "_", + "ap", + "up", + "%20", + " ", + "%3b", + "%3B", + "%253b", + "..%3b", + ".%3b", + ".%3b.", + "%25%32%46", + "%25%32%45", + "%25%35%43", + "%2%45", + "%c0%ae", + "%e0%80%af", + "%ff", + "%u002e", + "%0a", + "%2525252e", ]; const SEPS: &[&str] = &["/", "/", "/", "", "//"]; @@ -83,13 +150,11 @@ async fn matched_path_is_the_forwarded_path() { let body = to_bytes(resp.into_body(), 1 << 20).await.expect("body"); if status != 200 { refused += 1; - if status != 502 { - assert_eq!( - up.hits.load(Ordering::SeqCst), - hits_before, - "#{i} {target:?}: refused with {status} but upstream was contacted" - ); - } + assert_eq!( + up.hits.load(Ordering::SeqCst), + hits_before, + "#{i} {target:?}: refused with {status} but upstream was contacted" + ); continue; } forwarded += 1; diff --git a/fuzz/corpus/canon_path/double-pct b/fuzz/corpus/canon_path/double-pct new file mode 100644 index 0000000..a62850d --- /dev/null +++ b/fuzz/corpus/canon_path/double-pct @@ -0,0 +1 @@ +/v1/100%25%25 \ No newline at end of file diff --git a/fuzz/corpus/canon_path/encoded-ctl b/fuzz/corpus/canon_path/encoded-ctl new file mode 100644 index 0000000..894d83a --- /dev/null +++ b/fuzz/corpus/canon_path/encoded-ctl @@ -0,0 +1 @@ +/v1/%0a \ No newline at end of file diff --git a/fuzz/corpus/canon_path/encoded-del b/fuzz/corpus/canon_path/encoded-del new file mode 100644 index 0000000..23745a4 --- /dev/null +++ b/fuzz/corpus/canon_path/encoded-del @@ -0,0 +1 @@ +/v1/%7F \ No newline at end of file diff --git a/fuzz/corpus/canon_path/encoded-semi-dot b/fuzz/corpus/canon_path/encoded-semi-dot new file mode 100644 index 0000000..587435e --- /dev/null +++ b/fuzz/corpus/canon_path/encoded-semi-dot @@ -0,0 +1 @@ +/v1/.%3B/x \ No newline at end of file diff --git a/fuzz/corpus/canon_path/encoded-semi-dotdot b/fuzz/corpus/canon_path/encoded-semi-dotdot new file mode 100644 index 0000000..f49a599 --- /dev/null +++ b/fuzz/corpus/canon_path/encoded-semi-dotdot @@ -0,0 +1 @@ +/ap/apk_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef/up/v1/..%3b/admin \ No newline at end of file diff --git a/fuzz/corpus/canon_path/encoded-semi-dots-enc b/fuzz/corpus/canon_path/encoded-semi-dots-enc new file mode 100644 index 0000000..6ce85e6 --- /dev/null +++ b/fuzz/corpus/canon_path/encoded-semi-dots-enc @@ -0,0 +1 @@ +/v1/%2e%2e%3b/x \ No newline at end of file diff --git a/fuzz/corpus/canon_path/encoded-semi-mid b/fuzz/corpus/canon_path/encoded-semi-mid new file mode 100644 index 0000000..2e44710 --- /dev/null +++ b/fuzz/corpus/canon_path/encoded-semi-mid @@ -0,0 +1 @@ +/v1/.%3b./x \ No newline at end of file diff --git a/fuzz/corpus/canon_path/encoded-semi-nested b/fuzz/corpus/canon_path/encoded-semi-nested new file mode 100644 index 0000000..c8a777b --- /dev/null +++ b/fuzz/corpus/canon_path/encoded-semi-nested @@ -0,0 +1 @@ +/v1/..%253b/admin \ No newline at end of file diff --git a/fuzz/corpus/canon_path/encoded-semi-slash b/fuzz/corpus/canon_path/encoded-semi-slash new file mode 100644 index 0000000..92280b4 --- /dev/null +++ b/fuzz/corpus/canon_path/encoded-semi-slash @@ -0,0 +1 @@ +/v1/..%3b%2f \ No newline at end of file diff --git a/fuzz/corpus/canon_path/five-layer-dot b/fuzz/corpus/canon_path/five-layer-dot new file mode 100644 index 0000000..d57e912 --- /dev/null +++ b/fuzz/corpus/canon_path/five-layer-dot @@ -0,0 +1 @@ +/v1/%252525252e%252525252e/admin \ No newline at end of file diff --git a/fuzz/corpus/canon_path/iis-unicode b/fuzz/corpus/canon_path/iis-unicode new file mode 100644 index 0000000..24a8cda --- /dev/null +++ b/fuzz/corpus/canon_path/iis-unicode @@ -0,0 +1 @@ +/v1/%u002e \ No newline at end of file diff --git a/fuzz/corpus/canon_path/layered-backslash-upper b/fuzz/corpus/canon_path/layered-backslash-upper new file mode 100644 index 0000000..071bda4 --- /dev/null +++ b/fuzz/corpus/canon_path/layered-backslash-upper @@ -0,0 +1 @@ +/v1/%25%35%43admin \ No newline at end of file diff --git a/fuzz/corpus/canon_path/layered-dots-upper b/fuzz/corpus/canon_path/layered-dots-upper new file mode 100644 index 0000000..a0e2637 --- /dev/null +++ b/fuzz/corpus/canon_path/layered-dots-upper @@ -0,0 +1 @@ +/v1/%25%32%45%25%32%45/admin \ No newline at end of file diff --git a/fuzz/corpus/canon_path/layered-nul b/fuzz/corpus/canon_path/layered-nul new file mode 100644 index 0000000..3beee5a --- /dev/null +++ b/fuzz/corpus/canon_path/layered-nul @@ -0,0 +1 @@ +/v1/%25%30%30 \ No newline at end of file diff --git a/fuzz/corpus/canon_path/layered-slash-upper b/fuzz/corpus/canon_path/layered-slash-upper new file mode 100644 index 0000000..d09201d --- /dev/null +++ b/fuzz/corpus/canon_path/layered-slash-upper @@ -0,0 +1 @@ +/v1/%25%32%46admin \ No newline at end of file diff --git a/fuzz/corpus/canon_path/overlong-dot b/fuzz/corpus/canon_path/overlong-dot new file mode 100644 index 0000000..f944d62 --- /dev/null +++ b/fuzz/corpus/canon_path/overlong-dot @@ -0,0 +1 @@ +/v1/%c0%ae%c0%ae/x \ No newline at end of file diff --git a/fuzz/corpus/canon_path/overlong-slash b/fuzz/corpus/canon_path/overlong-slash new file mode 100644 index 0000000..3b1d41e --- /dev/null +++ b/fuzz/corpus/canon_path/overlong-slash @@ -0,0 +1 @@ +/v1/%e0%80%af \ No newline at end of file diff --git a/fuzz/corpus/canon_path/partial-escape b/fuzz/corpus/canon_path/partial-escape new file mode 100644 index 0000000..32608b0 --- /dev/null +++ b/fuzz/corpus/canon_path/partial-escape @@ -0,0 +1 @@ +/v1/%2%45 \ No newline at end of file diff --git a/fuzz/corpus/canon_path/valid-utf8 b/fuzz/corpus/canon_path/valid-utf8 new file mode 100644 index 0000000..fe8d155 --- /dev/null +++ b/fuzz/corpus/canon_path/valid-utf8 @@ -0,0 +1 @@ +/v1/%C3%A9 \ No newline at end of file diff --git a/tests/matrix/matrix.py b/tests/matrix/matrix.py index e9b333f..829059e 100644 --- a/tests/matrix/matrix.py +++ b/tests/matrix/matrix.py @@ -821,7 +821,10 @@ def _(e): s = e.mint("agent-1", ("c-up",)) au = [("Host", e.authority()), ("Authorization", f"Bearer {s}")] paths = ["/v1/%252f", "/v1/%252F", "/v1/%252e%252e/x", "/v1/%255c", "/v1/%2500", "/v1/%25%32%66", - "/v1%2fecho", "/v1/%2Fecho", "/v1/a%5cb", "/v1/a%5Cb", "/v1/a%00b", "/v1/a\\b"] + "/v1%2fecho", "/v1/%2Fecho", "/v1/a%5cb", "/v1/a%5Cb", "/v1/a%00b", "/v1/a\\b", + "/v1/%25%32%46admin", "/v1/%25%32%45%25%32%45/admin", "/v1/%25%35%43admin", "/v1/%2%45", + "/v1/%252525252e%252525252e/admin", "/v1/%0a", "/v1/%25%30%30", "/v1/%c0%ae%c0%ae/x", + "/v1/%e0%80%af", "/v1/%u002e", "/v1/%ff"] return canon_run([canon_refused(e, p, f"GET {e.ap('up', p)} HTTP/1.1", au, {"path_ambiguous"}) for p in paths]) @@ -831,8 +834,10 @@ def _(e): s = e.mint("agent-1", ("c-up",)) au = [("Host", e.authority()), ("Authorization", f"Bearer {s}")] checks = [canon_refused(e, p, f"GET {e.ap('up', p)} HTTP/1.1", au, {"path_ambiguous"}) - for p in ["/v1/..;/admin", "/v1/..;x/admin", "/v1/.;/x", "/v1/..;a=b/x"]] - for p in ["/v1/a;b=c", "/v1/a;b/echo", "/v1/;x/echo"]: + for p in ["/v1/..;/admin", "/v1/..;x/admin", "/v1/.;/x", "/v1/..;a=b/x", + "/v1/..%3b/admin", "/v1/..%3B/admin", "/v1/.%3b/x", "/v1/.%3b./x", + "/v1/..%3b%2f", "/v1/%2e%2e%3b/x", "/v1/..%253b/admin"]] + for p in ["/v1/a;b=c", "/v1/a;b/echo", "/v1/;x/echo", "/v1/a%3bb/echo"]: checks.append(canon_forwarded_identical(e, p, f"GET {e.ap('up', p)} HTTP/1.1", au, p)) return canon_run(checks) diff --git a/tests/matrix/passthrough.py b/tests/matrix/passthrough.py index bbe3cb9..f6123eb 100644 --- a/tests/matrix/passthrough.py +++ b/tests/matrix/passthrough.py @@ -664,7 +664,11 @@ def get(path, key=k): checks = [] for p in ["/discord/v1/%252f", "/discord/v1/%255c", "/discord/v1/%2500", "/discord/v1%2fx", "/discord/v1/%5cx", "/discord/v1/..;/x", "/discord/v1/.;/x", "/discord/v1/{x}", '/discord/v1/a"b', - "/discord/v1/caf\u00e9", "/discord/v1/\uff0e\uff0e/x"]: + "/discord/v1/caf\u00e9", "/discord/v1/\uff0e\uff0e/x", + "/discord/v1/..%3b/x", "/discord/v1/.%3B/x", "/discord/v1/..%253b/x", + "/discord/v1/%25%32%46x", "/discord/v1/%25%32%45%25%32%45/x", "/discord/v1/%25%35%43x", + "/discord/v1/%2%45", "/discord/v1/%252525252e/x", "/discord/v1/%0a", + "/discord/v1/%c0%ae/x", "/discord/v1/%u002e"]: checks.append(canon_refused(c, p, get(p), None if not p.isascii() else {"path_ambiguous"})) for label, key in [("empty key", ""), ("key %2f", k + "%2f"), ("key ;", k + ";x"), ("key upper", k.upper()), ("key short", k[:-1]), ("key long", k + "0")]: