diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f70b57a..7e4e010 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,14 +30,26 @@ jobs: - name: Clippy run: cargo clippy --workspace --all-targets -- -D warnings + - name: Clippy (stage1-probe) + run: cargo clippy -p ap-proxy --all-targets --features stage1-probe -- -D warnings + - name: Unit and integration tests run: cargo test --workspace + - name: Unit tests (stage1-probe) + run: cargo test -p ap-proxy --features stage1-probe --lib + - name: Release build (default features; the matrix-upstream feature stays off) run: cargo build --release -p ap-proxy -p ap-egress -p ap-runtime-shim - name: Release binaries carry no test hooks run: | + if grep -q __ap_probe target/release/auth-proxy; then + echo "probe route string found in the release auth-proxy"; exit 1 + fi + if grep -q __ap_test_panic target/release/auth-proxy; then + echo "panic-injection string found in the release auth-proxy"; exit 1 + fi if grep -q AP_TEST_UPSTREAM_CA target/release/auth-proxy; then echo "test hook strings found in the release auth-proxy"; exit 1 fi @@ -55,7 +67,7 @@ jobs: fi - name: Build test binaries (matrix-upstream feature; debug profile, default target dir) - run: cargo build -p ap-proxy -p ap-egress --features ap-proxy/matrix-upstream,ap-egress/matrix-upstream + run: cargo build -p ap-proxy -p ap-egress --features ap-proxy/matrix-upstream,ap-proxy/stage1-probe,ap-egress/matrix-upstream - name: Matrix cargo target (fails unless every row is PASS) run: cargo test -p ap-proxy --features matrix-upstream --test matrix @@ -65,6 +77,14 @@ jobs: set -o pipefail python3 tests/matrix/matrix.py --bin target/debug --json matrix.json | tee matrix.txt + - name: Passthrough matrix cargo target (Muse gate, stage 1) + run: cargo test -p ap-proxy --features matrix-upstream,stage1-probe --test matrix_passthrough + + - name: Passthrough matrix driver (writes matrix-pt.json and matrix-pt.txt) + run: | + set -o pipefail + python3 tests/matrix/passthrough.py --bin target/debug --json matrix-pt.json | tee matrix-pt.txt + - name: Upload matrix results if: always() uses: actions/upload-artifact@v4 @@ -73,3 +93,5 @@ jobs: path: | matrix.json matrix.txt + matrix-pt.json + matrix-pt.txt diff --git a/README.md b/README.md index 6c40f57..fcb2ec9 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,18 @@ control to credential control, in two sub-shapes. This mode is **under development** and is not part of Phase 1; its first consumer is tracked in [#5](https://github.com/openabdev/auth-proxy/issues/5). +## Muse gated passthrough (stage 1, pilot) + +A second mode for one consumer (Muse) and one upstream (Discord): the caller's own `Authorization` +passes through unchanged and the gate only decides allow or deny. The caller key travels in a header, +the route is a path prefix mapped by policy to a fixed host, reads on granted prefixes pass, and +everything else (writes included) is refused with 423 `no_grant` and an `X-AP-Decision` header. It +needs no session machinery and does not change the sidecar mode. + +The gate constrains the agent, not the Muse platform: Muse's egress holds the real Discord token and +can call Discord directly. See `docs/design/muse-gated-passthrough.md`, `docs/runbooks/muse-stage1.md` +and `deploy/muse/pilot-policy.example.toml`. + ## Features Implemented and tested in Phase 1: diff --git a/crates/ap-core/src/canon.rs b/crates/ap-core/src/canon.rs index 2ec8794..09f5a96 100644 --- a/crates/ap-core/src/canon.rs +++ b/crates/ap-core/src/canon.rs @@ -151,10 +151,126 @@ pub fn parse_ap_path(path: &str) -> Result, Code> { }) } -fn is_caller_key(k: &str) -> bool { +pub fn is_caller_key(k: &str) -> bool { k.strip_prefix("apk_").is_some_and(is_lower_hex_64) } +/// Split `//` into the route name and the route-relative path. +/// +/// The first segment must be `[a-z0-9-]{1,32}`, else `route_unknown`. A missing rest is `/`. +pub fn parse_route_path(path: &str) -> Result<(&str, String), Code> { + let rest = path.strip_prefix('/').ok_or(Code::RouteUnknown)?; + let (route, tail) = match rest.split_once('/') { + Some((r, t)) => (r, format!("/{t}")), + None => (rest, "/".to_string()), + }; + let ok = !route.is_empty() + && route.len() <= 32 + && route + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'); + if !ok { + return Err(Code::RouteUnknown); + } + Ok((route, tail)) +} + +/// Read the caller key from exactly one value of `name`, in the form `apk_<64 lowercase hex>`. +/// +/// Missing, duplicate, non-UTF-8 and malformed values are all `caller_rejected`. The value is +/// never formatted into a message. +pub fn caller_key_from_header(headers: &HeaderMap, name: &str) -> Result { + let mut values = headers.get_all(name).iter(); + let value = match (values.next(), values.next()) { + (Some(v), None) => v, + _ => return Err(Code::CallerRejected), + }; + let s = value.to_str().map_err(|_| Code::CallerRejected)?; + if !is_caller_key(s) { + return Err(Code::CallerRejected); + } + Ok(s.to_string()) +} + +/// True when the request framing is ambiguous and must be refused before policy runs. +/// +/// Refused: `Content-Length` with `Transfer-Encoding`; more than one `Content-Length`; a +/// `Content-Length` that is not plain digits (a comma list, a sign, blanks); a +/// `Transfer-Encoding` other than a single `chunked`; a `Connection` header that nominates a +/// framing header, `Host`, `Authorization` or the caller-key header. +pub fn framing_refused(headers: &HeaderMap, caller_key_header: &str) -> bool { + let cl: Vec<_> = headers + .get_all(http::header::CONTENT_LENGTH) + .iter() + .collect(); + let te: Vec<_> = headers + .get_all(http::header::TRANSFER_ENCODING) + .iter() + .collect(); + if !cl.is_empty() && !te.is_empty() { + return true; + } + if cl.len() > 1 { + return true; + } + if let Some(v) = cl.first() { + let digits = v + .to_str() + .map(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) + .unwrap_or(false); + if !digits { + return true; + } + } + if !te.is_empty() { + let single_chunked = te.len() == 1 + && te[0] + .to_str() + .map(|s| s.eq_ignore_ascii_case("chunked")) + .unwrap_or(false); + if !single_chunked { + return true; + } + } + for v in headers.get_all(http::header::CONNECTION) { + let Ok(s) = v.to_str() else { + return true; + }; + for tok in s.split(',') { + let t = tok.trim().to_ascii_lowercase(); + if matches!( + t.as_str(), + "content-length" | "transfer-encoding" | "host" | "authorization" + ) || t == caller_key_header + { + return true; + } + } + } + false +} + +/// Replace the secret token segment of Discord webhook and interaction paths with ``. +/// +/// Matches `webhooks//` and `interactions//` at any depth. The rest of +/// the path is kept. A path with no such prefix is returned unchanged. +pub fn redact_path(path: &str) -> String { + let segs: Vec<&str> = path.split('/').collect(); + let mut out: Vec<&str> = Vec::with_capacity(segs.len()); + let mut i = 0; + while i < segs.len() { + out.push(segs[i]); + if (segs[i] == "webhooks" || segs[i] == "interactions") && i + 2 < segs.len() { + out.push(segs[i + 1]); + out.push(""); + i += 3; + } else { + i += 1; + } + } + out.join("/") +} + /// True for exactly 64 lowercase hex characters (sha256 hex, or the key and surrogate digests). pub fn is_lower_hex_64(s: &str) -> bool { s.len() == 64 @@ -519,4 +635,103 @@ mod tests { ); } } + + #[test] + fn route_path_splits_and_refuses() { + assert_eq!( + parse_route_path("/discord/api/v10/x"), + Ok(("discord", "/api/v10/x".to_string())) + ); + assert_eq!( + parse_route_path("/discord"), + Ok(("discord", "/".to_string())) + ); + assert_eq!(parse_route_path("/"), Err(Code::RouteUnknown)); + assert_eq!(parse_route_path("//x"), Err(Code::RouteUnknown)); + assert_eq!(parse_route_path("/Disc/x"), Err(Code::RouteUnknown)); + assert_eq!( + parse_route_path(&format!("/{}/x", "a".repeat(33))), + Err(Code::RouteUnknown) + ); + } + + #[test] + fn caller_key_header_rules() { + let n = "x-ap-caller-key"; + let mut h = HeaderMap::new(); + assert_eq!(caller_key_from_header(&h, n), Err(Code::CallerRejected)); + h.append(n, HeaderValue::from_static(KEY)); + assert_eq!(caller_key_from_header(&h, n), Ok(KEY.to_string())); + h.append(n, HeaderValue::from_static(KEY)); + assert_eq!(caller_key_from_header(&h, n), Err(Code::CallerRejected)); + let mut m = HeaderMap::new(); + m.insert(n, HeaderValue::from_static("apk_short")); + assert_eq!(caller_key_from_header(&m, n), Err(Code::CallerRejected)); + let mut m = HeaderMap::new(); + m.insert(n, HeaderValue::from_bytes(b"apk_\xff").unwrap()); + assert_eq!(caller_key_from_header(&m, n), Err(Code::CallerRejected)); + } + + fn hm(pairs: &[(&'static str, &'static str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append(*k, HeaderValue::from_static(v)); + } + h + } + + #[test] + fn framing_cases() { + let k = "x-ap-caller-key"; + assert!(!framing_refused(&hm(&[("content-length", "12")]), k)); + assert!(!framing_refused( + &hm(&[("transfer-encoding", "chunked")]), + k + )); + assert!(!framing_refused(&hm(&[]), k)); + assert!(!framing_refused(&hm(&[("connection", "keep-alive")]), k)); + for bad in [ + vec![("content-length", "1"), ("transfer-encoding", "chunked")], + vec![("content-length", "1"), ("content-length", "1")], + vec![("content-length", "1, 1")], + vec![("content-length", "+1")], + vec![("content-length", "")], + vec![("transfer-encoding", "gzip")], + vec![("transfer-encoding", "gzip, chunked")], + vec![ + ("transfer-encoding", "chunked"), + ("transfer-encoding", "chunked"), + ], + vec![("connection", "close, Content-Length")], + vec![("connection", "x-ap-caller-key")], + vec![("connection", "authorization")], + ] { + assert!(framing_refused(&hm(&bad), k), "{bad:?}"); + } + } + + #[test] + fn redacts_webhook_and_interaction_tokens() { + assert_eq!( + redact_path("/api/v10/webhooks/1/SECRET/github"), + "/api/v10/webhooks/1//github" + ); + assert_eq!( + redact_path("/api/v10/interactions/1/SECRET/callback"), + "/api/v10/interactions/1//callback" + ); + assert_eq!( + redact_path("/api/v10/webhooks/1/SECRET"), + "/api/v10/webhooks/1/" + ); + assert_eq!( + redact_path("/api/v10/channels/1/messages"), + "/api/v10/channels/1/messages" + ); + assert_eq!(redact_path("/api/v10/webhooks/1"), "/api/v10/webhooks/1"); + assert_eq!( + redact_path("/x/webhooks/1/S/interactions/2/T/c"), + "/x/webhooks/1//interactions/2//c" + ); + } } diff --git a/crates/ap-core/src/config.rs b/crates/ap-core/src/config.rs index a18aac3..5e7dd91 100644 --- a/crates/ap-core/src/config.rs +++ b/crates/ap-core/src/config.rs @@ -60,6 +60,105 @@ pub struct Config { pub grants: Vec, #[serde(default)] pub egress: Egress, + /// Passthrough settings. Required when any route has `mode = "passthrough"`. + #[serde(default)] + pub passthrough: Option, + #[serde(default)] + pub probe: Probe, +} + +/// How a route treats the request credential. +#[derive(Debug, Deserialize, Clone, Copy, Default, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum RouteMode { + /// Phase 1: swap the surrogate for the stored credential. + #[default] + Swap, + /// Muse gate: the caller's own `Authorization` is forwarded unchanged. + Passthrough, +} + +/// What a matching grant does. Stage 1 supports `allow` only. +#[derive(Debug, Deserialize, Clone, Copy, Default, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum Decision { + #[default] + Allow, + Hold, +} + +/// Settings for the public passthrough listener (design 3.1, 3.2, 3.7). +#[derive(Debug, Deserialize, Clone, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Passthrough { + /// The `Host` the front passes to the loopback listener. Replaces `listen.proxy` in the Host check. + pub public_authority: String, + #[serde(default = "default_caller_key_header")] + pub caller_key_header: String, + /// Lowercase header names the front adds. A trailing `*` makes the entry a prefix. + #[serde(default = "default_front_strip_headers")] + pub front_strip_headers: Vec, + /// Concurrent connections, 1..=65535. + #[serde(default = "default_max_connections")] + pub max_connections: usize, + /// Header read timeout, 1..=300. + #[serde(default = "default_header_read_secs")] + pub header_read_secs: u64, + /// Per-chunk stall limit on request bodies, 1..=300. + #[serde(default = "default_body_read_secs")] + pub body_read_secs: u64, + /// First byte to last response byte, 1..=3600. + #[serde(default = "default_request_deadline_secs")] + pub request_deadline_secs: u64, + /// No byte from upstream, 1..=3600. + #[serde(default = "default_upstream_idle_secs")] + pub upstream_idle_secs: u64, +} + +fn default_caller_key_header() -> String { + "x-ap-caller-key".to_string() +} + +fn default_front_strip_headers() -> Vec { + [ + "forwarded", + "x-forwarded-*", + "x-real-ip", + "via", + "cf-*", + "tailscale-*", + ] + .iter() + .map(|s| (*s).to_string()) + .collect() +} + +fn default_max_connections() -> usize { + 256 +} + +fn default_header_read_secs() -> u64 { + 10 +} + +fn default_body_read_secs() -> u64 { + 15 +} + +fn default_request_deadline_secs() -> u64 { + 300 +} + +fn default_upstream_idle_secs() -> u64 { + 30 +} + +/// The stage 1 hold-tolerance probe. Off unless `enabled`, and only built with the +/// `stage1-probe` feature of ap-proxy. +#[derive(Debug, Deserialize, Clone, Copy, Default, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct Probe { + pub enabled: bool, } /// The single loopback listener of the credential proxy. @@ -133,6 +232,12 @@ pub struct Route { pub credential_header: String, #[serde(default)] pub pass_headers: Vec, + #[serde(default)] + pub mode: RouteMode, + /// Passthrough routes only: members of `AUTH_HEADERS` (other than `authorization`) that are + /// forwarded. Default empty. + #[serde(default)] + pub keep_auth_headers: Vec, } #[derive(Debug, Deserialize, Clone)] @@ -148,12 +253,17 @@ pub struct Credential { #[serde(deny_unknown_fields)] pub struct Grant { pub identity: String, + /// Required on swap routes, forbidden on passthrough routes (empty). + #[serde(default)] pub credential: String, pub route: String, pub methods: Vec, pub paths: Vec, #[serde(default)] pub aws_targets: Vec, + /// `allow` (default). `hold` is not supported in stage 1. + #[serde(default)] + pub decision: Decision, } #[derive(Debug, Deserialize, Clone)] @@ -246,7 +356,86 @@ fn valid_path(p: &str) -> Result<(), &'static str> { Ok(()) } +/// Passthrough grant paths are plain prefixes (`starts_with`), so no trailing `/` is required. +/// Every other path rule still applies. +fn valid_prefix_path(p: &str) -> Result<(), &'static str> { + if !p.starts_with('/') { + return Err("must start with /"); + } + if p.contains('%') { + return Err("must not contain %"); + } + if p.contains("//") { + return Err("must not contain //"); + } + if p.split('/').any(|s| s == "." || s == "..") { + return Err("must not contain a dot segment"); + } + Ok(()) +} + +/// A lowercase header token, or one followed by a single `*` (prefix match). +fn valid_header_pattern(s: &str) -> bool { + let token = s.strip_suffix('*').unwrap_or(s); + valid_header_name(token) +} + +fn validate_passthrough(p: &Passthrough) -> Result<(), ConfigError> { + let a = &p.public_authority; + if a.is_empty() + || a.len() > 255 + || a.contains('@') + || a.contains('/') + || a.chars().any(char::is_whitespace) + { + return Err(invalid( + "passthrough.public_authority must be a non-empty host[:port] without @, / or whitespace", + )); + } + let h = &p.caller_key_header; + if !valid_header_name(h) + || AUTH_HEADERS.contains(&h.as_str()) + || HOP_HEADERS.contains(&h.as_str()) + { + return Err(invalid( + "passthrough.caller_key_header must be a lowercase header name that is not a credential or hop-by-hop header", + )); + } + if p.front_strip_headers.len() > 64 { + return Err(invalid( + "passthrough.front_strip_headers has too many entries", + )); + } + for e in &p.front_strip_headers { + if !valid_header_pattern(e) { + return Err(invalid(format!( + "passthrough.front_strip_headers entry {e:?} must be a lowercase header name, optionally ending in *" + ))); + } + } + if !(1..=65535).contains(&p.max_connections) { + return Err(invalid("passthrough.max_connections must be in 1..=65535")); + } + for (field, v, max) in [ + ("header_read_secs", p.header_read_secs, 300), + ("body_read_secs", p.body_read_secs, 300), + ("request_deadline_secs", p.request_deadline_secs, 3600), + ("upstream_idle_secs", p.upstream_idle_secs, 3600), + ] { + if !(1..=max).contains(&v) { + return Err(invalid(format!("passthrough.{field} must be in 1..={max}"))); + } + } + Ok(()) +} + impl Config { + /// True when every route is a passthrough route (and there is at least one). Such a + /// deployment runs without the session machinery. + pub fn is_passthrough_only(&self) -> bool { + !self.routes.is_empty() && self.routes.iter().all(|r| r.mode == RouteMode::Passthrough) + } + fn validate(&self) -> Result<(), ConfigError> { if self.version != 1 { return Err(invalid("version must be 1")); @@ -344,9 +533,76 @@ impl Config { ))); } } + match r.mode { + RouteMode::Swap => { + if !r.keep_auth_headers.is_empty() { + return Err(invalid(format!( + "route {:?}: keep_auth_headers is only for passthrough routes", + r.name + ))); + } + } + RouteMode::Passthrough => { + if r.name == "ap" { + return Err(invalid(format!( + "passthrough route name {:?} is reserved", + r.name + ))); + } + if r.error_shape != ErrorShape::Generic { + return Err(invalid(format!( + "route {:?}: a passthrough route needs error_shape generic", + r.name + ))); + } + if !r.pass_headers.is_empty() { + return Err(invalid(format!( + "route {:?}: a passthrough route must not set pass_headers", + r.name + ))); + } + for h in &r.keep_auth_headers { + if h == "authorization" || !AUTH_HEADERS.contains(&h.as_str()) { + return Err(invalid(format!( + "route {:?}: keep_auth_headers entry {h:?} must be a member of the credential header set other than authorization", + r.name + ))); + } + } + } + } route_hosts.insert(r.name.as_str(), r.host.as_str()); } + let passthrough_routes: HashSet<&str> = self + .routes + .iter() + .filter(|r| r.mode == RouteMode::Passthrough) + .map(|r| r.name.as_str()) + .collect(); + if !passthrough_routes.is_empty() && passthrough_routes.len() != self.routes.len() { + return Err(invalid( + "swap and passthrough routes cannot be mixed in one config in stage 1", + )); + } + match (&self.passthrough, passthrough_routes.is_empty()) { + (None, false) => { + return Err(invalid( + "a passthrough route needs a [passthrough] table with public_authority", + )) + } + (Some(_), true) => { + return Err(invalid( + "[passthrough] is only valid with a passthrough route", + )) + } + (Some(p), false) => validate_passthrough(p)?, + (None, true) => {} + } + if self.probe.enabled && passthrough_routes.is_empty() { + return Err(invalid("[probe] needs a passthrough deployment")); + } + let mut credential_ids = HashSet::new(); let mut credential_routes: HashMap<&str, HashSet<&str>> = HashMap::new(); for c in &self.credentials { @@ -373,6 +629,12 @@ impl Config { } let mut set = HashSet::new(); for r in &c.routes { + if passthrough_routes.contains(r.as_str()) { + return Err(invalid(format!( + "credential {:?} lists passthrough route {r:?}", + c.id + ))); + } if !route_hosts.contains_key(r.as_str()) { return Err(invalid(format!( "credential {:?} names unknown route {r:?}", @@ -399,19 +661,48 @@ impl Config { g.identity ))); } - let routes = credential_routes - .get(g.credential.as_str()) - .ok_or_else(|| { - invalid(format!("grant names unknown credential {:?}", g.credential)) - })?; - if !route_hosts.contains_key(g.route.as_str()) { - return Err(invalid(format!("grant names unknown route {:?}", g.route))); + let on_passthrough = passthrough_routes.contains(g.route.as_str()); + if on_passthrough { + if !g.credential.is_empty() { + return Err(invalid(format!( + "grant on passthrough route {:?} must not name a credential", + g.route + ))); + } + if !g.aws_targets.is_empty() { + return Err(invalid(format!( + "grant on passthrough route {:?} must not set aws_targets", + g.route + ))); + } + if g.decision != Decision::Allow { + return Err(invalid( + "grant decision \"hold\" is not supported yet (stage 1 allows or denies)", + )); + } + } else { + let routes = credential_routes + .get(g.credential.as_str()) + .ok_or_else(|| { + invalid(format!("grant names unknown credential {:?}", g.credential)) + })?; + if !route_hosts.contains_key(g.route.as_str()) { + return Err(invalid(format!("grant names unknown route {:?}", g.route))); + } + if !routes.contains(g.route.as_str()) { + return Err(invalid(format!( + "grant route {:?} is not in the route set of credential {:?}", + g.route, g.credential + ))); + } + if g.decision != Decision::Allow { + return Err(invalid( + "grant decision \"hold\" is not supported yet (stage 1 allows or denies)", + )); + } } - if !routes.contains(g.route.as_str()) { - return Err(invalid(format!( - "grant route {:?} is not in the route set of credential {:?}", - g.route, g.credential - ))); + if on_passthrough && !route_hosts.contains_key(g.route.as_str()) { + return Err(invalid(format!("grant names unknown route {:?}", g.route))); } if g.methods.is_empty() { return Err(invalid("grant methods must not be empty")); @@ -429,7 +720,12 @@ impl Config { return Err(invalid("grant paths must not be empty")); } for p in &g.paths { - valid_path(p).map_err(|why| invalid(format!("grant path {p:?}: {why}")))?; + let checked = if on_passthrough { + valid_prefix_path(p) + } else { + valid_path(p) + }; + checked.map_err(|why| invalid(format!("grant path {p:?}: {why}")))?; } for t in &g.aws_targets { let ok = !t.is_empty() && t.len() <= 256 && t.bytes().all(|b| b.is_ascii_graphic()); @@ -1066,4 +1362,228 @@ allow = ["github.com:443"] fn rejects_invalid_toml_syntax() { expect_parse_error("version = "); } + + fn pt_base() -> String { + format!( + r#"version = 1 + +[listen] +proxy = "127.0.0.1:8443" + +[passthrough] +public_authority = "gate.example.test" + +[[identity]] +name = "muse-pilot" +caller_key_sha256 = "{H64}" + +[[route]] +name = "discord" +host = "discord.com" +mode = "passthrough" + +[[grant]] +identity = "muse-pilot" +route = "discord" +methods = ["GET"] +paths = ["/api/v10/channels/", "/api/v10/users/@me"] +"# + ) + } + + #[test] + fn passthrough_only_config_loads() { + let cfg = load(&pt_base()).expect("valid"); + assert!(cfg.is_passthrough_only()); + let p = cfg.passthrough.as_ref().unwrap(); + assert_eq!(p.caller_key_header, "x-ap-caller-key"); + assert_eq!(p.max_connections, 256); + assert_eq!(p.header_read_secs, 10); + assert_eq!(p.body_read_secs, 15); + assert_eq!(p.request_deadline_secs, 300); + assert_eq!(p.upstream_idle_secs, 30); + assert!(p.front_strip_headers.iter().any(|h| h == "tailscale-*")); + assert_eq!(cfg.routes[0].mode, RouteMode::Passthrough); + assert_eq!(cfg.grants[0].decision, Decision::Allow); + assert!(cfg.grants[0].credential.is_empty()); + assert!(!cfg.probe.enabled); + } + + #[test] + fn swap_config_is_not_passthrough_only() { + assert!(!load(&base()).unwrap().is_passthrough_only()); + } + + #[test] + fn rejects_mixed_modes() { + let text = format!( + "{}\n[[route]]\nname = \"other\"\nhost = \"other.example.test\"\n", + pt_base() + ); + expect_invalid(&text, "cannot be mixed"); + } + + #[test] + fn rejects_credential_listing_a_passthrough_route() { + let text = format!( + "{}\n[[credential]]\nid = \"c\"\nsource = \"k8s:a:b\"\nroutes = [\"discord\"]\n", + pt_base() + ); + expect_invalid(&text, "lists passthrough route"); + } + + #[test] + fn rejects_passthrough_grant_with_credential() { + let text = pt_base().replace( + "methods = [\"GET\"]", + "credential = \"c\"\nmethods = [\"GET\"]", + ); + expect_invalid(&text, "must not name a credential"); + } + + #[test] + fn rejects_hold_decision_in_stage_1() { + let text = pt_base().replace( + "methods = [\"GET\"]", + "decision = \"hold\"\nmethods = [\"GET\"]", + ); + expect_invalid(&text, "not supported yet"); + } + + #[test] + fn rejects_unknown_decision_value() { + let text = pt_base().replace( + "methods = [\"GET\"]", + "decision = \"maybe\"\nmethods = [\"GET\"]", + ); + expect_parse_error(&text); + } + + #[test] + fn rejects_missing_passthrough_table() { + let text = pt_base().replace( + "[passthrough]\npublic_authority = \"gate.example.test\"\n", + "", + ); + expect_invalid(&text, "needs a [passthrough] table"); + } + + #[test] + fn rejects_passthrough_table_without_passthrough_route() { + let text = format!( + "{}\n[passthrough]\npublic_authority = \"gate.example.test\"\n", + base() + ); + expect_invalid(&text, "only valid with a passthrough route"); + } + + #[test] + fn rejects_unknown_key_under_passthrough() { + let text = pt_base().replace( + "public_authority = \"gate.example.test\"", + "public_authority = \"gate.example.test\"\nbogus = 1", + ); + expect_parse_error(&text); + } + + #[test] + fn passthrough_grant_path_needs_no_trailing_slash_but_swap_grant_does() { + assert!(load(&pt_base()).is_ok()); + let swap = base().replace("paths = [\"/\"]", "paths = [\"/v1/x\"]"); + expect_invalid(&swap, "must end with /"); + let pt = pt_base().replace("\"/api/v10/users/@me\"", "\"/api/v10/a/../b\""); + expect_invalid(&pt, "dot segment"); + } + + #[test] + fn swap_grant_without_credential_is_invalid() { + let text = base().replace( + "credential = \"kiro\"\nroute = \"kiro-krs\"\nmethods", + "route = \"kiro-krs\"\nmethods", + ); + expect_invalid(&text, "unknown credential"); + } + + #[test] + fn rejects_passthrough_limits_out_of_range() { + for (field, bad) in [ + ("max_connections", "0"), + ("max_connections", "65536"), + ("header_read_secs", "0"), + ("header_read_secs", "301"), + ("body_read_secs", "301"), + ("request_deadline_secs", "3601"), + ("upstream_idle_secs", "0"), + ] { + let text = pt_base().replace( + "public_authority = \"gate.example.test\"", + &format!("public_authority = \"gate.example.test\"\n{field} = {bad}"), + ); + expect_invalid(&text, field); + } + } + + #[test] + fn rejects_bad_public_authority_and_headers() { + for bad in ["", "a@b", "a/b", "a b"] { + let text = pt_base().replace("gate.example.test", bad); + expect_invalid(&text, "public_authority"); + } + let text = pt_base().replace( + "public_authority = \"gate.example.test\"", + "public_authority = \"gate.example.test\"\ncaller_key_header = \"authorization\"", + ); + expect_invalid(&text, "caller_key_header"); + let text = pt_base().replace( + "public_authority = \"gate.example.test\"", + "public_authority = \"gate.example.test\"\nfront_strip_headers = [\"Via\"]", + ); + expect_invalid(&text, "front_strip_headers"); + } + + #[test] + fn rejects_bad_passthrough_route_fields() { + let text = pt_base().replace( + "mode = \"passthrough\"", + "mode = \"passthrough\"\nerror_shape = \"aws\"", + ); + expect_invalid(&text, "error_shape generic"); + let text = pt_base().replace( + "mode = \"passthrough\"", + "mode = \"passthrough\"\npass_headers = [\"x-a\"]", + ); + expect_invalid(&text, "pass_headers"); + let text = pt_base().replace( + "mode = \"passthrough\"", + "mode = \"passthrough\"\nkeep_auth_headers = [\"authorization\"]", + ); + expect_invalid(&text, "keep_auth_headers"); + let ok = pt_base().replace( + "mode = \"passthrough\"", + "mode = \"passthrough\"\nkeep_auth_headers = [\"x-api-key\"]", + ); + assert!(load(&ok).is_ok()); + let text = pt_base() + .replace("name = \"discord\"", "name = \"ap\"") + .replace("route = \"discord\"", "route = \"ap\""); + expect_invalid(&text, "reserved"); + } + + #[test] + fn probe_defaults_off_and_needs_passthrough() { + let on = format!("{}\n[probe]\nenabled = true\n", pt_base()); + assert!(load(&on).unwrap().probe.enabled); + let bad = format!("{}\n[probe]\nenabled = true\n", base()); + expect_invalid(&bad, "[probe]"); + } + + #[test] + fn pilot_example_policy_validates() { + let text = include_str!("../../../deploy/muse/pilot-policy.example.toml") + .replace("<64 lowercase hex, sha256 of the issued apk_ key>", H64); + let cfg = load(&text).expect("the committed example must validate"); + assert!(cfg.is_passthrough_only()); + assert!(cfg.probe.enabled); + assert_eq!(cfg.grants[0].methods, vec!["GET".to_string()]); + } } diff --git a/crates/ap-core/src/error.rs b/crates/ap-core/src/error.rs index 482f442..b31f623 100644 --- a/crates/ap-core/src/error.rs +++ b/crates/ap-core/src/error.rs @@ -26,6 +26,15 @@ pub enum Code { UpstreamUnavailable, PolicyUnavailable, BrokerUnavailable, + // Passthrough routes (Muse gate). The sidecar path never produces these; its statuses here + // are placeholders and passthrough answers come from `outcome::passthrough_outcome`. + NoGrant, + FramingRefused, + AuthorizationDuplicate, + BodyReadTimeout, + ConnectFailed, + ProbeParams, + CallerKeyAmbiguous, } impl Code { @@ -53,6 +62,13 @@ impl Code { Code::UpstreamUnavailable => "upstream is unavailable", Code::PolicyUnavailable => "policy is unavailable", Code::BrokerUnavailable => "credential store is unavailable", + Code::NoGrant => "no grant allows this request", + Code::FramingRefused => "request framing is ambiguous", + Code::AuthorizationDuplicate => "more than one Authorization header", + Code::BodyReadTimeout => "request body stalled", + Code::ConnectFailed => "upstream connection failed", + Code::ProbeParams => "probe parameters are not allowed", + Code::CallerKeyAmbiguous => "caller key given in more than one place", } } @@ -62,7 +78,11 @@ impl Code { Code::AbsoluteForm | Code::HostRejected | Code::PathAmbiguous - | Code::SurrogateAmbiguous => 400, + | Code::SurrogateAmbiguous + | Code::FramingRefused + | Code::AuthorizationDuplicate + | Code::ProbeParams + | Code::CallerKeyAmbiguous => 400, Code::CallerRejected | Code::SurrogateMissing | Code::SurrogateMalformed @@ -72,13 +92,17 @@ impl Code { | Code::SurrogateWrongCaller | Code::SurrogateWrongRoute | Code::PolicyEmpty - | Code::PolicyDenied => 403, + | Code::PolicyDenied + | Code::NoGrant => 403, Code::RouteUnknown => 404, Code::ConnectRefused => 405, Code::BodyTooLarge => 413, Code::WebsocketUnsupported => 501, Code::UpstreamUnavailable => 502, - Code::PolicyUnavailable | Code::BrokerUnavailable => 503, + Code::PolicyUnavailable + | Code::BrokerUnavailable + | Code::BodyReadTimeout + | Code::ConnectFailed => 503, } } @@ -106,6 +130,13 @@ impl Code { Code::UpstreamUnavailable => "upstream_unavailable", Code::PolicyUnavailable => "policy_unavailable", Code::BrokerUnavailable => "broker_unavailable", + Code::NoGrant => "no_grant", + Code::FramingRefused => "framing_refused", + Code::AuthorizationDuplicate => "authorization_duplicate", + Code::BodyReadTimeout => "body_read_timeout", + Code::ConnectFailed => "connect_failed", + Code::ProbeParams => "probe_params", + Code::CallerKeyAmbiguous => "caller_key_ambiguous", } } } @@ -185,6 +216,13 @@ mod tests { assert_eq!(Code::UpstreamUnavailable.status(), 502); assert_eq!(Code::PolicyUnavailable.status(), 503); assert_eq!(Code::BrokerUnavailable.status(), 503); + assert_eq!(Code::NoGrant.status(), 403); + assert_eq!(Code::FramingRefused.status(), 400); + assert_eq!(Code::AuthorizationDuplicate.status(), 400); + assert_eq!(Code::ProbeParams.status(), 400); + assert_eq!(Code::CallerKeyAmbiguous.status(), 400); + assert_eq!(Code::BodyReadTimeout.status(), 503); + assert_eq!(Code::ConnectFailed.status(), 503); } #[test] @@ -211,6 +249,13 @@ mod tests { Code::UpstreamUnavailable, Code::PolicyUnavailable, Code::BrokerUnavailable, + Code::NoGrant, + Code::FramingRefused, + Code::AuthorizationDuplicate, + Code::BodyReadTimeout, + Code::ConnectFailed, + Code::ProbeParams, + Code::CallerKeyAmbiguous, ]; let mut seen = std::collections::HashSet::new(); for c in all { @@ -221,6 +266,6 @@ mod tests { ); assert!(seen.insert(s), "duplicate {s}"); } - assert_eq!(seen.len(), 21); + assert_eq!(seen.len(), 28); } } diff --git a/crates/ap-core/src/lib.rs b/crates/ap-core/src/lib.rs index a296036..26cfcea 100644 --- a/crates/ap-core/src/lib.rs +++ b/crates/ap-core/src/lib.rs @@ -5,5 +5,6 @@ pub mod canon; pub mod config; pub mod error; pub mod headers; +pub mod outcome; pub mod policy; pub mod session_wire; diff --git a/crates/ap-core/src/outcome.rs b/crates/ap-core/src/outcome.rs new file mode 100644 index 0000000..2eb181d --- /dev/null +++ b/crates/ap-core/src/outcome.rs @@ -0,0 +1,132 @@ +//! Outcome contract for passthrough routes (design 3.5). +//! +//! Every refusal the gate generates carries `X-AP-Decision` and a small JSON body. The statuses +//! here differ from the sidecar's (`route_unknown` is 423, `caller_rejected` is 401), so they live +//! in this module and `Code::status` and `error::render` are untouched. + +use crate::error::Code; + +/// The value of the `X-AP-Decision` header. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Decision { + Denied, + Expired, + Unavailable, + Rejected, +} + +impl Decision { + pub fn as_str(self) -> &'static str { + match self { + Decision::Denied => "denied", + Decision::Expired => "expired", + Decision::Unavailable => "unavailable", + Decision::Rejected => "rejected", + } + } +} + +/// The name of the decision header. +pub const DECISION_HEADER: &str = "x-ap-decision"; + +/// Status and decision for a gate refusal on a passthrough route. +pub fn passthrough_outcome(code: Code) -> (u16, Decision) { + match code { + Code::CallerRejected => (401, Decision::Rejected), + Code::RouteUnknown | Code::NoGrant => (423, Decision::Denied), + Code::AbsoluteForm + | Code::HostRejected + | Code::PathAmbiguous + | Code::FramingRefused + | Code::AuthorizationDuplicate + | Code::ProbeParams + | Code::CallerKeyAmbiguous => (400, Decision::Denied), + Code::ConnectRefused => (405, Decision::Denied), + Code::WebsocketUnsupported => (501, Decision::Denied), + Code::BodyTooLarge => (413, Decision::Denied), + Code::PolicyUnavailable | Code::BodyReadTimeout | Code::ConnectFailed => { + (503, Decision::Unavailable) + } + // Not produced by the passthrough pipeline. Fail closed with a generic refusal. + _ => (503, Decision::Unavailable), + } +} + +/// Status, decision and JSON body `{"ap_decision","code"}`, built from fixed strings only. +pub fn render_passthrough(code: Code) -> (u16, Decision, Vec) { + let (status, decision) = passthrough_outcome(code); + let body = format!( + "{{\"ap_decision\":\"{}\",\"code\":\"{}\"}}", + decision.as_str(), + code.code_str() + ); + (status, decision, body.into_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::ErrorShape; + use crate::error::render; + + #[test] + fn stage1_rows_of_the_outcome_table() { + let rows = [ + (Code::NoGrant, 423, "denied", "no_grant"), + (Code::RouteUnknown, 423, "denied", "route_unknown"), + (Code::CallerRejected, 401, "rejected", "caller_rejected"), + (Code::PathAmbiguous, 400, "denied", "path_ambiguous"), + (Code::HostRejected, 400, "denied", "host_rejected"), + (Code::AbsoluteForm, 400, "denied", "absolute_form"), + (Code::FramingRefused, 400, "denied", "framing_refused"), + ( + Code::AuthorizationDuplicate, + 400, + "denied", + "authorization_duplicate", + ), + (Code::ConnectRefused, 405, "denied", "connect_refused"), + ( + Code::WebsocketUnsupported, + 501, + "denied", + "websocket_unsupported", + ), + (Code::BodyTooLarge, 413, "denied", "body_too_large"), + ( + Code::PolicyUnavailable, + 503, + "unavailable", + "policy_unavailable", + ), + ( + Code::BodyReadTimeout, + 503, + "unavailable", + "body_read_timeout", + ), + (Code::ConnectFailed, 503, "unavailable", "connect_failed"), + (Code::ProbeParams, 400, "denied", "probe_params"), + ( + Code::CallerKeyAmbiguous, + 400, + "denied", + "caller_key_ambiguous", + ), + ]; + for (code, status, decision, name) in rows { + let (s, d, body) = render_passthrough(code); + assert_eq!((s, d.as_str()), (status, decision), "{name}"); + let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(v["ap_decision"], decision); + assert_eq!(v["code"], name); + assert_eq!(v.as_object().unwrap().len(), 2); + } + } + + #[test] + fn sidecar_rendering_is_unchanged() { + assert_eq!(render(Code::CallerRejected, ErrorShape::Generic).0, 403); + assert_eq!(render(Code::RouteUnknown, ErrorShape::Generic).0, 404); + } +} diff --git a/crates/ap-proxy/Cargo.toml b/crates/ap-proxy/Cargo.toml index e8f7a98..f1dea2c 100644 --- a/crates/ap-proxy/Cargo.toml +++ b/crates/ap-proxy/Cargo.toml @@ -33,12 +33,19 @@ default = [] # Test-only, off by default and never enabled in a release build. Lets the black-box matrix trust a # throwaway CA and resolve mock upstream names (crates/ap-proxy/src/matrix_hooks.rs). matrix-upstream = [] +# Stage 1 measurement only: the hold-tolerance probe route. Off by default, never in a stage 2 build. +stage1-probe = [] [[test]] name = "matrix" path = "tests/matrix.rs" required-features = ["matrix-upstream"] +[[test]] +name = "matrix_passthrough" +path = "tests/matrix_passthrough.rs" +required-features = ["matrix-upstream"] + [dev-dependencies] base64 = "0.22" h2 = "0.4" diff --git a/crates/ap-proxy/src/evidence.rs b/crates/ap-proxy/src/evidence.rs new file mode 100644 index 0000000..f6c38f0 --- /dev/null +++ b/crates/ap-proxy/src/evidence.rs @@ -0,0 +1,212 @@ +//! Stage 1 evidence (design section 7): fixed fields about how a real Muse connector calls the +//! gate. No header value, no header length, no key, no body. One JSON line per request that +//! carried a valid caller key, written through the audit sink. +//! +//! The manually observed list of candidate non-secret header names is collected by hand, not +//! here (docs/runbooks/muse-stage1.md). + +use ap_broker::registry::sha256_hex; +use http::{header, HeaderMap, Version}; +use serde::Serialize; + +/// Which front-added header families were present. Booleans only. +#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)] +pub struct FrontFamilies { + pub forwarded: bool, + pub x_forwarded: bool, + pub x_real_ip: bool, + pub via: bool, + pub tailscale: bool, + pub cf: bool, +} + +/// Fixed fields only. Every field is a name, a boolean, a class or a status, so the derived +/// `Debug` cannot print a secret. +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct Evidence { + pub identity: String, + pub route: Option, + pub method: String, + /// Route-relative, redacted, no query. + pub path: String, + pub status: u16, + pub http_version: &'static str, + pub auth_present: bool, + pub chunked: bool, + pub compressed: bool, + pub content_type_class: &'static str, + pub expect_continue: bool, + pub front_headers_present: FrontFamilies, + /// sha256 over the sorted, de-duplicated header NAMES as the handler sees them, joined by `\n`. + /// The `http` crate lowercases names on parse. Names hyper already removed or merged (for + /// example `Content-Length` next to `Transfer-Encoding: chunked`) are not in it. Values never enter it. + pub fwd_names_digest: String, +} + +impl Evidence { + /// Collect the fixed fields from a request head. `route`, `path` and `status` are filled in + /// by the caller as the pipeline learns them. + pub fn collect( + identity: &str, + method: &str, + version: Version, + headers: &HeaderMap, + ) -> Evidence { + let chunked = headers.get_all(header::TRANSFER_ENCODING).iter().any(|v| { + v.to_str() + .is_ok_and(|s| s.to_ascii_lowercase().contains("chunked")) + }); + let compressed = headers.get(header::CONTENT_ENCODING).is_some_and(|v| { + v.to_str() + .map(|s| !s.trim().eq_ignore_ascii_case("identity")) + .unwrap_or(true) + }); + let content_type_class = match headers.get(header::CONTENT_TYPE) { + None => "none", + Some(v) => { + let s = v.to_str().unwrap_or("").to_ascii_lowercase(); + if s.starts_with("application/json") { + "json" + } else if s.starts_with("multipart/") { + "multipart" + } else { + "other" + } + } + }; + let has = |pred: &dyn Fn(&str) -> bool| headers.keys().any(|k| pred(k.as_str())); + let front = FrontFamilies { + forwarded: has(&|n| n == "forwarded"), + x_forwarded: has(&|n| n.starts_with("x-forwarded-")), + x_real_ip: has(&|n| n == "x-real-ip"), + via: has(&|n| n == "via"), + tailscale: has(&|n| n.starts_with("tailscale-")), + cf: has(&|n| n.starts_with("cf-")), + }; + let mut names: Vec<&str> = headers.keys().map(|k| k.as_str()).collect(); + names.sort_unstable(); + names.dedup(); + Evidence { + identity: identity.to_string(), + route: None, + method: method.to_string(), + path: String::new(), + status: 0, + http_version: match version { + Version::HTTP_10 => "1.0", + Version::HTTP_11 => "1.1", + Version::HTTP_2 => "2", + _ => "other", + }, + auth_present: headers.contains_key(header::AUTHORIZATION), + chunked, + compressed, + content_type_class, + expect_continue: headers.contains_key(header::EXPECT), + front_headers_present: front, + fwd_names_digest: sha256_hex(&names.join("\n")), + } + } + + /// `{"evidence":{...}}` with a trailing newline. + pub fn to_json_line(&self) -> String { + let mut line = serde_json::json!({ "evidence": self }).to_string(); + line.push('\n'); + line + } +} + +#[cfg(test)] +mod tests { + use super::*; + use http::HeaderValue; + + fn headers(pairs: &[(&str, &str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append( + http::HeaderName::from_bytes(k.as_bytes()).unwrap(), + HeaderValue::from_str(v).unwrap(), + ); + } + h + } + + #[test] + fn json_key_set_is_the_fixed_list() { + let e = Evidence::collect("m", "GET", Version::HTTP_11, &headers(&[])); + let v: serde_json::Value = serde_json::from_str(e.to_json_line().trim_end()).unwrap(); + let inner = v["evidence"].as_object().unwrap(); + let mut keys: Vec<&str> = inner.keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!( + keys, + vec![ + "auth_present", + "chunked", + "compressed", + "content_type_class", + "expect_continue", + "front_headers_present", + "fwd_names_digest", + "http_version", + "identity", + "method", + "path", + "route", + "status" + ] + ); + assert_eq!(v.as_object().unwrap().len(), 1); + } + + #[test] + fn no_value_reaches_the_line_and_digest_ignores_values() { + let a = headers(&[ + ("authorization", "Bot SENTINEL-AUTH"), + ("x-custom", "SENTINEL-CUSTOM"), + ("cookie", "SENTINEL-COOKIE"), + ("x-ap-caller-key", "SENTINEL-KEY"), + ("host", "gate.example.test"), + ("content-type", "application/json"), + ]); + let b = headers(&[ + ("authorization", "other"), + ("x-custom", "other"), + ("cookie", "other"), + ("x-ap-caller-key", "other"), + ("host", "gate.example.test"), + ("content-type", "application/json"), + ]); + let ea = Evidence::collect("m", "POST", Version::HTTP_11, &a); + let eb = Evidence::collect("m", "POST", Version::HTTP_11, &b); + let line = ea.to_json_line(); + assert!(!line.contains("SENTINEL"), "{line}"); + assert!(!format!("{ea:?}").contains("SENTINEL")); + assert_eq!(ea.fwd_names_digest, eb.fwd_names_digest); + assert!(ea.auth_present); + assert_eq!(ea.content_type_class, "json"); + assert_eq!(line.matches('\n').count(), 1); + assert!(line.ends_with('\n')); + } + + #[test] + fn booleans_and_classes() { + let h = headers(&[ + ("transfer-encoding", "chunked"), + ("content-encoding", "gzip"), + ("content-type", "multipart/form-data; boundary=x"), + ("expect", "100-continue"), + ("x-forwarded-for", "1"), + ("tailscale-user-login", "x"), + ("host", "wrong"), + ]); + let e = Evidence::collect("m", "POST", Version::HTTP_10, &h); + assert!(e.chunked && e.compressed && e.expect_continue); + assert_eq!(e.content_type_class, "multipart"); + assert_eq!(e.http_version, "1.0"); + assert!(e.front_headers_present.x_forwarded && e.front_headers_present.tailscale); + assert!(!e.front_headers_present.cf); + assert!(!e.auth_present); + } +} diff --git a/crates/ap-proxy/src/forward.rs b/crates/ap-proxy/src/forward.rs index 6714a68..0f7e3a8 100644 --- a/crates/ap-proxy/src/forward.rs +++ b/crates/ap-proxy/src/forward.rs @@ -10,12 +10,12 @@ use std::sync::Arc; use std::time::Duration; use ap_broker::store::SecretBytes; -use ap_core::config::Route; -use ap_core::headers::{strip_request_headers, HOP_HEADERS}; +use ap_core::config::{Passthrough, Route}; +use ap_core::headers::{strip_request_headers, AUTH_HEADERS, HOP_HEADERS}; use axum::body::Body; use bytes::Bytes; use futures_util::StreamExt; -use http::header::{CONTENT_LENGTH, HOST}; +use http::header::{AUTHORIZATION, CONNECTION, CONTENT_LENGTH, HOST}; use http::{HeaderMap, HeaderName, HeaderValue, Method}; use reqwest::redirect::Policy; use reqwest::{Client, ClientBuilder}; @@ -123,12 +123,129 @@ pub fn capped_body(body: Body, max: u64, overflow: Arc) -> reqwest:: reqwest::Body::wrap_stream(stream) } -/// Copy the upstream response headers for the agent. Hop-by-hop headers are dropped. -/// `Content-Length` is kept, because the body is streamed without re-framing. +/// Whether `name` matches a front-header pattern: exact, or a prefix when the pattern ends in `*`. +fn matches_pattern(name: &str, pattern: &str) -> bool { + match pattern.strip_suffix('*') { + Some(prefix) => name.starts_with(prefix), + None => name == pattern, + } +} + +/// Build the outbound headers for a passthrough route (design 3.1, ordered algorithm). +/// +/// Removed: the caller-key header, every `x-ap-*` header, hop-by-hop headers, every header named +/// by `Connection`, `Expect`, `Host`, the configured front headers, and every `AUTH_HEADERS` +/// member except `authorization` and the route's `keep_auth_headers`. Everything else is kept, +/// repeated values included. A declared `Content-Length` is put back, so the upstream request +/// keeps the declared framing. `Authorization` is marked sensitive and otherwise unchanged. +pub fn passthrough_headers(inbound: &HeaderMap, route: &Route, pt: &Passthrough) -> HeaderMap { + let nominated: Vec = inbound + .get_all(CONNECTION) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(',')) + .map(|n| n.trim().to_ascii_lowercase()) + .filter(|n| !n.is_empty()) + .collect(); + let mut out = HeaderMap::new(); + for (name, value) in inbound { + let n = name.as_str(); + let drop = n == pt.caller_key_header + || n.starts_with("x-ap-") + || n == "expect" + || HOP_HEADERS.contains(&n) + || nominated.iter().any(|c| c == n) + || pt.front_strip_headers.iter().any(|p| matches_pattern(n, p)) + || (AUTH_HEADERS.contains(&n) + && n != AUTHORIZATION.as_str() + && !route.keep_auth_headers.iter().any(|k| k == n)); + if drop { + continue; + } + let mut v = value.clone(); + if n == AUTHORIZATION.as_str() { + v.set_sensitive(true); + } + out.append(name.clone(), v); + } + if let Some(len) = inbound.get(CONTENT_LENGTH) { + out.insert(CONTENT_LENGTH, len.clone()); + } + out +} + +/// Shared flags a [`guarded_body`] sets while the upstream client reads it. +#[derive(Clone, Default)] +pub struct BodyFlags { + /// At least one body chunk was handed to the upstream request. + pub sent_any: Arc, + /// The body went over the cap. + pub overflow: Arc, + /// The client stalled longer than the per-chunk limit. + pub stalled: Arc, +} + +/// Wrap the inbound request body for an allowed passthrough request. +/// +/// Bytes are counted against `max`, each chunk must arrive within `stall`, and the flags record +/// what happened. Chunks are forwarded as they come, with no buffering. +pub fn guarded_body(body: Body, max: u64, stall: Duration, flags: BodyFlags) -> reqwest::Body { + let stream = futures_util::stream::unfold( + (Box::pin(body.into_data_stream()), 0u64, flags, false), + move |(mut s, seen, flags, failed)| async move { + if failed { + return None; + } + let next = match tokio::time::timeout(stall, s.next()).await { + Ok(n) => n, + Err(_) => { + flags.stalled.store(true, Ordering::SeqCst); + let e = io::Error::new(io::ErrorKind::TimedOut, "request body stalled"); + return Some((Err(e), (s, seen, flags, true))); + } + }; + match next { + None => None, + Some(Err(e)) => Some((Err(io::Error::other(e)), (s, seen, flags, true))), + Some(Ok(chunk)) => { + let seen = seen.saturating_add(chunk.len() as u64); + if seen > max { + flags.overflow.store(true, Ordering::SeqCst); + let e = io::Error::other("request body exceeds the configured limit"); + return Some((Err(e), (s, seen, flags, true))); + } + if !chunk.is_empty() { + flags.sent_any.store(true, Ordering::SeqCst); + } + Some((Ok::(chunk), (s, seen, flags, false))) + } + } + }, + ); + reqwest::Body::wrap_stream(stream) +} + +/// Response-only hop-by-hop fields, in addition to `HOP_HEADERS`. +const RESPONSE_HOP_HEADERS: &[&str] = &["proxy-authenticate"]; + +/// Copy the upstream response headers for the agent. Hop-by-hop headers and every field named by an +/// upstream `Connection` header are dropped. `Content-Length` is kept, because the body is streamed +/// without re-framing. pub fn response_headers(upstream: &HeaderMap) -> HeaderMap { + let nominated: Vec = upstream + .get_all(CONNECTION) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|s| s.split(',')) + .map(|t| t.trim().to_ascii_lowercase()) + .filter(|t| !t.is_empty()) + .collect(); let mut out = HeaderMap::new(); for (name, value) in upstream { let n = name.as_str(); + if nominated.iter().any(|t| t == n) || RESPONSE_HOP_HEADERS.contains(&n) { + continue; + } if n == CONTENT_LENGTH.as_str() || !HOP_HEADERS.contains(&n) { out.append(name.clone(), value.clone()); } @@ -151,3 +268,208 @@ pub async fn send( .send() .await } + +#[cfg(test)] +mod passthrough_tests { + use super::*; + use ap_core::config::{load, Config}; + use http::HeaderValue; + + fn cfg(extra_route: &str) -> Config { + load(&format!( + r#"version = 1 +[listen] +proxy = "127.0.0.1:8443" +[passthrough] +public_authority = "gate.example.test" +[[identity]] +name = "m" +caller_key_sha256 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" +[[route]] +name = "discord" +host = "discord.com" +mode = "passthrough" +{extra_route} +[[grant]] +identity = "m" +route = "discord" +methods = ["GET"] +paths = ["/"] +"# + )) + .expect("valid") + } + + fn build(c: &Config, pairs: &[(&str, &str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append( + HeaderName::from_bytes(k.as_bytes()).unwrap(), + HeaderValue::from_str(v).unwrap(), + ); + } + passthrough_headers(&h, &c.routes[0], c.passthrough.as_ref().unwrap()) + } + + #[test] + fn keeps_authorization_and_ordinary_headers_and_repeats() { + let c = cfg(""); + let out = build( + &c, + &[ + ("authorization", "Bot abc"), + ("content-type", "application/json"), + ("x-custom", "1"), + ("x-custom", "2"), + ("user-agent", "DiscordBot"), + ], + ); + assert_eq!(out.get("authorization").unwrap(), "Bot abc"); + assert!(out.get("authorization").unwrap().is_sensitive()); + assert_eq!(out.get("content-type").unwrap(), "application/json"); + assert_eq!(out.get_all("x-custom").iter().count(), 2); + assert_eq!(out.get("user-agent").unwrap(), "DiscordBot"); + } + + #[test] + fn strips_caller_key_front_hop_and_credential_headers() { + let c = cfg(""); + let out = build( + &c, + &[ + ("authorization", "Bot abc"), + ("x-ap-caller-key", "apk_x"), + ("x-ap-foo", "1"), + ("forwarded", "for=1"), + ("x-forwarded-for", "1"), + ("x-real-ip", "1"), + ("via", "1"), + ("cf-ray", "1"), + ("tailscale-user-login", "someone"), + ("cookie", "a=b"), + ("proxy-authorization", "x"), + ("x-api-key", "k"), + ("expect", "100-continue"), + ("host", "gate.example.test"), + ("connection", "x-private, keep-alive"), + ("x-private", "1"), + ("keep-alive", "5"), + ("te", "trailers"), + ("upgrade", "websocket"), + ], + ); + let names: Vec<&str> = out.keys().map(|k| k.as_str()).collect(); + assert_eq!(names, vec!["authorization"], "left: {names:?}"); + } + + #[test] + fn keep_auth_headers_keeps_a_named_member_only() { + let c = cfg("keep_auth_headers = [\"x-api-key\"]"); + let out = build(&c, &[("x-api-key", "k"), ("cookie", "a=b")]); + assert_eq!(out.get("x-api-key").unwrap(), "k"); + assert!(out.get("cookie").is_none()); + } + + #[test] + fn response_drops_hop_headers_and_connection_nominations() { + let mut up = HeaderMap::new(); + for (k, v) in [ + ("connection", "X-Hop, keep-alive"), + ("connection", " x-other "), + ("x-hop", "value"), + ("x-other", "value"), + ("x-kept", "ok"), + ("proxy-authenticate", "Basic"), + ("content-length", "5"), + ] { + up.append( + HeaderName::from_static(k), + HeaderValue::from_str(v).unwrap(), + ); + } + let out = response_headers(&up); + let mut names: Vec<&str> = out.keys().map(|k| k.as_str()).collect(); + names.sort_unstable(); + assert_eq!(names, vec!["content-length", "x-kept"]); + } + + #[test] + fn declared_content_length_is_put_back() { + let c = cfg(""); + let out = build(&c, &[("content-length", "12")]); + assert_eq!(out.get("content-length").unwrap(), "12"); + let out = build(&c, &[("transfer-encoding", "chunked")]); + assert!(out.get("content-length").is_none()); + assert!(out.get("transfer-encoding").is_none()); + } + + async fn drain(b: reqwest::Body) -> Vec> { + let mut out = Vec::new(); + let mut s = http_body_util::BodyDataStream::new(b); + while let Some(c) = s.next().await { + out.push(c.map_err(|e| e.to_string())); + } + out + } + + fn flags() -> BodyFlags { + BodyFlags::default() + } + + #[tokio::test] + async fn stall_after_a_prefix_sets_sent_any_and_stalled() { + let (tx, rx) = tokio::sync::mpsc::channel::>(2); + tx.send(Ok(Bytes::from_static(b"abc"))).await.unwrap(); + let f = flags(); + let body = guarded_body( + Body::from_stream(tokio_stream_from(rx)), + 100, + Duration::from_millis(50), + f.clone(), + ); + let got = drain(body).await; + assert!(got[0].is_ok()); + assert!(got[1].is_err()); + assert!(f.sent_any.load(Ordering::SeqCst)); + assert!(f.stalled.load(Ordering::SeqCst)); + drop(tx); + } + + #[tokio::test] + async fn stall_before_any_chunk_leaves_sent_any_false() { + let (tx, rx) = tokio::sync::mpsc::channel::>(2); + let f = flags(); + let body = guarded_body( + Body::from_stream(tokio_stream_from(rx)), + 100, + Duration::from_millis(50), + f.clone(), + ); + let got = drain(body).await; + assert!(got[0].is_err()); + assert!(!f.sent_any.load(Ordering::SeqCst)); + assert!(f.stalled.load(Ordering::SeqCst)); + drop(tx); + } + + #[tokio::test] + async fn over_cap_sets_overflow() { + let f = flags(); + let body = guarded_body( + Body::from(vec![0u8; 10]), + 5, + Duration::from_secs(5), + f.clone(), + ); + let got = drain(body).await; + assert!(got[0].is_err()); + assert!(f.overflow.load(Ordering::SeqCst)); + assert!(!f.sent_any.load(Ordering::SeqCst)); + } + + fn tokio_stream_from( + mut rx: tokio::sync::mpsc::Receiver>, + ) -> impl futures_util::Stream> { + futures_util::stream::poll_fn(move |cx| rx.poll_recv(cx)) + } +} diff --git a/crates/ap-proxy/src/lib.rs b/crates/ap-proxy/src/lib.rs index c184840..cf83ea2 100644 --- a/crates/ap-proxy/src/lib.rs +++ b/crates/ap-proxy/src/lib.rs @@ -5,11 +5,16 @@ pub mod admin_http; pub mod audit_sink; +pub mod evidence; pub mod forward; pub mod listener; #[cfg(feature = "matrix-upstream")] pub mod matrix_hooks; +pub mod passthrough; pub mod pipeline; +mod policy_store; +#[cfg(feature = "stage1-probe")] +mod probe; pub mod session_http; use std::future::IntoFuture; @@ -106,6 +111,9 @@ pub async fn run(opts: Options) -> i32 { return 2; } }; + if cfg.is_passthrough_only() { + return run_passthrough(&opts, cfg).await; + } let listen = cfg.listen.proxy; // The store is never created here. A missing file means it was lost or never provisioned, // and the proxy must not start over it. @@ -201,3 +209,46 @@ pub async fn run(opts: Options) -> i32 { async fn agent_response(app: Arc, req: Request) -> Response { pipeline::handle(app, req).await } + +/// A passthrough-only deployment (the Muse gate). It needs no expiry store, broker, session +/// socket or admin socket, so none is read or bound, and the sidecar flags are ignored. +async fn run_passthrough(opts: &Options, cfg: ap_core::config::Config) -> i32 { + if cfg.probe.enabled && !cfg!(feature = "stage1-probe") { + eprintln!("auth-proxy: [probe] is enabled but this build lacks the stage1-probe feature"); + return 2; + } + let Some(pt) = cfg.passthrough.clone() else { + eprintln!("auth-proxy: passthrough settings are missing"); + return 2; + }; + let client = match forward::client() { + Ok(c) => c, + Err(e) => { + eprintln!("auth-proxy: cannot build the upstream client: {e}"); + return 1; + } + }; + let listen = cfg.listen.proxy; + let listener = match listener::bind_loopback(listen).await { + Ok(l) => l, + Err(e) => { + eprintln!("auth-proxy: cannot bind the public listener: {e}"); + return 2; + } + }; + // A panic line carries the source location only, never the payload, which could hold a + // header value. + std::panic::set_hook(Box::new(|info| match info.location() { + Some(l) => eprintln!("auth-proxy: panic at {}:{}", l.file(), l.line()), + None => eprintln!("auth-proxy: panic"), + })); + let app = passthrough::PtApp::new(opts.config.clone(), cfg, AuditSink::stdout(), client); + let limits = listener::public::PublicLimits { + max_connections: pt.max_connections, + header_read: std::time::Duration::from_secs(pt.header_read_secs), + }; + eprintln!("auth-proxy: listening"); + listener::public::serve_public(listener, app, limits).await; + eprintln!("auth-proxy: public listener stopped"); + 1 +} diff --git a/crates/ap-proxy/src/listener.rs b/crates/ap-proxy/src/listener.rs index 2ac9555..740cfce 100644 --- a/crates/ap-proxy/src/listener.rs +++ b/crates/ap-proxy/src/listener.rs @@ -9,6 +9,8 @@ use std::path::Path; use tokio::net::{TcpListener, UnixListener}; +pub mod public; + #[cfg(test)] mod tests; diff --git a/crates/ap-proxy/src/listener/public.rs b/crates/ap-proxy/src/listener/public.rs new file mode 100644 index 0000000..820ed3e --- /dev/null +++ b/crates/ap-proxy/src/listener/public.rs @@ -0,0 +1,184 @@ +//! The public passthrough listener: an accept loop with a connection cap and a header-read +//! timeout, over hyper's HTTP/1 server. The socket still comes from `bind_loopback`. +//! +//! A handler that returns `Err(ConnAbort)` closes the connection with no answer. A panic in a +//! handler ends only its own connection task. + +use std::sync::Arc; +use std::time::Duration; + +use axum::body::Body; +use hyper::body::Incoming; +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper_util::rt::{TokioIo, TokioTimer}; +use tokio::net::TcpListener; +use tokio::sync::Semaphore; + +use crate::passthrough::{self, PtApp}; + +/// Public-listener limits, from `[passthrough]`. +#[derive(Debug, Clone, Copy)] +pub struct PublicLimits { + pub max_connections: usize, + pub header_read: Duration, +} + +/// Serve until the listener fails. Connections over the cap are accepted and closed at once. +pub async fn serve_public(listener: TcpListener, app: Arc, limits: PublicLimits) { + let permits = Arc::new(Semaphore::new(limits.max_connections)); + loop { + let (stream, _) = match listener.accept().await { + Ok(c) => c, + Err(_) => { + // A transient accept error (descriptor exhaustion) must not spin. + tokio::time::sleep(Duration::from_millis(50)).await; + continue; + } + }; + let Ok(permit) = Arc::clone(&permits).try_acquire_owned() else { + drop(stream); + continue; + }; + let _ = stream.set_nodelay(true); + let app = Arc::clone(&app); + tokio::spawn(async move { + let svc = service_fn(move |req: hyper::Request| { + let app = Arc::clone(&app); + async move { passthrough::handle(app, req.map(Body::new)).await } + }); + let _ = http1::Builder::new() + .timer(TokioTimer::new()) + .header_read_timeout(limits.header_read) + .serve_connection(TokioIo::new(stream), svc) + .await; + drop(permit); + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::{buffer_sink, caller_key, client_for, start_upstream, Scratch, HOST}; + use ap_broker::registry::sha256_hex; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpStream; + + async fn start(max: usize, header_read: Duration) -> (std::net::SocketAddr, String, Scratch) { + let up = start_upstream().await; + let s = Scratch::new("pub"); + let key = caller_key(); + let text = format!( + r#"version = 1 +[listen] +proxy = "127.0.0.1:8443" +[passthrough] +public_authority = "gate.example.test" +body_read_secs = 1 +[[identity]] +name = "muse-pilot" +caller_key_sha256 = "{}" +[[route]] +name = "discord" +host = "{HOST}" +port = {} +mode = "passthrough" +[[grant]] +identity = "muse-pilot" +route = "discord" +methods = ["GET", "POST"] +paths = ["/api/", "/up/"] +"#, + sha256_hex(&key), + up.addr.port() + ); + let path = s.path().join("policy.toml"); + std::fs::write(&path, &text).unwrap(); + let cfg = ap_core::config::load(&text).unwrap(); + let (sink, _audit) = buffer_sink(); + let app = PtApp::new(path, cfg, sink, client_for(&up)); + let l = crate::listener::bind_loopback("127.0.0.1:0".parse().unwrap()) + .await + .unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(serve_public( + l, + app, + PublicLimits { + max_connections: max, + header_read, + }, + )); + // Keep the upstream alive for the test's duration. + Box::leak(Box::new(up)); + (addr, key, s) + } + + fn get(key: &str) -> String { + format!( + "GET /discord/api/x HTTP/1.1\r\nHost: gate.example.test\r\nx-ap-caller-key: {key}\r\nauthorization: Bot t\r\n\r\n" + ) + } + + async fn read_some(c: &mut TcpStream) -> String { + let mut buf = vec![0u8; 4096]; + match tokio::time::timeout(Duration::from_secs(5), c.read(&mut buf)).await { + Ok(Ok(n)) => String::from_utf8_lossy(&buf[..n]).into_owned(), + // A reset is a close for these tests. + Ok(Err(_)) => String::new(), + _ => "".into(), + } + } + + #[tokio::test] + async fn connection_cap_closes_the_extra_connection() { + let (addr, key, _s) = start(2, Duration::from_secs(5)).await; + let mut a = TcpStream::connect(addr).await.unwrap(); + let mut b = TcpStream::connect(addr).await.unwrap(); + // Make sure both hold permits before the third arrives. + a.write_all(get(&key).as_bytes()).await.unwrap(); + assert!(read_some(&mut a).await.starts_with("HTTP/1.1 200")); + b.write_all(get(&key).as_bytes()).await.unwrap(); + assert!(read_some(&mut b).await.starts_with("HTTP/1.1 200")); + let mut c = TcpStream::connect(addr).await.unwrap(); + let _ = c.write_all(get(&key).as_bytes()).await; + assert_eq!( + read_some(&mut c).await, + "", + "third connection must be closed" + ); + // The first two still work (keep-alive). + a.write_all(get(&key).as_bytes()).await.unwrap(); + assert!(read_some(&mut a).await.starts_with("HTTP/1.1 200")); + } + + #[tokio::test] + async fn header_read_timeout_closes_and_proxy_keeps_serving() { + let (addr, key, _s) = start(8, Duration::from_millis(300)).await; + let mut slow = TcpStream::connect(addr).await.unwrap(); + slow.write_all(b"GET /discord/api/x HTT").await.unwrap(); + assert_eq!(read_some(&mut slow).await, "", "slow header must be closed"); + let mut ok = TcpStream::connect(addr).await.unwrap(); + ok.write_all(get(&key).as_bytes()).await.unwrap(); + assert!(read_some(&mut ok).await.starts_with("HTTP/1.1 200")); + } + + #[tokio::test] + async fn stalled_body_closes_and_proxy_keeps_serving() { + let (addr, key, _s) = start(8, Duration::from_secs(5)).await; + let mut c = TcpStream::connect(addr).await.unwrap(); + let head = format!( + "POST /discord/up/echo2 HTTP/1.1\r\nHost: gate.example.test\r\nx-ap-caller-key: {key}\r\nauthorization: Bot t\r\ntransfer-encoding: chunked\r\n\r\n3\r\nabc\r\n" + ); + c.write_all(head.as_bytes()).await.unwrap(); + assert_eq!( + read_some(&mut c).await, + "", + "stalled body must close the connection" + ); + let mut ok = TcpStream::connect(addr).await.unwrap(); + ok.write_all(get(&key).as_bytes()).await.unwrap(); + assert!(read_some(&mut ok).await.starts_with("HTTP/1.1 200")); + } +} diff --git a/crates/ap-proxy/src/matrix_hooks.rs b/crates/ap-proxy/src/matrix_hooks.rs index 1e0a991..e23438d 100644 --- a/crates/ap-proxy/src/matrix_hooks.rs +++ b/crates/ap-proxy/src/matrix_hooks.rs @@ -15,6 +15,9 @@ pub const ENV_CA: &str = "AP_TEST_UPSTREAM_CA"; /// Comma-separated `host=ip` pairs. Each host resolves to that address. The port comes from the URL. pub const ENV_RESOLVE: &str = "AP_TEST_RESOLVE"; +/// A request path that makes a passthrough handler panic, to exercise the panic hook. +pub const PANIC_PATH: &str = "/__ap_test_panic"; + /// Startup banner for a feature-enabled binary. It is printed on every start. pub const WARNING: &str = "auth-proxy: *************************************************************** auth-proxy: WARNING: TEST BUILD (feature matrix-upstream). This is not the release artifact. diff --git a/crates/ap-proxy/src/passthrough.rs b/crates/ap-proxy/src/passthrough.rs new file mode 100644 index 0000000..3dcc1f1 --- /dev/null +++ b/crates/ap-proxy/src/passthrough.rs @@ -0,0 +1,434 @@ +//! The passthrough pipeline (design 3.1) for the Muse gate, stage 1. +//! +//! In order: refuse CONNECT and Upgrade, canonicalize (origin form, public `Host`, ambiguous +//! path), refuse ambiguous framing, read the caller key from its header or the `/ap//` path prefix (exactly one), resolve the route name +//! in the path to a fixed host, refuse a duplicate `Authorization`, evaluate the grant (anything +//! not granted, writes included, is 423 `no_grant`), forward with the caller's own +//! `Authorization` unchanged, and stream the response back. Every gate refusal carries +//! `X-AP-Decision` and writes one audit line. Nothing request-supplied selects the upstream host. + +use std::io; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use ap_broker::registry::sha256_hex; +use ap_core::audit::{path_only, AuditRec}; +use ap_core::canon; +use ap_core::config::{Config, Identity}; +use ap_core::error::Code; +use ap_core::outcome::{render_passthrough, DECISION_HEADER}; +use axum::body::Body; +use bytes::Bytes; +use futures_util::{Stream, StreamExt}; +use http::{header, HeaderValue, Method, Request, Response, StatusCode}; +use subtle::ConstantTimeEq; + +use crate::audit_sink::AuditSink; +use crate::evidence::Evidence; +use crate::forward::{self, BodyFlags}; +use crate::policy_store::PolicyStore; + +#[cfg(test)] +mod tests; + +/// Returned instead of a response: the connection is closed with no synthetic decision. +#[derive(Debug)] +pub struct ConnAbort; + +impl std::fmt::Display for ConnAbort { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("connection aborted after the first upstream byte") + } +} + +impl std::error::Error for ConnAbort {} + +/// Shared state of the passthrough listener. +pub struct PtApp { + pub(crate) policy: PolicyStore, + pub(crate) audit: AuditSink, + client: reqwest::Client, +} + +impl PtApp { + pub(crate) fn new( + policy_path: std::path::PathBuf, + cfg: Config, + audit: AuditSink, + client: reqwest::Client, + ) -> Arc { + Arc::new(PtApp { + policy: PolicyStore::new(policy_path, cfg), + audit, + client, + }) + } +} + +/// What the audit line knows so far. The caller key and `Authorization` never enter it. +pub(crate) struct Trail { + started: Instant, + method: String, + identity: String, + route: Option, + path: String, + evidence: Option, +} + +impl Trail { + fn new(method: &str) -> Trail { + Trail { + started: Instant::now(), + method: method.to_string(), + identity: String::new(), + route: None, + path: String::new(), + evidence: None, + } + } + + pub(crate) fn rec(&self, decision: &'static str, code: Option<&str>, status: u16) -> AuditRec { + AuditRec { + identity: self.identity.clone(), + session: None, + generation: None, + route: self.route.clone(), + method: self.method.clone(), + path: self.path.clone(), + aws_target: None, + decision, + code: code.map(str::to_string), + status, + duration_ms: u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + bytes_sent: None, + } + } + + fn write_evidence(&self, audit: &AuditSink, status: u16) { + if let Some(e) = &self.evidence { + let mut e = e.clone(); + e.status = status; + e.route.clone_from(&self.route); + e.path.clone_from(&self.path); + audit.write_line(&e.to_json_line()); + } + } +} + +impl std::fmt::Debug for Trail { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Trail") + .field("method", &self.method) + .field("identity", &self.identity) + .field("route", &self.route) + .field("path", &self.path) + .finish() + } +} + +/// A gate refusal: audit line, evidence line, status, `X-AP-Decision` and JSON body. +pub(crate) fn refuse(app: &PtApp, trail: &Trail, code: Code) -> Response { + let (status, decision, body) = render_passthrough(code); + app.audit + .write_rec(&trail.rec("deny", Some(code.code_str()), status)); + trail.write_evidence(&app.audit, status); + let mut r = Response::new(Body::from(body)); + *r.status_mut() = StatusCode::from_u16(status).unwrap_or(StatusCode::SERVICE_UNAVAILABLE); + r.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + r.headers_mut() + .insert(DECISION_HEADER, HeaderValue::from_static(decision.as_str())); + r +} + +/// A failure after the first upstream request byte: one audit line, then the caller's +/// connection is closed with no synthetic answer. +fn abort(app: &PtApp, trail: &Trail, code: &str) -> ConnAbort { + app.audit.write_rec(&trail.rec("allow", Some(code), 0)); + trail.write_evidence(&app.audit, 0); + ConnAbort +} + +/// The caller whose key hashes to the presented key. Every identity is compared, so the time +/// taken does not show which identity matched. +fn caller_identity<'a>(cfg: &'a Config, caller_key: &str) -> Option<&'a Identity> { + let presented = sha256_hex(caller_key); + let mut found = None; + for id in &cfg.identities { + let same: bool = presented + .as_bytes() + .ct_eq(id.caller_key_sha256.as_bytes()) + .into(); + if same && found.is_none() { + found = Some(id); + } + } + found +} + +/// Writes the allow line when the response body ends, or when the client drops it. +struct StreamAudit { + app: Arc, + trail: Trail, + status: u16, + reset: bool, +} + +impl Drop for StreamAudit { + fn drop(&mut self) { + let code = self.reset.then_some("upstream_reset"); + self.app + .audit + .write_rec(&self.trail.rec("allow", code, self.status)); + self.trail.write_evidence(&self.app.audit, self.status); + } +} + +fn audited( + stream: S, + audit: StreamAudit, + deadline: Instant, + idle: Duration, +) -> impl Stream> +where + S: Stream> + Send + Unpin + 'static, +{ + futures_util::stream::unfold( + (Box::pin(stream), audit, false), + move |(mut s, mut a, done)| async move { + if done { + return None; + } + let left = deadline.saturating_duration_since(Instant::now()); + let wait = left.min(idle); + match tokio::time::timeout(wait, s.next()).await { + Ok(Some(Ok(bytes))) => Some((Ok(bytes), (s, a, false))), + Ok(Some(Err(e))) => { + a.reset = true; + Some((Err(io::Error::other(e)), (s, a, true))) + } + Ok(None) => None, + Err(_) => { + a.reset = true; + Some(( + Err(io::Error::new(io::ErrorKind::TimedOut, "upstream stalled")), + (s, a, true), + )) + } + } + }, + ) +} + +/// Handle one request on the public listener. +pub async fn handle(app: Arc, req: Request) -> Result, ConnAbort> { + let (mut parts, body) = req.into_parts(); + let mut trail = Trail::new(parts.method.as_str()); + + // 1. CONNECT and Upgrade. + if parts.method == Method::CONNECT { + return Ok(refuse(&app, &trail, Code::ConnectRefused)); + } + if parts.headers.contains_key(header::UPGRADE) { + return Ok(refuse(&app, &trail, Code::WebsocketUnsupported)); + } + + // 2. Policy snapshot, which also holds the public authority. + let Some(policy) = app.policy.current() else { + return Ok(refuse(&app, &trail, Code::PolicyUnavailable)); + }; + let Some(pt) = policy.cfg.passthrough.as_ref() else { + return Ok(refuse(&app, &trail, Code::PolicyUnavailable)); + }; + + // 3. Canonical request target, host and path. + if let Err(code) = canon::check_origin_form( + &parts.uri, + &parts.headers, + parts.version, + &pt.public_authority, + ) { + return Ok(refuse(&app, &trail, code)); + } + if canon::path_ambiguous(parts.uri.path()) { + return Ok(refuse(&app, &trail, Code::PathAmbiguous)); + } + // 4. Framing. + if canon::framing_refused(&parts.headers, &pt.caller_key_header) { + return Ok(refuse(&app, &trail, Code::FramingRefused)); + } + + // 5. Caller key: from its header OR from a `/ap//` path prefix, exactly one. + // Mark every header value sensitive first so no Debug print of the request or its headers + // can show it. The prefix is stripped here: everything after this point sees `eff_path`. + let mut header_present = false; + if let Ok(name) = http::HeaderName::from_bytes(pt.caller_key_header.as_bytes()) { + if let http::header::Entry::Occupied(mut e) = parts.headers.entry(name) { + header_present = true; + for v in e.iter_mut() { + v.set_sensitive(true); + } + } + } + let path_form = parts.uri.path().starts_with("/ap/"); + if header_present && path_form { + return Ok(refuse(&app, &trail, Code::CallerKeyAmbiguous)); + } + let (key, eff_path) = if path_form { + // `parse_ap_path` validates the prefix. Whatever follows the key, byte for byte, is the + // path the rest of the pipeline sees. + let path = parts.uri.path(); + let key = match canon::parse_ap_path(path) { + Ok(ap) => ap.caller_key, + // The key is well formed but the route segment is empty: authenticate the key + // first, so an unknown key is still 401; `/` then names no route. + Err(Code::RouteUnknown) => path + .strip_prefix("/ap/") + .and_then(|r| r.split('/').next()) + .unwrap_or_default(), + Err(code) => return Ok(refuse(&app, &trail, code)), + }; + ( + key.to_string(), + path["/ap/".len() + key.len()..].to_string(), + ) + } else { + match canon::caller_key_from_header(&parts.headers, &pt.caller_key_header) { + Ok(k) => (k, parts.uri.path().to_string()), + Err(code) => return Ok(refuse(&app, &trail, code)), + } + }; + let Some(identity) = caller_identity(&policy.cfg, &key) else { + return Ok(refuse(&app, &trail, Code::CallerRejected)); + }; + drop(key); + trail.identity.clone_from(&identity.name); + trail.evidence = Some(Evidence::collect( + &identity.name, + parts.method.as_str(), + parts.version, + &parts.headers, + )); + + #[cfg(feature = "matrix-upstream")] + if eff_path == crate::matrix_hooks::PANIC_PATH { + let auth = parts + .headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + panic!("test panic injection {auth}"); + } + + #[cfg(feature = "stage1-probe")] + if policy.cfg.probe.enabled && eff_path.starts_with(crate::probe::PREFIX) { + return Ok(crate::probe::handle(&app, &trail, &parts.method, &eff_path, body, pt).await); + } + + // 6. Route name in the path, mapped by policy to a fixed host. + let (route_name, rel) = match canon::parse_route_path(&eff_path) { + Ok(r) => r, + Err(code) => return Ok(refuse(&app, &trail, code)), + }; + let Some(route) = policy.snap.route(route_name) else { + return Ok(refuse(&app, &trail, Code::RouteUnknown)); + }; + trail.route = Some(route.name.clone()); + trail.path = canon::redact_path(&path_only(&rel)); + + // 7. More than one Authorization header is refused: the gate cannot say which one is read. + if parts.headers.get_all(header::AUTHORIZATION).iter().count() > 1 { + return Ok(refuse(&app, &trail, Code::AuthorizationDuplicate)); + } + + // 8. Grant. Everything not granted is 423 no_grant. + if policy + .snap + .evaluate( + &identity.name, + &route.name, + parts.method.as_str(), + &rel, + &[], + ) + .is_err() + { + return Ok(refuse(&app, &trail, Code::NoGrant)); + } + + // 9. Declared length over the cap. + let max_body = policy.cfg.limits.max_body_bytes; + let declared = forward::declared_length(&parts.headers); + if declared.is_some_and(|n| n > max_body) { + return Ok(refuse(&app, &trail, Code::BodyTooLarge)); + } + + // 10. Forward. The path goes upstream raw, with the query raw. + let headers = forward::passthrough_headers(&parts.headers, route, pt); + let rest = match parts.uri.query() { + Some(q) => format!("{rel}?{q}"), + None => rel.clone(), + }; + let url = forward::upstream_url(route, &rest); + let has_body = + parts.headers.contains_key(header::TRANSFER_ENCODING) || declared.is_some_and(|n| n > 0); + let flags = BodyFlags::default(); + let mut builder = app + .client + .request(parts.method.clone(), url) + .headers(headers); + if has_body { + builder = builder.body(forward::guarded_body( + body, + max_body, + Duration::from_secs(pt.body_read_secs), + flags.clone(), + )); + } + let deadline = Instant::now() + Duration::from_secs(pt.request_deadline_secs); + let sent = tokio::time::timeout_at(deadline.into(), builder.send()).await; + let upstream = match sent { + Ok(Ok(r)) => r, + Ok(Err(e)) => { + let sent_any = flags.sent_any.load(Ordering::SeqCst); + if flags.overflow.load(Ordering::SeqCst) { + return if sent_any { + Err(abort(&app, &trail, "body_failed_after_send")) + } else { + Ok(refuse(&app, &trail, Code::BodyTooLarge)) + }; + } + if flags.stalled.load(Ordering::SeqCst) { + return if sent_any { + Err(abort(&app, &trail, "body_failed_after_send")) + } else { + Ok(refuse(&app, &trail, Code::BodyReadTimeout)) + }; + } + if e.is_connect() { + return Ok(refuse(&app, &trail, Code::ConnectFailed)); + } + return Err(abort(&app, &trail, "upstream_reset")); + } + Err(_) => return Err(abort(&app, &trail, "upstream_reset")), + }; + + // 11. The response streams back. The allow line is written when the body ends. + let status = upstream.status(); + let out_headers = forward::response_headers(upstream.headers()); + let audit = StreamAudit { + app: Arc::clone(&app), + trail, + status: status.as_u16(), + reset: false, + }; + let idle = Duration::from_secs(pt.upstream_idle_secs); + let stream = audited(upstream.bytes_stream(), audit, deadline, idle); + let mut response = Response::new(Body::from_stream(stream)); + *response.status_mut() = status; + *response.headers_mut() = out_headers; + Ok(response) +} diff --git a/crates/ap-proxy/src/passthrough/tests.rs b/crates/ap-proxy/src/passthrough/tests.rs new file mode 100644 index 0000000..4a0ede8 --- /dev/null +++ b/crates/ap-proxy/src/passthrough/tests.rs @@ -0,0 +1,1046 @@ +use std::sync::atomic::Ordering; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::body::Body; +use bytes::Bytes; +use http::Request; +use http_body_util::BodyExt; + +use super::*; +use crate::test_support::{ + buffer_sink, caller_key, client_for, start_upstream, Scratch, Upstream, HOST, +}; +use ap_broker::registry::sha256_hex; + +const AUTH: &str = "gate.example.test"; +const SENTINEL: &str = "SENTINEL-DISCORD-TOKEN-0001"; +const PATH_TOKEN: &str = "SENTINEL-PATH-TOKEN-0002"; + +struct Pt { + app: Arc, + key: String, + audit: Arc>>, + up: Upstream, + _s: Scratch, +} + +impl Pt { + async fn new(tag: &str) -> Pt { + Self::with(tag, "").await + } + + async fn with(tag: &str, pt_extra: &str) -> Pt { + let up = start_upstream().await; + let s = Scratch::new(tag); + let key = caller_key(); + let text = format!( + r#"version = 1 + +[listen] +proxy = "127.0.0.1:8443" + +[limits] +max_body_bytes = 1024 + +[passthrough] +public_authority = "{AUTH}" +body_read_secs = 1 +{pt_extra} + +[[identity]] +name = "muse-pilot" +caller_key_sha256 = "{sha}" + +[[route]] +name = "discord" +host = "{HOST}" +port = {port} +mode = "passthrough" + +[[grant]] +identity = "muse-pilot" +route = "discord" +methods = ["GET"] +paths = ["/api/", "/xap", "/me"] + +[[grant]] +identity = "muse-pilot" +route = "discord" +methods = ["POST"] +paths = ["/up/"] + +[probe] +enabled = true +"#, + sha = sha256_hex(&key), + port = up.addr.port() + ); + let path = s.path().join("policy.toml"); + std::fs::write(&path, &text).unwrap(); + let cfg = ap_core::config::load(&text).expect("valid"); + let (sink, audit) = buffer_sink(); + let app = PtApp::new(path, cfg, sink, client_for(&up)); + Pt { + app, + key, + audit, + up, + _s: s, + } + } + + fn req(&self, method: &str, path: &str) -> http::request::Builder { + Request::builder() + .method(method) + .uri(path) + .header("host", AUTH) + .header("x-ap-caller-key", self.key.as_str()) + .header("authorization", format!("Bot {SENTINEL}")) + } + + fn audit_text(&self) -> String { + String::from_utf8_lossy(&self.audit.lock().unwrap()).into_owned() + } + + fn hits(&self) -> usize { + self.up.hits.load(Ordering::SeqCst) + } + + async fn send(&self, r: Request) -> Result<(http::response::Parts, Bytes), ()> { + match handle(Arc::clone(&self.app), r).await { + Ok(resp) => { + let (p, b) = resp.into_parts(); + let bytes = b.collect().await.map(|c| c.to_bytes()).unwrap_or_default(); + Ok((p, bytes)) + } + Err(_) => Err(()), + } + } +} + +fn decision(p: &http::response::Parts) -> String { + p.headers + .get("x-ap-decision") + .map(|v| v.to_str().unwrap().to_string()) + .unwrap_or_default() +} + +fn code(b: &Bytes) -> String { + let v: serde_json::Value = serde_json::from_slice(b).unwrap(); + v["code"].as_str().unwrap().to_string() +} + +#[tokio::test] +async fn get_passes_and_upstream_x_ap_headers_are_kept() { + let t = Pt::new("get").await; + let (p, b) = t + .send(t.req("GET", "/discord/xap").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(p.status, 200); + assert_eq!(decision(&p), "denied"); + assert_eq!(p.headers.get("x-ap-other").unwrap(), "kept"); + assert_eq!(p.headers.get("x-plain").unwrap(), "yes"); + assert_eq!(&b[..], b"upstream-body"); +} + +#[tokio::test] +async fn forwarded_headers_drop_the_caller_key_and_keep_authorization() { + let t = Pt::new("fwd").await; + let r = t + .req("GET", "/discord/api/echo2?x=1") + .header("x-ap-other", "1") + .header("forwarded", "for=1") + .header("tailscale-user-login", "someone") + .header("cookie", "a=b") + .body(Body::empty()) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_eq!(p.status, 200); + let v: serde_json::Value = serde_json::from_slice(&b).unwrap(); + let names: Vec = v["headers"] + .as_array() + .unwrap() + .iter() + .map(|h| h[0].as_str().unwrap().to_string()) + .collect(); + assert!(names.contains(&"authorization".to_string())); + for gone in [ + "x-ap-caller-key", + "x-ap-other", + "forwarded", + "tailscale-user-login", + "cookie", + ] { + assert!( + !names.contains(&gone.to_string()), + "{gone} reached upstream" + ); + } + let auth = v["headers"] + .as_array() + .unwrap() + .iter() + .find(|h| h[0] == "authorization") + .unwrap(); + assert_eq!(auth[1], format!("Bot {SENTINEL}")); + assert!(v["path"].as_str().unwrap().ends_with("/api/echo2?x=1")); + assert!(!t.audit_text().contains(&t.key)); +} + +#[tokio::test] +async fn write_is_423_no_grant_and_nothing_goes_upstream() { + let t = Pt::new("post").await; + let r = t + .req("POST", "/discord/api/v10/channels/1/messages") + .header("content-length", "2") + .body(Body::from("{}")) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_eq!(p.status, 423); + assert_eq!(decision(&p), "denied"); + assert_eq!(code(&b), "no_grant"); + assert_eq!(t.hits(), 0); +} + +#[tokio::test] +async fn refusal_table() { + let t = Pt::new("refuse").await; + let mk = |f: &dyn Fn(http::request::Builder) -> http::request::Builder| { + f(Request::builder() + .method("GET") + .uri("/discord/api/x") + .header("host", AUTH)) + .body(Body::empty()) + .unwrap() + }; + let key = t.key.clone(); + let cases: Vec<(&str, Request, u16, &str, &str)> = vec![ + ( + "missing key", + mk(&|b| b), + 401, + "rejected", + "caller_rejected", + ), + ( + "malformed key", + mk(&|b| b.header("x-ap-caller-key", "apk_short")), + 401, + "rejected", + "caller_rejected", + ), + ( + "unknown key", + mk(&|b| b.header("x-ap-caller-key", caller_key())), + 401, + "rejected", + "caller_rejected", + ), + ( + "duplicate key", + mk(&|b| { + b.header("x-ap-caller-key", key.as_str()) + .header("x-ap-caller-key", key.as_str()) + }), + 401, + "rejected", + "caller_rejected", + ), + ( + "unknown route", + Request::builder() + .uri("/nope/api/x") + .header("host", AUTH) + .header("x-ap-caller-key", key.as_str()) + .body(Body::empty()) + .unwrap(), + 423, + "denied", + "route_unknown", + ), + ( + "duplicate authorization", + mk(&|b| { + b.header("x-ap-caller-key", key.as_str()) + .header("authorization", "a") + .header("authorization", "b") + }), + 400, + "denied", + "authorization_duplicate", + ), + ( + "connect", + Request::builder() + .method("CONNECT") + .uri("/discord/api/x") + .header("host", AUTH) + .body(Body::empty()) + .unwrap(), + 405, + "denied", + "connect_refused", + ), + ( + "upgrade", + mk(&|b| b.header("upgrade", "websocket")), + 501, + "denied", + "websocket_unsupported", + ), + ( + "wrong host", + Request::builder() + .uri("/discord/api/x") + .header("host", "evil.test") + .header("x-ap-caller-key", key.as_str()) + .body(Body::empty()) + .unwrap(), + 400, + "denied", + "host_rejected", + ), + ( + "framing", + mk(&|b| { + b.header("x-ap-caller-key", key.as_str()) + .header("content-length", "2") + .header("transfer-encoding", "chunked") + }), + 400, + "denied", + "framing_refused", + ), + ]; + for (name, req, status, dec, c) in cases { + let (p, b) = t.send(req).await.unwrap(); + assert_eq!(p.status.as_u16(), status, "{name}"); + assert_eq!(decision(&p), dec, "{name}"); + assert_eq!(code(&b), c, "{name}"); + } + assert_eq!(t.hits(), 0); +} + +#[tokio::test] +async fn path_variants_are_refused_with_no_upstream_hit() { + let t = Pt::new("paths").await; + for p in [ + "/discord/api/../x", + "/discord/api/%2e%2e/x", + "/discord/api/%2e/x", + "/discord/api%2fx", + "/discord//api/x", + "/discord/api/%252e%252e/x", + ] { + let (parts, b) = t + .send(t.req("GET", p).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(parts.status, 400, "{p}"); + assert_eq!(code(&b), "path_ambiguous", "{p}"); + assert_eq!(decision(&parts), "denied"); + } + assert_eq!(t.hits(), 0); +} + +#[tokio::test] +async fn no_sentinel_in_audit_for_any_outcome() { + let t = Pt::new("sentinel").await; + let hook = format!("/discord/api/v10/webhooks/1/{PATH_TOKEN}/github"); + let inter = format!("/discord/api/v10/interactions/1/{PATH_TOKEN}/callback"); + let _ = t + .send(t.req("GET", &hook).body(Body::empty()).unwrap()) + .await; + let _ = t + .send(t.req("POST", &inter).body(Body::empty()).unwrap()) + .await; + let _ = t + .send( + t.req("GET", "/discord/api/echo2") + .body(Body::empty()) + .unwrap(), + ) + .await; + let big = t + .req("POST", "/discord/up/echo2") + .header("content-length", "5000") + .body(Body::empty()) + .unwrap(); + let _ = t.send(big).await; + let bad = Request::builder() + .uri("/discord/api/x") + .header("host", AUTH) + .header("x-ap-caller-key", "apk_bad") + .header("authorization", format!("Bot {SENTINEL}")) + .body(Body::empty()) + .unwrap(); + let _ = t.send(bad).await; + let text = t.audit_text(); + assert!(!text.is_empty()); + for s in [SENTINEL, PATH_TOKEN, t.key.as_str()] { + assert!(!text.contains(s), "{s} leaked: {text}"); + } + assert!(text.contains("")); + assert!(text.contains("\"evidence\"")); + let tr = Trail::new("GET"); + assert!(!format!("{tr:?}").contains(SENTINEL)); +} + +#[tokio::test] +async fn body_over_declared_cap_is_413() { + let t = Pt::new("cap").await; + let r = t + .req("POST", "/discord/up/echo2") + .header("content-length", "5000") + .body(Body::empty()) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_eq!(p.status, 413); + assert_eq!(code(&b), "body_too_large"); + assert_eq!(t.hits(), 0); +} + +fn chan_body() -> ( + tokio::sync::mpsc::Sender>, + Body, +) { + let (tx, mut rx) = tokio::sync::mpsc::channel::>(4); + let s = futures_util::stream::poll_fn(move |cx| rx.poll_recv(cx)); + (tx, Body::from_stream(s)) +} + +#[tokio::test] +async fn stall_after_a_prefix_aborts_with_body_failed_after_send() { + let t = Pt::new("stall1").await; + let (tx, body) = chan_body(); + tx.send(Ok(Bytes::from_static(b"abc"))).await.unwrap(); + let r = t + .req("POST", "/discord/up/echo2") + .header("transfer-encoding", "chunked") + .body(body) + .unwrap(); + assert!(t.send(r).await.is_err()); + let text = t.audit_text(); + assert!(text.contains("body_failed_after_send"), "{text}"); + assert_eq!(text.matches("\"decision\"").count(), 1); + drop(tx); +} + +#[tokio::test] +async fn stall_before_the_first_byte_is_503() { + let t = Pt::new("stall0").await; + let (tx, body) = chan_body(); + let r = t + .req("POST", "/discord/up/echo2") + .header("transfer-encoding", "chunked") + .body(body) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_eq!(p.status, 503); + assert_eq!(decision(&p), "unavailable"); + assert_eq!(code(&b), "body_read_timeout"); + drop(tx); +} + +#[tokio::test] +async fn undeclared_over_cap_after_a_prefix_aborts() { + let t = Pt::new("over1").await; + let (tx, body) = chan_body(); + tx.send(Ok(Bytes::from(vec![1u8; 600]))).await.unwrap(); + tx.send(Ok(Bytes::from(vec![1u8; 600]))).await.unwrap(); + let r = t + .req("POST", "/discord/up/echo2") + .header("transfer-encoding", "chunked") + .body(body) + .unwrap(); + assert!(t.send(r).await.is_err()); + assert!(t.audit_text().contains("body_failed_after_send")); + drop(tx); +} + +#[tokio::test] +async fn undeclared_over_cap_before_any_byte_is_413() { + let t = Pt::new("over0").await; + let (tx, body) = chan_body(); + tx.send(Ok(Bytes::from(vec![1u8; 2000]))).await.unwrap(); + let r = t + .req("POST", "/discord/up/echo2") + .header("transfer-encoding", "chunked") + .body(body) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_eq!(p.status, 413); + assert_eq!(code(&b), "body_too_large"); + drop(tx); +} + +#[tokio::test] +async fn chunked_body_reaches_upstream_chunked_without_content_length() { + let t = Pt::new("chunked").await; + let (tx, body) = chan_body(); + tx.send(Ok(Bytes::from_static(b"hello "))).await.unwrap(); + tx.send(Ok(Bytes::from_static(b"world"))).await.unwrap(); + drop(tx); + let r = t + .req("POST", "/discord/up/echo2") + .header("transfer-encoding", "chunked") + .body(body) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_eq!(p.status, 200); + let v: serde_json::Value = serde_json::from_slice(&b).unwrap(); + assert_eq!(v["body_len"], 11); + let names: Vec<&str> = v["headers"] + .as_array() + .unwrap() + .iter() + .map(|h| h[0].as_str().unwrap()) + .collect(); + assert!(names.contains(&"transfer-encoding")); + assert!(!names.contains(&"content-length")); +} + +#[tokio::test] +async fn unreachable_upstream_is_503_connect_failed() { + let t = Pt::new("down").await; + // Point the route at a closed port by rewriting the policy file. + let text = std::fs::read_to_string(t._s.path().join("policy.toml")).unwrap(); + let dead = text.replace(&format!("port = {}", t.up.addr.port()), "port = 9"); + std::fs::write(t._s.path().join("policy.toml"), dead).unwrap(); + tokio::time::sleep(Duration::from_millis(20)).await; + let (p, b) = t + .send(t.req("GET", "/discord/api/x").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(p.status, 503); + assert_eq!(code(&b), "connect_failed"); + assert_eq!(decision(&p), "unavailable"); +} + +#[cfg(feature = "stage1-probe")] +mod probe_tests { + use super::*; + + async fn probe(t: &Pt, key: bool, path: &str) -> (http::response::Parts, Bytes) { + let mut b = Request::builder() + .method("POST") + .uri(path) + .header("host", AUTH) + .header("content-length", "2"); + if key { + b = b.header("x-ap-caller-key", t.key.as_str()); + } + t.send(b.body(Body::from("{}")).unwrap()).await.unwrap() + } + + #[tokio::test] + async fn probe_needs_a_caller_key() { + let t = Pt::new("probe-key").await; + let (p, _) = probe(&t, false, "/__ap_probe/200/1").await; + assert_eq!(p.status, 401); + assert_eq!(decision(&p), "rejected"); + } + + #[tokio::test] + async fn probe_answers_each_status_with_its_decision() { + let t = Pt::new("probe-status").await; + for (status, dec) in [ + (200, ""), + (410, "expired"), + (423, "denied"), + (503, "unavailable"), + ] { + let (p, _) = probe(&t, true, &format!("/__ap_probe/{status}/1")).await; + assert_eq!(p.status.as_u16(), status); + assert_eq!(decision(&p), dec); + assert!(p.headers.get("retry-after").is_none()); + } + assert!(t.audit_text().contains("\"event\":\"completed\"")); + assert_eq!(t.hits(), 0); + } + + #[tokio::test] + async fn probe_rejects_bad_parameters() { + let t = Pt::new("probe-bad").await; + for path in [ + "/__ap_probe/201/1", + "/__ap_probe/200/7", + "/__ap_probe/200", + "/__ap_probe/x/1", + ] { + let (p, b) = probe(&t, true, path).await; + assert_eq!(p.status, 400, "{path}"); + assert_eq!(code(&b), "probe_params"); + } + } + + #[tokio::test] + async fn dropping_the_handler_records_client_gone() { + let t = Pt::new("probe-gone").await; + let r = Request::builder() + .method("POST") + .uri("/__ap_probe/200/10") + .header("host", AUTH) + .header("x-ap-caller-key", t.key.as_str()) + .header("content-length", "2") + .body(Body::from("{}")) + .unwrap(); + let fut = handle(Arc::clone(&t.app), r); + let _ = tokio::time::timeout(Duration::from_millis(200), fut).await; + assert!(t.audit_text().contains("\"event\":\"client_gone\"")); + } +} + +// ---- caller key in the path (`/ap///`) ---- + +impl Pt { + /// A request carrying the caller key in the path prefix and no caller-key header. + fn preq(&self, method: &str, path: &str) -> http::request::Builder { + Request::builder() + .method(method) + .uri(format!("/ap/{}{path}", self.key)) + .header("host", AUTH) + .header("authorization", format!("Bot {SENTINEL}")) + } +} + +/// Exact body, header and content type of a gate refusal. +fn assert_refusal( + name: &str, + p: &http::response::Parts, + b: &Bytes, + status: u16, + dec: &str, + c: &str, +) { + assert_eq!(p.status.as_u16(), status, "{name}"); + assert_eq!(decision(p), dec, "{name}"); + assert_eq!( + p.headers.get("content-type").unwrap(), + "application/json", + "{name}" + ); + let want = format!("{{\"ap_decision\":\"{dec}\",\"code\":\"{c}\"}}"); + assert_eq!(std::str::from_utf8(b).unwrap(), want, "{name}"); +} + +#[tokio::test] +async fn path_key_is_stripped_routed_and_forwarded() { + let t = Pt::new("pkey").await; + let (p, b) = t + .send( + t.preq("GET", "/discord/api/echo2?x=1") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(p.status, 200); + let v: serde_json::Value = serde_json::from_slice(&b).unwrap(); + let path = v["path"].as_str().unwrap(); + assert!(path.ends_with("/api/echo2?x=1"), "{path}"); + assert!(!path.contains("/ap/") && !path.contains(&t.key), "{path}"); + let auth = v["headers"] + .as_array() + .unwrap() + .iter() + .find(|h| h[0] == "authorization") + .unwrap(); + assert_eq!(auth[1], format!("Bot {SENTINEL}")); + assert!(!v.to_string().contains(&t.key)); + let text = t.audit_text(); + assert!(text.contains("\"path\":\"/api/echo2\""), "{text}"); + assert!(!text.contains(&t.key) && !text.contains("/ap/"), "{text}"); +} + +#[tokio::test] +async fn both_sources_are_ambiguous_even_when_each_is_valid() { + let t = Pt::new("both").await; + let r = t + .preq("GET", "/discord/api/x") + .header("x-ap-caller-key", t.key.as_str()) + .body(Body::empty()) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_refusal("both", &p, &b, 400, "denied", "caller_key_ambiguous"); + // Also when the header is not a valid key: still exactly-one-source, not a 401. + let r = t + .preq("GET", "/discord/api/x") + .header("x-ap-caller-key", "apk_bad") + .body(Body::empty()) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_refusal("both bad", &p, &b, 400, "denied", "caller_key_ambiguous"); + assert_eq!(t.hits(), 0); + assert!(!t.audit_text().contains(&t.key)); +} + +#[tokio::test] +async fn path_key_failures_are_401_and_leak_nothing() { + let t = Pt::new("pbad").await; + let other = caller_key(); + let upper = t.key.to_ascii_uppercase(); + let cases = [ + ("unknown", format!("/ap/{other}/discord/api/x")), + ("short", "/ap/apk_short/discord/api/x".to_string()), + ("uppercase", format!("/ap/{upper}/discord/api/x")), + ("no route", "/ap/apk_short/".to_string()), + ("key only", format!("/ap/{other}")), + ]; + for (name, path) in cases { + let r = Request::builder() + .uri(path) + .header("host", AUTH) + .body(Body::empty()) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_refusal(name, &p, &b, 401, "rejected", "caller_rejected"); + assert!(!String::from_utf8_lossy(&b).contains("apk_"), "{name}"); + } + // A valid key with no route is refused after authentication, as route_unknown. + for path in [format!("/ap/{}/", t.key), format!("/ap/{}", t.key)] { + let r = Request::builder() + .uri(path.clone()) + .header("host", AUTH) + .body(Body::empty()) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + if path.ends_with('/') { + assert_refusal("no route", &p, &b, 423, "denied", "route_unknown"); + } else { + assert_eq!(p.status, 401); + } + } + assert_eq!(t.hits(), 0); + let text = t.audit_text(); + for k in [t.key.as_str(), other.as_str(), "/ap/"] { + assert!(!text.contains(k), "{k} leaked: {text}"); + } +} + +#[tokio::test] +async fn path_form_keeps_the_other_checks() { + let t = Pt::new("pchecks").await; + for (path, c) in [ + ("/discord/api/../x", "path_ambiguous"), + ("/discord/api/%2e%2e/x", "path_ambiguous"), + ("/nope/api/x", "route_unknown"), + ] { + let (p, b) = t + .send(t.preq("GET", path).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(code(&b), c, "{path}"); + assert_eq!(decision(&p), "denied"); + } + let (p, b) = t + .send( + t.preq("POST", "/discord/api/v10/channels/1/messages") + .header("content-length", "2") + .body(Body::from("{}")) + .unwrap(), + ) + .await + .unwrap(); + assert_refusal("write", &p, &b, 423, "denied", "no_grant"); + assert_eq!(t.hits(), 0); + assert!(!t.audit_text().contains(&t.key)); +} + +#[tokio::test] +async fn no_path_key_in_audit_for_any_outcome() { + let t = Pt::new("psentinel").await; + let hook = format!("/discord/api/v10/webhooks/1/{PATH_TOKEN}/github"); + let _ = t + .send(t.preq("GET", &hook).body(Body::empty()).unwrap()) + .await; + let _ = t + .send( + t.preq("GET", "/discord/api/echo2") + .body(Body::empty()) + .unwrap(), + ) + .await; + let _ = t + .send( + t.preq("POST", "/discord/up/echo2") + .header("content-length", "5000") + .body(Body::empty()) + .unwrap(), + ) + .await; + let _ = t + .send( + t.preq("GET", "/discord/api/../x") + .body(Body::empty()) + .unwrap(), + ) + .await; + let _ = t + .send( + t.preq("GET", "/discord/api/x") + .header("x-ap-caller-key", t.key.as_str()) + .body(Body::empty()) + .unwrap(), + ) + .await; + let (tx, body) = chan_body(); + let r = t + .preq("POST", "/discord/up/echo2") + .header("transfer-encoding", "chunked") + .body(body) + .unwrap(); + let _ = t.send(r).await; + drop(tx); + let text = t.audit_text(); + assert!(!text.is_empty()); + for s in [SENTINEL, PATH_TOKEN, t.key.as_str(), "/ap/"] { + assert!(!text.contains(s), "{s} leaked: {text}"); + } + assert!(text.contains("\"evidence\"")); +} + +#[tokio::test] +async fn path_form_connect_failed_and_policy_unavailable_leak_nothing() { + let t = Pt::new("pdown").await; + let policy = t._s.path().join("policy.toml"); + let text = std::fs::read_to_string(&policy).unwrap(); + std::fs::write( + &policy, + text.replace(&format!("port = {}", t.up.addr.port()), "port = 9"), + ) + .unwrap(); + tokio::time::sleep(Duration::from_millis(20)).await; + let (p, b) = t + .send(t.preq("GET", "/discord/api/x").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_refusal("connect", &p, &b, 503, "unavailable", "connect_failed"); + std::fs::remove_file(&policy).unwrap(); + let (p, b) = t + .send(t.preq("GET", "/discord/api/x").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_refusal("policy", &p, &b, 503, "unavailable", "policy_unavailable"); + let text = t.audit_text(); + assert!(!text.contains(&t.key) && !text.contains("/ap/"), "{text}"); +} + +/// Every refusal row of the outcome table (design 3.5), in both caller-key forms: status, +/// `X-AP-Decision` header and the exact fixed JSON body. +#[tokio::test] +async fn every_refusal_row_carries_the_decision_in_header_and_body() { + let t = Pt::new("rows").await; + let key = t.key.clone(); + let other = caller_key(); + // (name, form, request, status, decision, code); form 'h' = header, 'p' = path prefix. + let mut cases: Vec<(String, Request, u16, &str, &str)> = Vec::new(); + for form in ['h', 'p'] { + let mk = |method: &str, path: &str| -> http::request::Builder { + if form == 'h' { + t.req(method, path) + } else { + t.preq(method, path) + } + }; + let n = |s: &str| format!("{s} [{form}]"); + cases.push(( + n("401 unknown key"), + if form == 'h' { + Request::builder() + .uri("/discord/api/x") + .header("host", AUTH) + .header("x-ap-caller-key", other.as_str()) + .body(Body::empty()) + .unwrap() + } else { + Request::builder() + .uri(format!("/ap/{other}/discord/api/x")) + .header("host", AUTH) + .body(Body::empty()) + .unwrap() + }, + 401, + "rejected", + "caller_rejected", + )); + cases.push(( + n("400 path"), + mk("GET", "/discord/api/../x").body(Body::empty()).unwrap(), + 400, + "denied", + "path_ambiguous", + )); + cases.push(( + n("400 authorization dup"), + mk("GET", "/discord/api/x") + .header("authorization", "b") + .body(Body::empty()) + .unwrap(), + 400, + "denied", + "authorization_duplicate", + )); + cases.push(( + n("400 framing"), + mk("GET", "/discord/api/x") + .header("content-length", "2") + .header("transfer-encoding", "chunked") + .body(Body::empty()) + .unwrap(), + 400, + "denied", + "framing_refused", + )); + cases.push(( + n("501 upgrade"), + mk("GET", "/discord/api/x") + .header("upgrade", "websocket") + .body(Body::empty()) + .unwrap(), + 501, + "denied", + "websocket_unsupported", + )); + cases.push(( + n("413 declared"), + mk("POST", "/discord/up/echo2") + .header("content-length", "5000") + .body(Body::empty()) + .unwrap(), + 413, + "denied", + "body_too_large", + )); + cases.push(( + n("423 no grant"), + mk("DELETE", "/discord/api/x").body(Body::empty()).unwrap(), + 423, + "denied", + "no_grant", + )); + cases.push(( + n("423 route"), + mk("GET", "/nope/api/x").body(Body::empty()).unwrap(), + 423, + "denied", + "route_unknown", + )); + } + cases.push(( + "400 both sources".to_string(), + t.preq("GET", "/discord/api/x") + .header("x-ap-caller-key", key.as_str()) + .body(Body::empty()) + .unwrap(), + 400, + "denied", + "caller_key_ambiguous", + )); + cases.push(( + "400 host".to_string(), + Request::builder() + .uri("/discord/api/x") + .header("host", "evil.test") + .header("x-ap-caller-key", key.as_str()) + .body(Body::empty()) + .unwrap(), + 400, + "denied", + "host_rejected", + )); + cases.push(( + "405 connect".to_string(), + Request::builder() + .method("CONNECT") + .uri("/discord/api/x") + .header("host", AUTH) + .body(Body::empty()) + .unwrap(), + 405, + "denied", + "connect_refused", + )); + for (name, req, status, dec, c) in cases { + let (p, b) = t.send(req).await.unwrap(); + assert_refusal(&name, &p, &b, status, dec, c); + let text = String::from_utf8_lossy(&b); + assert!(!text.contains("apk_") && !text.contains(SENTINEL), "{name}"); + } + assert_eq!(t.hits(), 0); + let text = t.audit_text(); + for k in [key.as_str(), other.as_str(), "/ap/"] { + assert!(!text.contains(k), "{k} leaked: {text}"); + } + + // 503 body_read_timeout, in both forms. + for form in ['h', 'p'] { + let (tx, body) = chan_body(); + let b = if form == 'h' { + t.req("POST", "/discord/up/echo2") + } else { + t.preq("POST", "/discord/up/echo2") + }; + let r = b.header("transfer-encoding", "chunked").body(body).unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_refusal("503 stall", &p, &b, 503, "unavailable", "body_read_timeout"); + drop(tx); + } +} + +#[cfg(feature = "stage1-probe")] +mod probe_path_tests { + use super::*; + + async fn probe_p(t: &Pt, path: &str) -> (http::response::Parts, Bytes) { + let r = t + .preq("POST", path) + .header("content-length", "2") + .body(Body::from("{}")) + .unwrap(); + t.send(r).await.unwrap() + } + + #[tokio::test] + async fn probe_works_under_the_path_form_and_410_body_carries_the_decision() { + let t = Pt::new("probe-path").await; + for (status, dec) in [ + (200, ""), + (410, "expired"), + (423, "denied"), + (503, "unavailable"), + ] { + let (p, b) = probe_p(&t, &format!("/__ap_probe/{status}/1")).await; + assert_eq!(p.status.as_u16(), status); + assert_eq!(decision(&p), dec); + if status != 200 { + assert_refusal("probe", &p, &b, status, dec, "probe"); + } + } + let (p, b) = probe_p(&t, "/__ap_probe/200/7").await; + assert_refusal("probe bad", &p, &b, 400, "denied", "probe_params"); + let r = Request::builder() + .method("POST") + .uri(format!("/ap/{}/__ap_probe/200/1", caller_key())) + .header("host", AUTH) + .header("content-length", "2") + .body(Body::from("{}")) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_refusal("probe unknown", &p, &b, 401, "rejected", "caller_rejected"); + let r = t + .preq("POST", "/__ap_probe/200/1") + .header("x-ap-caller-key", t.key.as_str()) + .header("content-length", "2") + .body(Body::from("{}")) + .unwrap(); + let (p, b) = t.send(r).await.unwrap(); + assert_refusal("probe both", &p, &b, 400, "denied", "caller_key_ambiguous"); + let text = t.audit_text(); + assert!(text.contains("\"event\":\"completed\"")); + assert!(!text.contains(&t.key) && !text.contains("/ap/"), "{text}"); + assert_eq!(t.hits(), 0); + } +} diff --git a/crates/ap-proxy/src/pipeline.rs b/crates/ap-proxy/src/pipeline.rs index 7ce4477..7af931f 100644 --- a/crates/ap-proxy/src/pipeline.rs +++ b/crates/ap-proxy/src/pipeline.rs @@ -15,10 +15,10 @@ use std::collections::HashMap; use std::io; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex, RwLock}; -use std::time::{Instant, SystemTime}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; use ap_broker::broker::Broker; use ap_broker::clock::SystemClock; @@ -27,9 +27,8 @@ use ap_broker::proof::{parse_public_key, NonceTable}; use ap_broker::registry::{sha256_hex, Access, Registry, RegistryCfg}; use ap_core::audit::{path_only, AuditRec}; use ap_core::canon; -use ap_core::config::{self, Config, ErrorShape, Grant, Identity, Route}; +use ap_core::config::{Config, ErrorShape, Grant, Identity, Route}; use ap_core::error::{render, Code}; -use ap_core::policy::Snapshot; use axum::body::Body; use axum::extract::Request; use axum::response::Response; @@ -40,41 +39,16 @@ use subtle::ConstantTimeEq; use crate::audit_sink::AuditSink; use crate::forward; +use crate::policy_store::{Loaded, PolicyStore}; #[cfg(test)] mod h2_tests; #[cfg(test)] mod tests; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct Stamp { - modified: SystemTime, - len: u64, -} - -fn stamp_of(path: &Path) -> Option { - let meta = std::fs::metadata(path).ok()?; - if !meta.is_file() { - return None; - } - Some(Stamp { - modified: meta.modified().ok()?, - len: meta.len(), - }) -} - -/// A policy file that loaded and validated, with the stamp it was read under. -#[derive(Clone)] -struct Loaded { - stamp: Stamp, - cfg: Arc, - snap: Arc, -} - /// Shared state for the agent listener and the session plane. pub struct App { - policy_path: PathBuf, - policy: RwLock>, + policy: PolicyStore, listen_authority: String, max_body: u64, pub(crate) token_dir: PathBuf, @@ -125,15 +99,9 @@ impl App { } } let authority_lease_secs = cfg.sessions.authority_lease_secs; - let snap = Arc::new(Snapshot::from_config(&cfg)); - let policy = stamp_of(&policy_path).map(|stamp| Loaded { - stamp, - snap, - cfg: Arc::new(cfg), - }); + let policy = PolicyStore::new(policy_path, cfg); Ok(Arc::new(App { - policy_path, - policy: RwLock::new(policy), + policy, listen_authority, max_body, token_dir, @@ -148,40 +116,9 @@ impl App { })) } - /// The policy in force now. The file's stamp (mtime and size) is checked on every call. A - /// change triggers a reload. A file that cannot be read or validated drops the snapshot and - /// returns `None`, so the caller answers 503. + /// The policy in force now, reloaded when the file changed. `None` means 503. fn policy(&self) -> Option { - let Some(stamp) = stamp_of(&self.policy_path) else { - self.drop_policy(); - return None; - }; - if let Ok(guard) = self.policy.read() { - if let Some(l) = guard.as_ref() { - if l.stamp == stamp { - return Some(l.clone()); - } - } - } - let loaded = std::fs::read_to_string(&self.policy_path) - .ok() - .and_then(|text| config::load(&text).ok()) - .map(|cfg| Loaded { - stamp, - snap: Arc::new(Snapshot::from_config(&cfg)), - cfg: Arc::new(cfg), - }); - match self.policy.write() { - Ok(mut slot) => *slot = loaded.clone(), - Err(_) => return None, - } - loaded - } - - fn drop_policy(&self) { - if let Ok(mut slot) = self.policy.write() { - *slot = None; - } + self.policy.current() } } diff --git a/crates/ap-proxy/src/policy_store.rs b/crates/ap-proxy/src/policy_store.rs new file mode 100644 index 0000000..002baf4 --- /dev/null +++ b/crates/ap-proxy/src/policy_store.rs @@ -0,0 +1,92 @@ +//! The policy file as the pipeline sees it: loaded, validated and reloaded on change. +//! +//! The file's stamp (mtime and size) is checked on every read. A change triggers a reload. A file +//! that cannot be read or validated drops the snapshot, and every request that needs it gets 503 +//! until a valid file appears. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; +use std::time::SystemTime; + +use ap_core::config::{self, Config}; +use ap_core::policy::Snapshot; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Stamp { + modified: SystemTime, + len: u64, +} + +fn stamp_of(path: &Path) -> Option { + let meta = std::fs::metadata(path).ok()?; + if !meta.is_file() { + return None; + } + Some(Stamp { + modified: meta.modified().ok()?, + len: meta.len(), + }) +} + +/// A policy file that loaded and validated, with the stamp it was read under. +#[derive(Clone)] +pub(crate) struct Loaded { + stamp: Stamp, + pub(crate) cfg: Arc, + pub(crate) snap: Arc, +} + +pub(crate) struct PolicyStore { + path: PathBuf, + slot: RwLock>, +} + +impl PolicyStore { + /// A store over `path`, seeded with `cfg`, which was read from that file at startup. + pub(crate) fn new(path: PathBuf, cfg: Config) -> PolicyStore { + let snap = Arc::new(Snapshot::from_config(&cfg)); + let loaded = stamp_of(&path).map(|stamp| Loaded { + stamp, + snap, + cfg: Arc::new(cfg), + }); + PolicyStore { + path, + slot: RwLock::new(loaded), + } + } + + /// The policy in force now. `None` means the caller answers 503. + pub(crate) fn current(&self) -> Option { + let Some(stamp) = stamp_of(&self.path) else { + self.drop_policy(); + return None; + }; + if let Ok(guard) = self.slot.read() { + if let Some(l) = guard.as_ref() { + if l.stamp == stamp { + return Some(l.clone()); + } + } + } + let loaded = std::fs::read_to_string(&self.path) + .ok() + .and_then(|text| config::load(&text).ok()) + .map(|cfg| Loaded { + stamp, + snap: Arc::new(Snapshot::from_config(&cfg)), + cfg: Arc::new(cfg), + }); + match self.slot.write() { + Ok(mut slot) => *slot = loaded.clone(), + Err(_) => return None, + } + loaded + } + + fn drop_policy(&self) { + if let Ok(mut slot) = self.slot.write() { + *slot = None; + } + } +} diff --git a/crates/ap-proxy/src/probe.rs b/crates/ap-proxy/src/probe.rs new file mode 100644 index 0000000..de88d07 --- /dev/null +++ b/crates/ap-proxy/src/probe.rs @@ -0,0 +1,132 @@ +//! Stage 1 hold-tolerance probe (design acceptance 10). Compiled only with the `stage1-probe` +//! feature and mounted only when `[probe] enabled`. +//! +//! `POST /__ap_probe//` answers with `status` after `secs` seconds and the matching +//! `X-AP-Decision`. It runs after the caller-key check, so it is never an unauthenticated slow +//! endpoint. A drop guard records whether the handler future was dropped before it answered, +//! which is how a client disconnect reaching the proxy is measured. + +use std::time::{Duration, Instant}; + +use ap_core::config::Passthrough; +use ap_core::error::Code; +use ap_core::outcome::DECISION_HEADER; +use axum::body::Body; +use futures_util::StreamExt; +use http::{header, HeaderValue, Method, Response, StatusCode}; + +use crate::passthrough::{refuse, PtApp, Trail}; + +/// Path prefix of the probe route. +pub(crate) const PREFIX: &str = "/__ap_probe/"; + +const STATUSES: &[u16] = &[200, 410, 423, 503]; +#[cfg(not(test))] +const SECS: &[u64] = &[10, 30, 60, 120, 300]; +#[cfg(test)] +const SECS: &[u64] = &[0, 1, 2, 10, 30, 60, 120, 300]; +const MAX_BODY: usize = 1024 * 1024; + +fn parse(path: &str) -> Option<(u16, u64)> { + let rest = path.strip_prefix(PREFIX)?; + let (s, n) = rest.split_once('/')?; + let status: u16 = s.parse().ok()?; + let secs: u64 = n.parse().ok()?; + (STATUSES.contains(&status) && SECS.contains(&secs)).then_some((status, secs)) +} + +struct Guard<'a> { + app: &'a PtApp, + status: u16, + secs: u64, + started: Instant, + done: bool, +} + +impl Drop for Guard<'_> { + fn drop(&mut self) { + let event = if self.done { + "completed" + } else { + "client_gone" + }; + let line = serde_json::json!({"probe": { + "event": event, + "status": self.status, + "secs": self.secs, + "elapsed_ms": u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + }}) + .to_string(); + self.app.audit.write_line(&line); + } +} + +pub(crate) async fn handle( + app: &PtApp, + trail: &Trail, + method: &Method, + path: &str, + body: Body, + pt: &Passthrough, +) -> Response { + let Some((status, secs)) = parse(path).filter(|_| method == Method::POST) else { + return refuse(app, trail, Code::ProbeParams); + }; + let mut guard = Guard { + app, + status, + secs, + started: Instant::now(), + done: false, + }; + // Read the body (a write is what will be held), bounded in size, per-chunk time and total time. + let mut stream = body.into_data_stream(); + let mut seen = 0usize; + // Total bound on the body read, so a trickling caller cannot hold the slot indefinitely. + let deadline = Instant::now() + Duration::from_secs(pt.request_deadline_secs); + loop { + let wait = Duration::from_secs(pt.body_read_secs) + .min(deadline.saturating_duration_since(Instant::now())); + match tokio::time::timeout(wait, stream.next()).await { + Err(_) => { + guard.done = true; + return refuse(app, trail, Code::BodyReadTimeout); + } + Ok(None) => break, + Ok(Some(Err(_))) => { + guard.done = true; + return refuse(app, trail, Code::BodyReadTimeout); + } + Ok(Some(Ok(c))) => { + seen += c.len(); + if seen > MAX_BODY { + guard.done = true; + return refuse(app, trail, Code::BodyTooLarge); + } + } + } + } + tokio::time::sleep(Duration::from_secs(secs)).await; + guard.done = true; + let decision = match status { + 410 => Some("expired"), + 423 => Some("denied"), + 503 => Some("unavailable"), + _ => None, + }; + let body = match decision { + Some(d) => format!("{{\"ap_decision\":\"{d}\",\"code\":\"probe\"}}"), + None => "{\"probe\":\"ok\"}".to_string(), + }; + let mut r = Response::new(Body::from(body)); + *r.status_mut() = StatusCode::from_u16(status).unwrap_or(StatusCode::OK); + r.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + if let Some(d) = decision { + r.headers_mut() + .insert(DECISION_HEADER, HeaderValue::from_static(d)); + } + r +} diff --git a/crates/ap-proxy/src/test_support.rs b/crates/ap-proxy/src/test_support.rs index 032504a..263c157 100644 --- a/crates/ap-proxy/src/test_support.rs +++ b/crates/ap-proxy/src/test_support.rs @@ -146,6 +146,36 @@ impl Upstream { } async fn echo(req: hyper::Request) -> Result>, Infallible> { + use http_body_util::BodyExt; + if req.uri().path() == "/xap" { + let resp = hyper::Response::builder() + .header("x-ap-decision", "denied") + .header("x-ap-other", "kept") + .header("x-plain", "yes") + .body(Full::new(Bytes::from_static(b"upstream-body"))) + .expect("xap response"); + return Ok(resp); + } + if req.uri().path().ends_with("/echo2") { + let (parts, body) = req.into_parts(); + let len = match body.collect().await { + Ok(b) => b.to_bytes().len(), + Err(_) => 0, + }; + let headers: Vec<(String, String)> = parts + .headers + .iter() + .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string())) + .collect(); + let out = serde_json::json!({ + "headers": headers, + "body_len": len, + "path": parts.uri.to_string(), + }); + return Ok(hyper::Response::new(Full::new(Bytes::from( + serde_json::to_vec(&out).unwrap_or_default(), + )))); + } if req.uri().path() == "/redirect" { let resp = hyper::Response::builder() .status(302) diff --git a/crates/ap-proxy/tests/matrix.rs b/crates/ap-proxy/tests/matrix.rs index db7d716..fec0b19 100644 --- a/crates/ap-proxy/tests/matrix.rs +++ b/crates/ap-proxy/tests/matrix.rs @@ -5,6 +5,8 @@ //! cargo build -p ap-proxy -p ap-egress --features ap-proxy/matrix-upstream,ap-egress/matrix-upstream //! cargo test -p ap-proxy --features matrix-upstream --test matrix //! +//! The passthrough (Muse gate) rows live in `tests/matrix_passthrough.rs`; this file is unchanged by them. +//! //! The test passes only when the driver exits 0, prints no FAIL row, and reports every registered //! row as PASS. If python3 or openssl is missing, the test prints a skip message and returns. The CI //! job asserts that both tools exist, so the skip cannot hide a failure there. diff --git a/crates/ap-proxy/tests/matrix_passthrough.rs b/crates/ap-proxy/tests/matrix_passthrough.rs new file mode 100644 index 0000000..079aee1 --- /dev/null +++ b/crates/ap-proxy/tests/matrix_passthrough.rs @@ -0,0 +1,65 @@ +//! Runs the passthrough matrix driver (`tests/matrix/passthrough.py`) against the built binary. +//! +//! Build with both test features, then run: +//! cargo build -p ap-proxy --features matrix-upstream,stage1-probe +//! cargo test -p ap-proxy --features matrix-upstream,stage1-probe --test matrix_passthrough +//! +//! Passes only when the driver exits 0, prints no FAIL row and reports every registered row as +//! PASS. The sidecar matrix (`tests/matrix.rs`) is separate and unchanged. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Rows registered in `tests/matrix/passthrough.py`. +const ROWS: usize = 16; + +/// 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. +fn bin_dir() -> PathBuf { + Path::new(env!("CARGO_BIN_EXE_auth-proxy")) + .parent() + .expect("binary directory") + .to_path_buf() +} + +fn tool_works(tool: &str, arg: &str) -> bool { + Command::new(tool) + .arg(arg) + .output() + .map(|o| o.status.success()) + .unwrap_or(false) +} + +#[test] +fn matrix_passthrough() { + if !tool_works("python3", "--version") || !tool_works("openssl", "version") { + eprintln!("SKIP matrix_passthrough: python3 or openssl is not on PATH"); + return; + } + let bins = bin_dir(); + assert!( + bins.join("auth-proxy").exists(), + "missing auth-proxy in {}; build it with --features matrix-upstream,stage1-probe", + bins.display() + ); + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let out = Command::new("python3") + .current_dir(&root) + .arg("tests/matrix/passthrough.py") + .arg("--bin") + .arg(&bins) + .output() + .expect("run passthrough matrix driver"); + let stdout = String::from_utf8_lossy(&out.stdout); + print!("{stdout}"); + eprint!("{}", String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success(), "driver exited {}", out.status); + assert!( + !stdout.lines().any(|l| l.starts_with("FAIL")), + "a row failed" + ); + assert!( + stdout.contains(&format!("summary: {ROWS} PASS of {ROWS} rows")), + "not every row passed:\n{stdout}" + ); +} diff --git a/deploy/muse/pilot-policy.example.toml b/deploy/muse/pilot-policy.example.toml new file mode 100644 index 0000000..cd2ff41 --- /dev/null +++ b/deploy/muse/pilot-policy.example.toml @@ -0,0 +1,35 @@ +# Muse pilot, stage 1 (measurement plus allow/deny passthrough). +# Placeholders only: replace every <...> value. Never commit a real host name or key hash. +# See docs/runbooks/muse-stage1.md. +version = 1 + +[listen] +# Loopback only. The TLS front (for example `tailscale serve`) forwards to this address. +proxy = "127.0.0.1:8443" + +[passthrough] +# The Host header the front passes to the loopback listener. +public_authority = "" + +[probe] +# Only for the stage 1 measurement build (cargo build --features stage1-probe). +enabled = true + +[[identity]] +name = "muse-pilot" +# sha256 of the issued apk_ key, 64 lowercase hex characters. +caller_key_sha256 = "<64 lowercase hex, sha256 of the issued apk_ key>" + +[[route]] +name = "discord" +host = "discord.com" +mode = "passthrough" + +# Reads pass. Every other method or path (including POST /api/v10/channels/{id}/messages) +# is refused 423 no_grant. +[[grant]] +identity = "muse-pilot" +route = "discord" +methods = ["GET"] +paths = ["/api/v10/channels/", "/api/v10/guilds/", "/api/v10/users/@me"] +decision = "allow" diff --git a/docs/design/muse-gated-passthrough.md b/docs/design/muse-gated-passthrough.md index 8123ce8..d1cc1a6 100644 --- a/docs/design/muse-gated-passthrough.md +++ b/docs/design/muse-gated-passthrough.md @@ -92,7 +92,9 @@ reuses Phase 1 steps 1 to 3 and 6 and skips steps 4, 5 and 7 [I phase1.md sectio 1. Refuse `CONNECT` (405) and `Upgrade` (501), as in Phase 1 [I pipeline.rs `handle`], each carrying `X-AP-Decision: denied`. 2. Canonicalize: origin form, one `Host`, no ambiguous path (section 3.8). -3. Read the caller key from the header (section 3.2), find the identity by constant-time hash compare. +3. Read the caller key from exactly one source: the header, or a `/ap//` path prefix that is stripped + before routing and forwarding (section 3.2). Both present is 400 `caller_key_ambiguous`. Find the identity by + constant-time hash compare. 4. Evaluate policy for identity, route, method and route-relative path. Result is `allow`, `hold` or deny. 5. `allow`: forward now. `hold`: section 3.4. Deny: terminal error (section 3.5). 6. Audit: one record per allowed request, hold transitions for a held one (section 3.9). @@ -138,9 +140,21 @@ Tailnet identity headers that `tailscale serve` injects are ignored: no decision `Transfer-Encoding`, with more than one or a comma-joined `Content-Length`, or with a `Transfer-Encoding` other than a single `chunked` is refused 400 (`framing_refused`) and produces no upstream request. hyper's HTTP/1 parser may refuse some of these before the handler runs, in which case the answer is hyper's, not - ours [A, not checked in this work]. The gate does not rely on that. Stage 1 sends raw HTTP/1 requests + ours. The gate does not rely on that. Stage 1 sends raw HTTP/1 requests directly and through the front and records which layer refused and whether the answer carries `X-AP-Decision`. + **Known gap (stage 1, decided by the owner):** hyper 1.12 changes three cases before the handler can see + them [I hyper-1.12.0 `proto/h1/role.rs`]: it deletes `Content-Length` when `Transfer-Encoding: chunked` + is present, it collapses identical duplicate `Content-Length` headers into one, and its parser accepts a + bare LF line ending. The handler therefore cannot refuse these three, and a direct request carrying one is + forwarded. Stage 1 accepts this because the listener is loopback-only, so a direct request is possible + only from the proxy host itself, and the real path goes through the owner's `tailscale serve`, which was + measured to normalise or terminate all three [M, source: `docs/evidence/muse-stage1-front-measurements.md`]. + The fix is a connection-level raw-head scanner (about 100 lines, with a Content-Length and chunked + body-length tracker so it finds each head on a keep-alive connection). It is the stage 2 candidate and must be decided + before any listener is exposed beyond the front. It was not built now because a second HTTP parser in + front of hyper adds a parser-differential surface, and `keep_alive(false)` would change behaviour that + the front's pooled connections rely on. - Body framing: a held body gets a `Content-Length` computed from the buffered bytes. An allowed request forwards a declared `Content-Length` as declared, and an allowed chunked body is forwarded chunked, with no buffering and no computed length. The body bytes are unchanged; only framing, which is hop-by-hop, @@ -187,6 +201,22 @@ What is worse, and the control for each: The caller key authenticates the connector to the gate. It is not a Discord credential and not an approval credential. +**Two sources, exactly one per request.** The key is accepted from the header, or from a path prefix +`/ap///` (the Phase 1 form, parsed by the same `parse_ap_path` with the same key +format). A connector whose helper cannot add a custom header uses the path form. A request carrying both is +refused 400 `caller_key_ambiguous` before any key is compared, never resolved by picking one. The prefix is +stripped before routing and forwarding, so `/ap//discord/x` is routed and forwarded exactly as +`/discord/x`; the probe works under it (`/ap//__ap_probe//`). + +**`Authorization` is not a source.** A registered connector credential is injected as `Authorization`. On a +passthrough route that header is the upstream credential and is forwarded unchanged, so using it as the caller +key would send the key to Discord. + +The path form brings back the cost named above: the key is in the URL. The audit line, evidence record, +journal, error bodies and panic message never contain the `/ap/` prefix or the key (the audit path field +is the stripped, redacted route-relative path), and the matrix scans every output for it. Anything in front of +the gate that logs URLs would still see it, and the key is unsafe wherever such a log is kept. + ### 3.3 Policy: a third verdict, and segment patterns Phase 1 policy answers allow or deny. A grant is `{identity, credential, route, methods, paths}` with @@ -332,7 +362,9 @@ reach Discord, by name at least. ### 3.5 Outcome contract Every refusal the gate generates carries `X-AP-Decision` and a small JSON body -`{"ap_decision": "...", "code": "..."}`. This table is the single list of gate refusals. Discord's response +`{"ap_decision": "...", "code": "..."}`. The body is the reliable copy: Muse's helper discards all response +headers and shows the agent only `HTTP : ` [M-reported], so the decision must be readable from the +body alone. The body has this fixed two-field shape for every row below and echoes no request data. This table is the single list of gate refusals. Discord's response is returned verbatim, including any `x-ap-*` headers it carries; the gate's own refusals are identified by a locally generated status plus `X-AP-Decision`, and Discord is not expected to send that header [A]. @@ -342,6 +374,7 @@ a locally generated status plus `X-AP-Decision`, and Discord is not expected to | No grant matches | 423 | `denied` | `no_grant` | nothing | | Unknown route name | 423 | `denied` | `route_unknown` | nothing | | Caller key missing, duplicate, malformed or unknown | 401 | `rejected` | `caller_rejected` | nothing | +| Caller key in both the header and the path prefix | 400 | `denied` | `caller_key_ambiguous` | nothing | | Canonicalization refusal (Phase 1 codes, for example `path_ambiguous`, `Host` mismatch) | 400 | `denied` | Phase 1 code | nothing | | Framing conflict (section 3.1) | 400 | `denied` | `framing_refused` | nothing | | More than one `Authorization` header | 400 | `denied` | `authorization_duplicate` | nothing | @@ -357,7 +390,7 @@ a locally generated status plus `X-AP-Decision`, and Discord is not expected to | Failure after the first upstream request byte (reset, stalled or undeclared oversized allowed body, upstream error) | none: the client connection is closed | none | n/a | possibly the request | If hyper refuses a request before the handler runs (section 3.1 framing policy), the answer is hyper's and -may lack the header; stage 1 records this. +may lack the header; stage 1 records this. The three cases in the section 3.1 known gap never reach the handler. Why these statuses: Discord's documented API statuses are 2xx, 304, 400, 401, 403, 404, 405, 429 and some 5xx [A, not checked in this work]. 423 and 410 are not expected from Discord. 400, 401, 405, 413 and 503 @@ -699,8 +732,8 @@ Goal: validate Muse's hook format end to end with no approval machinery. A write `hold` is simply denied. Stage 1 contains items 1 to 3 and 5 to 6 of the "needed" list, and the `decision = "allow"` half of item 4. -Evidence to collect from a real Muse connector run (names only, never values): which header carries the -key, whether `Authorization` arrives (present or absent), the `Host` +Evidence to collect from a real Muse connector run (names only, never values): which header or path prefix +carries the key, whether `Authorization` arrives (present or absent), the `Host` header and path prefix, HTTP version at the TLS front, whether bodies are chunked or compressed, whether Muse sends other headers we would forward, whether two identical connector calls carry the same forwarded header names, the `Content-Type` of message create, and whether the front sends `100 Continue` @@ -715,17 +748,19 @@ Acceptance: another `X-AP-*` header keeps both. 2. A `POST /channels/{id}/messages` is 423 `no_grant` with `X-AP-Decision: denied`, and the mock upstream records no request. -3. Missing, duplicate and malformed caller-key headers are `caller_rejected`, status 401 with - `X-AP-Decision: rejected` (not the 423 of a human denial), nothing upstream. An unknown route name is +3. Missing, duplicate and malformed caller-key headers (and unknown or malformed path-prefix keys) are `caller_rejected`, status 401 with + `X-AP-Decision: rejected` (not the 423 of a human denial), nothing upstream. The key in both the header and + the path prefix is 400 `caller_key_ambiguous`. Every refusal body is `{"ap_decision","code"}` matching the header. An unknown route name is 423 `denied` (`route_unknown`) and nothing is sent. Duplicate `Authorization` is 400 `authorization_duplicate` with `X-AP-Decision: denied`; `CONNECT` is 405 and `Upgrade` 501, each with the header. -4. **Caller-key header stripped upstream:** the mock upstream's recorded headers contain neither the - caller-key header nor any `x-ap-*` header, for allowed requests. +4. **Caller key stripped upstream:** the mock upstream's recorded headers contain neither the + caller-key header nor any `x-ap-*` header, and its recorded path contains no `/ap/` prefix, for allowed requests + in both key forms. 5. **`Authorization` forwarded unchanged:** the mock upstream receives the identical `Authorization` value that the test sent. 6. **`Authorization` never in any log:** run the proxy with a sentinel token, exercise allow, deny, 413, malformed, upstream-failure and panic-injection paths, and assert the sentinel and the caller key are - absent from stdout, stderr and the audit stream. The test also sends a path-token sentinel + absent from stdout, stderr and the audit stream, for both key forms (the `/ap/` prefix included). The test also sends a path-token sentinel (`/webhooks//` and `/interactions///callback`) and asserts that it is absent from the audit stream and the logs. (Phase 1 has the same discipline for surrogates and credentials [I audit.rs].) @@ -750,7 +785,11 @@ Acceptance: 12. **Framing:** raw HTTP/1 requests with both `Content-Length` and `Transfer-Encoding`, duplicate and comma-joined `Content-Length`, a `Transfer-Encoding` other than `chunked`, and conflicting `Connection` nominations, sent directly and through the real front: the mock upstream records no request. Record - which layer refused and whether the answer carries `X-AP-Decision`. + which layer refused and whether the answer carries `X-AP-Decision`. Stage 1 asserts this for the + refused cases (differing or comma-joined `Content-Length`, bad `Transfer-Encoding`, `Connection` + nominations, obs-fold, wrong or duplicate `Host`). Identical duplicate `Content-Length`, a request with + `Content-Length` and `Transfer-Encoding: chunked`, and bare LF are the section 3.1 known gap: they are + documented and measured, not asserted as refused. 13. **Allowed-body boundary:** an allowed body that stalls after a prefix, and an undeclared body that exceeds the cap after the mock upstream consumed a prefix, close the client connection with one audit record, `code = body_failed_after_send`. A stall before the first upstream byte is 503 `unavailable`, and an undeclared over-cap body before it is 413. An @@ -857,6 +896,25 @@ Adds the hold table, the approval listener, the notification hook and the `hold` ## 8. Open questions for the owner +### Muse-reported facts [M-reported] + +Reported by the Muse side after trying the gate. They are not measured by us and describe the current Discord +helper, not the new connector, until the first measurement round says otherwise. + +- The base URL is hard-coded to the Discord host and any other host is refused. Muse will register a separate + connector, `oab-auth-proxy`, for the gate host [owner decision]; the first round uses a dummy credential. +- The helper cannot add a custom request header. The registered credential is injected as `Authorization`. +- JSON requests have a 30 s socket timeout (60 s for multipart). No retries, no trace, request or idempotency headers. +- All response headers are discarded; the agent sees only `HTTP : `. Consequence: the decision + lives in the JSON body (section 3.5). +- Redirects are not followed. `Host` includes a non-default port. +- The agent can still reach Discord directly. + +Consequences. (a) The 30 s JSON timeout is a hard constraint on the stage 2 hold window: `hold_secs` must stay +below it unless Muse raises it for this connector, so the 120 s default is not usable as things stand. (b) The +gate constrains the agent only if the new connector is the agent's only route to Discord. While the agent can +call Discord directly, the gate is advisory (section 4.3). + Open questions 1 to 4 are stage 1 blockers. 1. **Muse's tolerance for a held connection (open point d).** How long will the Muse custom connector wait @@ -865,16 +923,20 @@ Open questions 1 to 4 are stage 1 blockers. 120, range 5 to 600) and stage 1 item 10 measures it. Until measured, treat 120 s as a guess. The TLS front's own idle timeout also bounds the window, and whether `tailscale serve` cuts a long idle connection is unmeasured [A] and measured in stage 1. -2. **Caller-key header name.** Can the connector set an arbitrary header name, and does it constrain the - name or value format? Default `X-AP-Caller-Key` is a guess [A]. +2. **Caller-key header name.** Answered [M-reported]: the current helper cannot add a custom request header, + and the registered credential is injected as `Authorization`, which cannot be the caller key. The gate + therefore also accepts the key in the path prefix (section 3.2). Still open: whether a future connector can + set `X-AP-Caller-Key`. 3. **How does Muse reach the gate, and who terminates TLS?** Decided: `tailscale serve` on the owner's own node, proxy loopback-only (section 4.2). Still to confirm in stage 1: can Muse's egress reach that address, given the ACL restriction to Muse's node? -4. **Base URL shape.** The PoC uses path-prefix routing, `/discord/api/v10/...`. Does the connector accept - a base URL with a path prefix, or must the gate sit at the root and serve one route? +4. **Base URL shape.** The PoC uses path-prefix routing, `/discord/api/v10/...`. Muse will register a separate + connector, `oab-auth-proxy`, with its own base URL for this host [owner decision]. Whether that base URL may + carry a path prefix such as `/ap/` is to be confirmed by the first measurement round, which uses a + dummy credential only. 5. **Status codes for the terminal errors.** The proposed 423, 410 and 503 are untested against Muse - [A]. Does Muse treat unusual statuses or non-Discord bodies as a connector failure, retry on them, or - show them to the agent? + [A]. The helper shows the agent `HTTP : ` and does not retry [M-reported], so the body is what the + agent reads (section 3.5). Still open: how the agent reacts to those statuses. 6. **Retry behaviour.** After an `expired` or `denied`, does Muse's agent retry automatically? If so each retry is another phone prompt; dedupe, the per-identity cap and the default 60 s cooldown bound this. 7. **Approver channel.** Answered in the review comments: Basic auth plus a per-page CSRF token for the PoC, diff --git a/docs/evidence/muse-stage1-front-measurements.md b/docs/evidence/muse-stage1-front-measurements.md new file mode 100644 index 0000000..4287764 --- /dev/null +++ b/docs/evidence/muse-stage1-front-measurements.md @@ -0,0 +1,43 @@ +# Muse stage 1: front and framing measurements (redacted) + +Redacted excerpt of the stage 1 owner measurements. It holds no hostnames, addresses, logins, URLs or keys. +`` is the TLS front (a `tailscale serve` entry, tailnet only) and `` is the proxy's +loopback listener on the same host. All requests used a dummy `Authorization` value; the real Discord +token was never used. Tags follow the design doc: [M] measured. + +## Through the front + +- [M] No caller key: 401, `X-AP-Decision: rejected`. Wrong caller key: 401. +- [M] Valid key, `POST /discord/api/v10/channels/1/messages`: 423 `no_grant`, `X-AP-Decision: denied`. +- [M] Valid key, `GET /discord/api/v10/users/@me` with the dummy Authorization: 401 carrying Discord's own + headers and a 43-byte body. A direct request to Discord with the same dummy value also returned 401. The + bodies were not byte-diffed. +- [M] Hold probe `POST /__ap_probe/200/30` and `/200/120`: 200 after 30.05 s and 120.05 s. The front did not + cut the held connection. The evidence log recorded `elapsed_ms` 30000 and 120001. +- [M] The front passes a `Host` that includes its port. A request whose `Host` lacks the port is refused + 400 `host_rejected`, so a client that omits the port would be refused. +- [M] The front adds `tailscale-*` and `x-forwarded-*` headers. `cf-*`, `via`, `forwarded` and `x-real-ip` + were absent. +- [M] Framing through the front: duplicate `Content-Length: 0`, an obsolete folded header and bare-LF line + endings were accepted and forwarded (Discord answered 401). A POST with both `Content-Length` and + `Transfer-Encoding: chunked` reached the proxy as chunked and got 423 `no_grant`. The front normalises or + terminates these, so they cannot be tested end to end through it. + +## Directly to `` (raw HTTP/1) + +| Request | Result | +|---|---| +| different `Content-Length` values (0 and 5) | 400, empty body (hyper) | +| obsolete folded header | 400 (hyper) | +| `Host` not the public authority, or duplicate `Host` | 400 `host_rejected` | +| duplicate identical `Content-Length: 0` | accepted and forwarded | +| bare-LF line endings | accepted and forwarded | +| GET with `Content-Length: 1` and `Transfer-Encoding: chunked` | accepted and forwarded | + +The last three fall to the HTTP parser's defaults, not to a stage 1 rule. This is the documented framing gap. + +## No-leak check + +Counts only, patterns fed through stdin: 0 audit lines (44 inspected) contain the caller key, the dummy +Authorization value, `apk_`, `authorization` or `x-ap-caller-key`. The service journal had 0 matches. +Evidence entries carry presence flags and a digest of header names, never values. diff --git a/docs/runbooks/muse-stage1.md b/docs/runbooks/muse-stage1.md new file mode 100644 index 0000000..4cf490a --- /dev/null +++ b/docs/runbooks/muse-stage1.md @@ -0,0 +1,140 @@ +# Muse gated passthrough, stage 1 runbook + +Design: `docs/design/muse-gated-passthrough.md` (sections 3, 6, 7). Stage 1 is measurement plus +allow/deny passthrough for one consumer (Muse) and one upstream (Discord), on a single instance. No +approval machinery exists yet: a write that would later be held is denied with 423 `no_grant`. + +**The gate constrains the agent, not the Muse platform.** Muse's egress holds the real Discord token, +so Muse or anyone who compromises it can call Discord directly and skip the gate. + +All host names below are placeholders. Do not commit real tailnet names, addresses or logins. + +## 1. Build + +Build on a build host, not a laptop. The measurement build includes the probe: + +``` +cargo build --release -p ap-proxy --features stage1-probe +``` + +A default build (no feature) has no probe code and no `__ap_probe` string. A config with +`[probe] enabled = true` makes that binary exit 2. Stage 2 builds without the feature. + +## 2. Issue the caller key + +``` +key="apk_$(openssl rand -hex 32)" +printf '%s' "$key" | shasum -a 256 # put the hex digest in caller_key_sha256 +``` + +Give `$key` to the Muse connector in one of two ways, never both (both is 400 `caller_key_ambiguous`): + +- the `X-AP-Caller-Key` header (name configurable with `passthrough.caller_key_header`), or +- a path prefix on the base URL, `https:///ap//discord/...`, for a connector that cannot add a + header. The prefix is stripped before routing and forwarding. + +Do not use the registered credential (`Authorization`) as the key: on a passthrough route it is the upstream +credential and is forwarded unchanged. The path form puts the key in the URL, so keep any URL-logging layer +in front of the gate out of the path, or treat its logs as secret. The key never goes into the config, a log or a +commit. Revoke it by deleting the identity and its grants from the policy file (hot reload). Deleting only the identity leaves grants naming an unknown identity, the file stops validating, and every request gets 503 until it is fixed. + +## 3. Policy + +Start from `deploy/muse/pilot-policy.example.toml`. Set `public_authority` to the `Host` the front +passes to the loopback listener (a request whose `Host` differs is refused 400 `host_rejected` and audited without an identity). The proxy refuses a +non-loopback `listen.proxy`; the TLS front (for example `tailscale serve --bg --https=443 http://127.0.0.1:8443`) +exposes it to the tailnet only. Do not use Funnel. + +Run: + +``` +auth-proxy --config /etc/auth-proxy/policy.toml +``` + +No expiry store, session socket, admin socket or secret root is needed or read for a passthrough-only config. + +Muse base URL: `https:///discord` with the header, or `https:///ap//discord` with the +path form (the Discord path after `/discord` goes upstream unchanged). +Whether the connector accepts a path prefix is open question 4. + +## 4. Gate behaviour to expect + +| Request | Answer | +|---|---| +| `GET` on a granted prefix | Discord's own response, unchanged | +| any other method or path (including `POST /api/v10/channels/{id}/messages`) | 423, `X-AP-Decision: denied`, `no_grant` | +| unknown route name | 423 `route_unknown` | +| missing, duplicate or malformed caller key | 401, `X-AP-Decision: rejected` | +| caller key in both the header and the path prefix | 400 `caller_key_ambiguous` | +| ambiguous path, bad `Host`, framing conflict, duplicate `Authorization` | 400 | + +Every refusal also carries `{"ap_decision":"","code":""}` as its body, because Muse's helper drops +response headers and shows the agent only `HTTP : `. + +## 5. Evidence collection + +With a valid caller key, each request writes one `{"evidence":{...}}` line next to the audit line. Fields +(fixed; no header value, no length, no key, no body): `identity`, `route`, `method`, redacted `path`, +`status`, `http_version`, `auth_present`, +`chunked`, `compressed`, `content_type_class`, `expect_continue`, `front_headers_present` +(`forwarded`, `x_forwarded`, `x_real_ip`, `via`, `tailscale`, `cf`), and `fwd_names_digest` (sha256 over +sorted header names only; equal digests for two identical connector calls mean the same header names). + +Manual checklist, names only, redacted, written into the design doc afterwards: + +- [ ] which header carries the key (confirm the configured name arrives) +- [ ] `auth_present` for message-read calls +- [ ] path prefix as seen at the loopback listener (a wrong `Host` shows only as a `host_rejected` audit line) +- [ ] HTTP version at the front +- [ ] chunked and compressed bodies +- [ ] other non-secret header names the connector sends (names only) +- [ ] two identical connector calls: same `fwd_names_digest` +- [ ] `Content-Type` class of message create (denied in stage 1, but still logged) +- [ ] whether the front sends `100 Continue` itself + +## 6. Hold-tolerance probe (acceptance 10) + +Enable `[probe] enabled = true` on the `stage1-probe` build. From the Muse connector, through the real +front, send probe calls directly to the proxy (they are not Discord calls and do not use a route prefix): +`POST https:///__ap_probe//` (or `/ap//__ap_probe//`) with a small body and the caller key. `status` +is one of 200, 410, 423, 503 and `secs` one of 10, 30, 60, 120, 300. 410, 423 and 503 return the matching +`X-AP-Decision`; 200 returns none. + +Record for each run: + +- the largest `secs` that completes through the front +- whether the front interrupts a long idle connection +- whether a client disconnect during the wait reaches the proxy, and how fast: the audit stream gets a + `{"probe":{"event":"client_gone",...}}` line when it does, `completed` when the answer was sent + (measure both direct to the loopback listener and through the front) +- Muse's reaction to each status, to its own timeout, to a dropped connection, and its retry behaviour + +Muse's current helper has a 30 s socket timeout for JSON requests [M-reported], so `secs` of 60 and above +cannot complete through it unless Muse raises the timeout for this connector. Treat 30 s as the ceiling for the +stage 2 hold window until that is measured. + +**Stop rule:** if the connection is cut well below a usable `hold_secs`, or disconnects never reach the +proxy and Muse retries without bound, stop and rethink the design instead of building stage 2. + +## 7. Framing and ACL checks (acceptance 11, 12) + +- ACL isolation: from Muse's node only the public port is reachable; every other port (SSH included) + fails. This needs the real ACL, so it is checked by hand. +- Framing: send raw HTTP/1 requests with both `Content-Length` and `Transfer-Encoding`, differing or + comma-joined `Content-Length`, a `Transfer-Encoding` other than `chunked`, and a `Connection` header + naming `Content-Length`, directly and through the front. The upstream must see nothing. Record which + layer refused (hyper or the gate) and whether the answer carries `X-AP-Decision`. The automated matrix + (`tests/matrix/passthrough.py`, row PT-12) records the direct path. It also shows that hyper collapses a + duplicate `Content-Length` with identical values before the gate sees it. The same row measures a GET + with `Content-Length` and chunked, and bare-LF line endings. All three are the design 3.1 known gap: + forwarded on a direct request, not asserted as refused, deferred to stage 2 (raw-head scanner). The + listener is loopback-only, so direct requests come only from the proxy host. + +## 8. Automated checks + +``` +cargo build -p ap-proxy -p ap-egress --features ap-proxy/matrix-upstream,ap-proxy/stage1-probe,ap-egress/matrix-upstream +cargo test -p ap-proxy --features matrix-upstream,stage1-probe --test matrix_passthrough +python3 tests/matrix/passthrough.py --bin target/debug # needs an OpenSSL 3 `openssl` on PATH +python3 tests/matrix/matrix.py --bin target/debug # sidecar matrix, still 41 rows +``` diff --git a/tests/matrix/harness.py b/tests/matrix/harness.py index 45528a4..ec73ff2 100644 --- a/tests/matrix/harness.py +++ b/tests/matrix/harness.py @@ -186,15 +186,29 @@ def log_message(self, *a): pass def _record(self): - n = int(self.headers.get("content-length") or 0) - if n: - self.rfile.read(n) + te = (self.headers.get("transfer-encoding") or "").lower() + body_len = 0 + if "chunked" in te: + while True: + size = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16) + if size == 0: + while self.rfile.readline().strip(): + pass + break + body_len += len(self.rfile.read(size)) + self.rfile.readline() + else: + n = int(self.headers.get("content-length") or 0) + if n: + body_len = len(self.rfile.read(n)) self.server.rec.add({ "listener": self.server.name, "sni": getattr(self.connection, "ap_sni", None), "method": self.command, "path": self.path, "headers": [[k.lower(), v] for k, v in self.headers.items()], + "transfer_encoding": te, + "body_len": body_len, }) def _send(self, code, body=b"", ctype="application/json", extra=()): @@ -221,6 +235,11 @@ def _any(self): time.sleep(0.05) self.wfile.write(b"0\r\n\r\n") return + if path == "/v1/xap": + return self._send(200, b"upstream-body", extra=[("x-ap-decision", "denied"), ("x-ap-other", "kept")]) + if path == "/v1/hop": + return self._send(200, b"hop-body", extra=[("connection", "X-Hop"), ("x-hop", "value"), + ("proxy-authenticate", "Basic realm=up"), ("x-kept", "ok")]) if path == "/v1/redirect": import urllib.parse to = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query).get("to", [""])[0] @@ -431,6 +450,23 @@ def start_proxy(self, cfg_path, port, keep_tokens=False): if not wait_port(port, self.proc) or not os.path.exists(self.session_sock): raise RuntimeError(f"auth-proxy did not start on {port}; see proxy-{port}.log") + def start_passthrough(self, cfg_path, port, extra_env=None): + """Start the proxy on a passthrough-only config. No expiry store, no session or admin + socket, no secret root: the process must come up without any of them.""" + self.stop_proxy() + self.port = port + self.cur_cfg = cfg_path + out = open(self.audit_file, "ab") + err = open(os.path.join(self.work, f"proxy-{port}.log"), "ab") + env = self._proxy_env() + env.update(extra_env or {}) + self.proc = subprocess.Popen([os.path.join(self.bindir, "auth-proxy"), "--config", cfg_path], + stdout=out, stderr=err, env=env) + out.close() + err.close() + if not wait_port(port, self.proc): + raise RuntimeError(f"auth-proxy did not start on {port}; see proxy-{port}.log") + def stop_proxy(self): if self.proc is not None: self.proc.terminate() diff --git a/tests/matrix/passthrough.py b/tests/matrix/passthrough.py new file mode 100644 index 0000000..cc55f91 --- /dev/null +++ b/tests/matrix/passthrough.py @@ -0,0 +1,679 @@ +#!/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. + + passthrough.py --bin DIR [--work DIR] [--json OUT] + +DIR holds an `auth-proxy` built with `--features matrix-upstream,stage1-probe`. Each row asserts the +client-visible outcome AND what the mock upstream received. The upstream is the harness mock, so +nothing real is involved; every sentinel is random per run. + +Not automatable here (see docs/runbooks/muse-stage1.md): acceptance 11 (ACL isolation), and the +real-connector and real-front parts of 10 and 12. +""" +import argparse +import json +import os +import secrets +import socket +import subprocess +import sys +import tempfile +import threading +import time +import traceback + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from harness import Env, sha256_hex, wait_port # noqa: E402 + +PORT_A = 18200 # main instance +PORT_B = 18201 # small-limits instance +PORT_C = 18202 # refused-at-startup checks +AUTHORITY = "gate.example.test" +KEY_HEADER = "x-ap-caller-key" + +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"] + + +def case(cid, row, name, instance="main"): + def deco(f): + CASES.append((cid, row, name, instance, f)) + return f + return deco + + +# ------------------------------------------------------------------ config and client helpers +def pt_text(key, port, limits="", probe=True, listen_host="127.0.0.1"): + return f"""version = 1 + +[listen] +proxy = "{listen_host}:{port}" + +[limits] +max_body_bytes = 4096 + +[passthrough] +public_authority = "{AUTHORITY}" +{limits} + +[probe] +enabled = {"true" if probe else "false"} + +[[identity]] +name = "muse-pilot" +caller_key_sha256 = "{sha256_hex(key)}" + +[[route]] +name = "discord" +host = "api.up.test" +port = 18443 +mode = "passthrough" + +[[grant]] +identity = "muse-pilot" +route = "discord" +methods = ["GET"] +paths = ["/v1/"] + +[[grant]] +identity = "muse-pilot" +route = "discord" +methods = ["POST"] +paths = ["/v1/upload/"] +""" + + +def exchange(port, raw, timeout=4.0, stall=None): + """Send raw bytes, read one response. Returns dict(status, headers, body, closed, head). + + `stall` is a (bytes, seconds) pair: the bytes are sent after `raw`, then the client waits. + """ + s = socket.create_connection(("127.0.0.1", port), 5) + s.settimeout(timeout) + try: + s.sendall(raw) + if stall: + time.sleep(stall[0]) + except OSError: + pass + buf = b"" + closed = False + try: + while b"\r\n\r\n" not in buf: + b = s.recv(65536) + if not b: + closed = True + break + buf += b + except (socket.timeout, OSError): + pass + head, _, rest = buf.partition(b"\r\n\r\n") + lines = head.decode(errors="replace").split("\r\n") + first = lines[0].split(" ") if lines and lines[0] else [] + status = int(first[1]) if len(first) > 1 and first[1].isdigit() else 0 + headers = {} + for ln in lines[1:]: + if ":" in ln: + k, v = ln.split(":", 1) + headers[k.strip().lower()] = v.strip() + body = rest + try: + if "chunked" in headers.get("transfer-encoding", ""): + while not body.endswith(b"0\r\n\r\n"): + b = s.recv(65536) + if not b: + break + body += b + elif "content-length" in headers: + while len(body) < int(headers["content-length"]): + b = s.recv(65536) + if not b: + break + body += b + except (socket.timeout, OSError): + pass + s.close() + return dict(status=status, headers=headers, body=body, closed=closed, head=head.decode(errors="replace")) + + +def build(method, path, headers, body=b"", host=AUTHORITY, add_host=True): + lines = [f"{method} {path} HTTP/1.1"] + if add_host: + lines.append(f"Host: {host}") + lines += [f"{k}: {v}" for k, v in headers] + return ("\r\n".join(lines) + "\r\n\r\n").encode() + body + + +class Ctx: + """Per-run state shared by the rows.""" + + def __init__(self, env): + self.e = env + self.key = "apk_" + secrets.token_hex(32) + self.auth = "Bot SENTINEL-" + secrets.token_hex(12) + self.path_token = "PATHTOKEN" + secrets.token_hex(10) + self.port = PORT_A + + def good(self, extra=(), key=True, auth=True): + h = [] + if key: + h.append((KEY_HEADER, self.key)) + if auth: + h.append(("Authorization", self.auth)) + return h + list(extra) + + def get(self, path, extra=(), port=None, **kw): + return exchange(port or self.port, build("GET", path, self.good(extra, **kw))) + + def ulog(self): + return self.e.ulog() + + +def code_of(r): + try: + return json.loads(r["body"]).get("code") + except ValueError: + return None + + +def body_decision(r): + """The decision carried in the JSON body (Muse's helper drops response headers).""" + try: + return json.loads(r["body"]).get("ap_decision") + except ValueError: + return None + + +def refused(c, r, status, decision, code, n_up=0): + n = len(c.ulog()) + ok = (r["status"] == status and r["headers"].get("x-ap-decision") == decision + and code_of(r) == code and body_decision(r) == decision and n == n_up) + return ok, (f"status={r['status']} decision={r['headers'].get('x-ap-decision')} " + f"body_decision={body_decision(r)} code={code_of(r)} upstream={n}") + + +# ------------------------------------------------------------------ rows (instance "main") +@case("PT-01", "acc 1", "GET on an allowed prefix passes; upstream x-ap-* response headers are kept") +def pt01(c): + r = c.get("/discord/v1/xap") + up = c.ulog() + ok = (r["status"] == 200 and r["headers"].get("x-ap-decision") == "denied" + and r["headers"].get("x-ap-other") == "kept" and r["body"].startswith(b"upstream-body") + and len(up) == 1 and up[0]["method"] == "GET" and up[0]["path"] == "/v1/xap") + return ok, f"status={r['status']} headers={sorted(k for k in r['headers'] if k.startswith('x-ap'))} upstream={len(up)}" + + +@case("PT-15", "design 6", "upstream Connection nominations are dropped from the response (X-Hop and Connection do not reach the caller)") +def pt15(c): + r = c.get("/discord/v1/hop") + h = r["headers"] + ok = (r["status"] == 200 and r["body"] == b"hop-body" and "x-hop" not in h + and "connection" not in h and h.get("x-kept") == "ok") + return ok, f"status={r['status']} x-hop={'x-hop' in h} connection={h.get('connection')} x-kept={h.get('x-kept')}" + + +@case("PT-16", "design 6", "upstream Proxy-Authenticate does not reach the caller") +def pt16(c): + r = c.get("/discord/v1/hop") + ok = r["status"] == 200 and "proxy-authenticate" not in r["headers"] + return ok, f"status={r['status']} proxy-authenticate={'proxy-authenticate' in r['headers']}" + + +@case("PT-17", "design 3.1", "caller key in the /ap// path prefix: stripped before forwarding, exactly one source, probe works") +def pt17(c): + out, ok = [], True + r = exchange(c.port, build("GET", f"/ap/{c.key}/discord/v1/echo?q=1", c.good(key=False))) + up = c.ulog() + names = [k for k, _ in up[0]["headers"]] if up else [] + path = up[0]["path"] if up else "" + good = (r["status"] == 200 and len(up) == 1 and path == "/v1/echo?q=1" and KEY_HEADER not in names + and c.key not in json.dumps(up)) + ok &= good + out.append(f"allow:{r['status']} upstream_path={path}") + n = len(up) + r = exchange(c.port, build("GET", f"/ap/{c.key}/discord/v1/x", c.good())) + good, d = refused(c, r, 400, "denied", "caller_key_ambiguous", n_up=n) + ok &= good + out.append(f"both:{d}") + for name, path in (("unknown", f"/ap/apk_{secrets.token_hex(32)}/discord/v1/x"), ("malformed", "/ap/apk_bad/discord/v1/x")): + r = exchange(c.port, build("GET", path, c.good(key=False))) + good, d = refused(c, r, 401, "rejected", "caller_rejected", n_up=n) + ok &= good + out.append(f"{name}:{d}") + r = exchange(c.port, build("POST", f"/ap/{c.key}/discord/v1/channels/1/messages", + c.good([("Content-Length", "2")], key=False), b"{}")) + good, d = refused(c, r, 423, "denied", "no_grant", n_up=n) + ok &= good + out.append(f"write:{d}") + hs = c.good([("Content-Length", "2")], key=False) + r = exchange(c.port, build("POST", f"/ap/{c.key}/__ap_probe/423/10", hs, b"{}"), timeout=20) + good = (r["status"] == 423 and r["headers"].get("x-ap-decision") == "denied" + and body_decision(r) == "denied") + ok &= good + out.append(f"probe:{r['status']}") + r = exchange(c.port, build("POST", f"/ap/{c.key}/__ap_probe/200/7", hs, b"{}")) + good, d = refused(c, r, 400, "denied", "probe_params", n_up=n) + ok &= good + out.append(f"probe-bad:{d}") + return ok, " | ".join(out) + + +@case("PT-02", "acc 2", "POST message create is 423 no_grant with X-AP-Decision: denied, nothing upstream") +def pt02(c): + body = b'{"content":"hi"}' + r = exchange(c.port, build("POST", "/discord/v1/channels/1/messages", + c.good([("Content-Type", "application/json"), ("Content-Length", str(len(body)))]), body)) + return refused(c, r, 423, "denied", "no_grant") + + +@case("PT-03", "acc 3", "caller-key shapes, unknown route, duplicate Authorization, CONNECT, Upgrade") +def pt03(c): + out, ok = [], True + shapes = { + "missing": c.good(key=False), + "malformed": [(KEY_HEADER, "apk_zz"), ("Authorization", c.auth)], + "unknown": [(KEY_HEADER, "apk_" + secrets.token_hex(32)), ("Authorization", c.auth)], + "duplicate": [(KEY_HEADER, c.key), (KEY_HEADER, c.key), ("Authorization", c.auth)], + } + for name, hs in shapes.items(): + r = exchange(c.port, build("GET", "/discord/v1/x", hs)) + good, d = refused(c, r, 401, "rejected", "caller_rejected") + ok &= good + out.append(f"{name}:{d}") + r = exchange(c.port, build("GET", "/nope/v1/x", c.good())) + good, d = refused(c, r, 423, "denied", "route_unknown") + ok &= good + out.append(f"route:{d}") + r = exchange(c.port, build("GET", "/discord/v1/x", c.good([("Authorization", "second")]))) + good, d = refused(c, r, 400, "denied", "authorization_duplicate") + ok &= good + out.append(f"dupauth:{d}") + r = exchange(c.port, build("CONNECT", "/discord/v1/x", c.good())) + good, d = refused(c, r, 405, "denied", "connect_refused") + ok &= good + out.append(f"connect:{d}") + r = exchange(c.port, build("GET", "/discord/v1/x", c.good([("Upgrade", "websocket"), ("Connection", "Upgrade")]))) + good, d = refused(c, r, 501, "denied", "websocket_unsupported") + ok &= good + out.append(f"upgrade:{d}") + return ok, " | ".join(out) + + +FRONT = [("Forwarded", "for=1"), ("X-Forwarded-For", "1"), ("X-Real-IP", "1"), ("Via", "1"), + ("CF-Ray", "1"), ("Tailscale-User-Login", "someone"), ("Cookie", "a=b"), + ("Proxy-Authorization", "x"), ("X-Api-Key", "k"), ("X-AP-Other", "1"), ("Expect", "100-continue")] + + +@case("PT-04", "acc 4", "caller key, x-ap-*, front and credential headers are stripped upstream") +def pt04(c): + r = c.get("/discord/v1/echo", FRONT + [("X-Keep", "yes")]) + up = c.ulog() + names = [k for k, _ in up[0]["headers"]] if up else [] + gone = [KEY_HEADER, "x-ap-other", "forwarded", "x-forwarded-for", "x-real-ip", "via", "cf-ray", + "tailscale-user-login", "cookie", "proxy-authorization", "x-api-key", "expect"] + leaked = [g for g in gone if g in names] + ok = r["status"] == 200 and len(up) == 1 and not leaked and "x-keep" in names + return ok, f"status={r['status']} leaked={leaked} names={names}" + + +@case("PT-05", "acc 5", "Authorization reaches upstream identical") +def pt05(c): + r = c.get("/discord/v1/echo") + up = c.ulog() + vals = [v for k, v in up[0]["headers"] if k == "authorization"] if up else [] + return r["status"] == 200 and vals == [c.auth], f"status={r['status']} identical={vals == [c.auth]}" + + +@case("PT-07", "acc 7", "path and Host rows of the sidecar matrix on a passthrough route") +def pt07(c): + out, ok = [], True + for p in ["/discord/v1/../x", "/discord/v1/%2e%2e/x", "/discord/v1/%2e/x", "/discord/v1%2fx", + "/discord//v1/x", "/discord/v1/%252e%252e/x"]: + r = exchange(c.port, build("GET", p, c.good())) + good, d = refused(c, r, 400, "denied", "path_ambiguous") + ok &= good + out.append(f"{p}:{r['status']}") + r = exchange(c.port, build("GET", "/discord/v1/x", c.good(), host="evil.example")) + good, d = refused(c, r, 400, "denied", "host_rejected") + ok &= good + r = exchange(c.port, build("GET", "/discord/v1/x", c.good([("Host", AUTHORITY)]))) + good, d = refused(c, r, 400, "denied", "host_rejected") + ok &= good + r = exchange(c.port, build("GET", "/discord/v1/x", c.good(), add_host=False)) + good, d = refused(c, r, 400, "denied", "host_rejected") + ok &= good + r = exchange(c.port, build("GET", f"http://{AUTHORITY}/discord/v1/x", c.good())) + good, d = refused(c, r, 400, "denied", "absolute_form") + ok &= good + return ok, " ".join(out) + f" upstream={len(c.ulog())}" + + +@case("PT-12", "acc 12", "framing conflicts produce no upstream request (layer and header recorded)") +def pt12(c): + cases = { + "cl+te": [("Content-Length", "2"), ("Transfer-Encoding", "chunked")], + "dup-cl-differing": [("Content-Length", "2"), ("Content-Length", "3")], + "comma-cl": [("Content-Length", "2, 2")], + "te-gzip": [("Transfer-Encoding", "gzip")], + "te-gzip-chunked": [("Transfer-Encoding", "gzip, chunked")], + "connection-nominates-cl": [("Connection", "close, Content-Length"), ("Content-Length", "2")], + "connection-nominates-key": [("Connection", KEY_HEADER)], + } + out = [] + for name, hs in cases.items(): + r = exchange(c.port, build("POST", "/discord/v1/upload/x", c.good(hs), b"{}")) + layer = "gate" if r["headers"].get("x-ap-decision") else ("hyper" if r["status"] else "closed") + out.append(f"{name}:{r['status']}/{layer}/decision={r['headers'].get('x-ap-decision')}") + # obs-fold: a folded header line. hyper's parser answers it; the layer is recorded. + fold = build("POST", "/discord/v1/upload/x", c.good([("X-Folded", "a\r\n b"), ("Content-Length", "2")]), b"{}") + r = exchange(c.port, fold) + layer = "gate" if r["headers"].get("x-ap-decision") else ("hyper" if r["status"] else "closed") + out.append(f"obs-fold:{r['status']}/{layer}") + n = len(c.ulog()) + # Known gap, measured not asserted (design 3.1): hyper deletes Content-Length when chunked is + # present, accepts bare LF, and collapses identical duplicate Content-Length. The proxy is + # loopback-only and the front normalises these, so stage 1 documents them. + r = exchange(c.port, build("GET", "/discord/api/x", c.good([("Content-Length", "2"), ("Transfer-Encoding", "chunked")]), b"0\r\n\r\n")) + out.append(f"get-cl+te(known gap, not asserted):{r['status']}") + lf = build("GET", "/discord/api/x", c.good(), b"").replace(b"\r\n", b"\n") + r = exchange(c.port, lf) + out.append(f"bare-lf(known gap, not asserted):{r['status']}") + # Measurement, not an assertion: hyper collapses a duplicate Content-Length with identical + # values into one before the handler runs, so the gate cannot see it and forwards one value. + r = exchange(c.port, build("POST", "/discord/v1/upload/x", c.good([("Content-Length", "2"), ("Content-Length", "2")]), b"{}")) + out.append(f"dup-cl-identical(hyper collapses, not asserted):{r['status']}") + return n == 0, f"upstream={n} " + " ".join(out) + + +@case("PT-10a", "acc 10", "probe: statuses with matching decision, keyless 401, bad params 400, client-gone line") +def pt10(c): + out, ok = [], True + body = b"{}" + hs = lambda: c.good([("Content-Length", "2")]) # noqa: E731 + res = {} + + def one(st): + res[st] = exchange(c.port, build("POST", f"/__ap_probe/{st}/10", hs(), body), timeout=20) + + threads = [threading.Thread(target=one, args=(st,)) for st in (200, 410, 423, 503)] + t0 = time.time() + for t in threads: + t.start() + for t in threads: + t.join() + took = time.time() - t0 + want = {200: None, 410: "expired", 423: "denied", 503: "unavailable"} + for st, dec in want.items(): + r = res[st] + good = (r["status"] == st and r["headers"].get("x-ap-decision") == dec + and body_decision(r) == dec and "retry-after" not in r["headers"]) + ok &= good + out.append(f"{st}:{'ok' if good else 'BAD'}") + r = exchange(c.port, build("POST", "/__ap_probe/200/10", [("Content-Length", "2")], body)) + ok &= r["status"] == 401 and r["headers"].get("x-ap-decision") == "rejected" + out.append(f"keyless:{r['status']}") + for bad in ("/__ap_probe/201/10", "/__ap_probe/200/7"): + r = exchange(c.port, build("POST", bad, hs(), body)) + ok &= r["status"] == 400 and code_of(r) == "probe_params" + # Client disconnect during the wait: record whether the proxy notices and how fast. + s = socket.create_connection(("127.0.0.1", c.port), 5) + s.sendall(build("POST", "/__ap_probe/200/10", hs(), body)) + time.sleep(0.5) + s.close() + time.sleep(2.0) + with open(c.e.audit_file, "rb") as f: + text = f.read().decode(errors="replace") + gone = '"event":"client_gone"' in text + out.append(f"client_gone_line={'yes' if gone else 'no (measurement: disconnect did not reach the handler within 2s)'}") + ok &= len(c.ulog()) == 0 and took < 25 + return ok, " ".join(out) + f" upstream={len(c.ulog())}" + + +# ------------------------------------------------------------------ PT-06 (runs on its own instance) +@case("PT-06", "acc 6", "no Authorization, caller key or path token in stdout, stderr, audit or any file", "secrets") +def pt06(c): + e = c.e + hook = f"/discord/v1/webhooks/1/{c.path_token}/github" + inter = f"/discord/v1/interactions/1/{c.path_token}/callback" + steps = [ + ("allow", build("GET", "/discord/v1/echo", c.good())), + ("deny-write", build("POST", hook, c.good([("Content-Length", "2")]), b"{}")), + ("deny-inter", build("POST", inter, c.good([("Content-Length", "2")]), b"{}")), + ("413", build("POST", "/discord/v1/upload/x", c.good([("Content-Length", "99999")]))), + ("malformed", build("GET", "/discord/v1/x", [(KEY_HEADER, "apk_bad"), ("Authorization", c.auth)])), + ("panic", build("GET", "/__ap_test_panic", c.good())), + ("webhook-read", build("GET", hook, c.good())), + # The same outcomes with the caller key in the path prefix (no header). + ("p-allow", build("GET", f"/ap/{c.key}/discord/v1/echo", c.good(key=False))), + ("p-deny-write", build("POST", f"/ap/{c.key}{hook}", c.good([("Content-Length", "2")], key=False), b"{}")), + ("p-413", build("POST", f"/ap/{c.key}/discord/v1/upload/x", c.good([("Content-Length", "99999")], key=False))), + ("p-path-ambiguous", build("GET", f"/ap/{c.key}/discord/v1/../x", c.good(key=False))), + ("p-unknown-key", build("GET", f"/ap/apk_{secrets.token_hex(32)}/discord/v1/x", c.good(key=False))), + ("p-malformed-key", build("GET", "/ap/apk_bad/discord/v1/x", c.good(key=False))), + ("p-both", build("GET", f"/ap/{c.key}/discord/v1/x", c.good())), + ("p-no-route", build("GET", f"/ap/{c.key}/", c.good(key=False))), + ("p-panic", build("GET", f"/ap/{c.key}/__ap_test_panic", c.good(key=False))), + ] + out = [] + for name, raw in steps: + r = exchange(c.port, raw) + out.append(f"{name}:{r['status']}") + # Upstream failure: point the route at a dead port, then restore. + cfg = e.cur_cfg + with open(cfg) as f: + text = f.read() + e.write_file(cfg, text.replace("port = 18443", "port = 9")) + r = exchange(c.port, build("GET", "/discord/v1/x", c.good())) + out.append(f"upstream-down:{r['status']}") + r = exchange(c.port, build("GET", f"/ap/{c.key}/discord/v1/x", c.good(key=False))) + out.append(f"p-upstream-down:{r['status']}") + e.write_file(cfg, text) + r = exchange(c.port, build("GET", "/discord/v1/echo", c.good())) + 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/"] + hits, scanned = [], [] + for root, _d, files in os.walk(e.work): + rel = os.path.relpath(root, e.work) + if rel == "secrets" or rel.startswith("secrets" + os.sep): + continue + for fn in files: + p = os.path.join(root, fn) + try: + data = open(p, "rb").read() + except OSError: + continue + scanned.append(os.path.relpath(p, e.work)) + if any(n in data for n in needles): + hits.append(os.path.relpath(p, e.work)) + log = open(os.path.join(e.work, f"proxy-{c.port}.log"), "rb").read() # stdout and stderr of the proxy + panicked = b"panic at" in log + audit_has = os.path.exists(e.audit_file) and b"" in open(e.audit_file, "rb").read() + ok = not hits and alive and panicked and audit_has + return ok, f"hits={hits} scanned={len(scanned)} panic_line={panicked} redacted_in_audit={audit_has} " + " ".join(out) + + +# ------------------------------------------------------------------ PT-08 (startup refusals) +@case("PT-08", "acc 8", "a non-loopback listener is refused at startup: exit 2, nothing listening", "startup") +def pt08(c): + e = c.e + cfg = os.path.join(e.work, "config-nonloop.toml") + e.write_file(cfg, pt_text(c.key, PORT_C, listen_host="0.0.0.0")) + p = subprocess.run([os.path.join(e.bindir, "auth-proxy"), "--config", cfg], capture_output=True, + env=e._proxy_env(), timeout=10) + listening = wait_port(PORT_C, None, 0.5) + # Probe enabled is allowed by this build; a loopback config must start without an expiry store. + return p.returncode == 2 and not listening, f"exit={p.returncode} listening={listening}" + + +# ------------------------------------------------------------------ PT-09, PT-13 (small limits) +@case("PT-09", "acc 9", "connection cap, header-read and body-read timeouts close the connection, proxy keeps serving", + "limits") +def pt09(c): + port = PORT_B + out, ok = [], True + held = [socket.create_connection(("127.0.0.1", port), 5) for _ in range(3)] + for s in held: # three idle connections hold the three permits + s.sendall(b"GET /discord/v1/x HTTP/1.1\r\nHost: " + AUTHORITY.encode() + b"\r\n") + time.sleep(0.2) + extra = socket.create_connection(("127.0.0.1", port), 5) + extra.settimeout(3) + try: + extra.sendall(build("GET", "/discord/v1/echo", c.good())) + data = extra.recv(4096) + except OSError: + data = b"" + capped = data == b"" + extra.close() + out.append(f"cap_closed={capped}") + ok &= capped + for s in held: + s.close() + time.sleep(1.5) + r = exchange(port, build("GET", "/discord/v1/echo", c.good())) + ok &= r["status"] == 200 + out.append(f"after_cap={r['status']}") + # Header read timeout: half a header line. + r = exchange(port, b"GET /discord/v1/x HTT", timeout=4, stall=(0, 0)) + ok &= r["status"] == 0 and r["closed"] + out.append(f"header_timeout_closed={r['closed']}") + r = exchange(port, build("GET", "/discord/v1/echo", c.good())) + ok &= r["status"] == 200 + # Body read timeout: a chunk, then silence. + r = exchange(port, build("POST", "/discord/v1/upload/x", c.good([("Transfer-Encoding", "chunked")]), b"3\r\nabc\r\n"), + timeout=5) + ok &= r["status"] == 0 and r["closed"] + out.append(f"body_timeout_closed={r['closed']}") + r = exchange(port, build("GET", "/discord/v1/echo", c.good())) + ok &= r["status"] == 200 + out.append(f"still_serving={r['status']}") + return ok, " ".join(out) + + +@case("PT-13", "acc 13", "allowed-body boundary: stall and over-cap before and after the first byte; chunked stays chunked", + "limits") +def pt13(c): + port = PORT_B + out, ok = [], True + # Stall after a prefix: closed, one audit line body_failed_after_send. + before = open(c.e.audit_file, "rb").read().count(b"body_failed_after_send") + r = exchange(port, build("POST", "/discord/v1/upload/x", c.good([("Transfer-Encoding", "chunked")]), b"3\r\nabc\r\n"), + timeout=5) + time.sleep(0.3) + after = open(c.e.audit_file, "rb").read().count(b"body_failed_after_send") + good = r["status"] == 0 and r["closed"] and after - before == 1 + ok &= good + out.append(f"stall_after_prefix closed={r['closed']} audit_lines={after - before}") + # Stall before the first byte: 503. + r = exchange(port, build("POST", "/discord/v1/upload/x", c.good([("Transfer-Encoding", "chunked")])), timeout=5) + good = r["status"] == 503 and r["headers"].get("x-ap-decision") == "unavailable" + ok &= good + out.append(f"stall_before={r['status']}") + # Undeclared over-cap before any byte: 413. + big = b"%x\r\n%s\r\n" % (6000, b"a" * 6000) + r = exchange(port, build("POST", "/discord/v1/upload/x", c.good([("Transfer-Encoding", "chunked")]), big + b"0\r\n\r\n"), + timeout=5) + ok &= r["status"] == 413 + out.append(f"overcap_before={r['status']}") + # Undeclared over-cap after a prefix: closed. + part = b"%x\r\n%s\r\n" % (3000, b"a" * 3000) + r = exchange(port, build("POST", "/discord/v1/upload/x", c.good([("Transfer-Encoding", "chunked")]), + part + part + b"0\r\n\r\n"), timeout=5) + ok &= r["status"] == 0 and r["closed"] + out.append(f"overcap_after_closed={r['closed']}") + # Chunked allowed body arrives chunked with no Content-Length. + c.e.ureset() + ch = b"5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n" + r = exchange(port, build("POST", "/discord/v1/upload/x", c.good([("Transfer-Encoding", "chunked")]), ch), timeout=5) + up = c.ulog() + names = [k for k, _ in up[0]["headers"]] if up else [] + good = (r["status"] == 200 and len(up) == 1 and "chunked" in up[0]["transfer_encoding"] + and "content-length" not in names and up[0]["body_len"] == 11) + ok &= good + out.append(f"chunked_ok={good}") + return ok, " ".join(out) + + +@case("PT-14", "acc 5/start", "passthrough-only config starts with no expiry store, session or admin socket", "startup") +def pt14(c): + e = c.e + cfg = os.path.join(e.work, "config-nostore.toml") + e.write_file(cfg, pt_text(c.key, PORT_C)) + e.start_passthrough(cfg, PORT_C) + try: + r = exchange(PORT_C, build("GET", "/discord/v1/xap", c.good())) + socks = [n for n in os.listdir(e.run_dir)] if os.path.isdir(e.run_dir) else [] + finally: + e.stop_proxy() + return r["status"] == 200 and not socks, f"status={r['status']} sockets={socks}" + + +# ------------------------------------------------------------------ driver +def run_instance(c, instance, results): + cases = [x for x in CASES if x[3] == instance] + if not cases: + return + e = c.e + cfg = os.path.join(e.work, f"config-{instance}.toml") + if instance == "main": + e.write_file(cfg, pt_text(c.key, PORT_A)) + e.start_passthrough(cfg, PORT_A) + c.port = PORT_A + elif instance == "secrets": + e.write_file(cfg, pt_text(c.key, PORT_A, probe=False)) + e.start_passthrough(cfg, PORT_A) + c.port = PORT_A + elif instance == "limits": + lim = "max_connections = 3\nheader_read_secs = 1\nbody_read_secs = 1" + e.write_file(cfg, pt_text(c.key, PORT_B, limits=lim, probe=False)) + e.start_passthrough(cfg, PORT_B) + c.port = PORT_B + try: + for cid, row, name, _, fn in cases: + e.ureset() + try: + ok, detail = fn(c) + except Exception as ex: + ok, detail = False, f"EXCEPTION {ex!r} {traceback.format_exc(limit=2)}" + results.append({"id": cid, "row": row, "case": name, "verdict": "PASS" if ok else "FAIL", "detail": detail}) + print(f"{'PASS' if ok else 'FAIL'} | {cid} | {row} | {name} | {detail}", flush=True) + finally: + e.stop_proxy() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bin", required=True, help="directory with auth-proxy (matrix-upstream + stage1-probe build)") + ap.add_argument("--work", help="work directory (default: a fresh temp dir)") + ap.add_argument("--json", help="write the per-case results here") + a = ap.parse_args() + bindir = os.path.abspath(a.bin) + if not os.path.exists(os.path.join(bindir, "auth-proxy")): + print(f"missing binary auth-proxy in {bindir}", file=sys.stderr) + return 2 + work = os.path.abspath(a.work) if a.work else tempfile.mkdtemp(prefix="apm-pt-") + os.makedirs(work, exist_ok=True) + c = Ctx(Env(bindir, work)) + results = [] + try: + for instance in ("main", "secrets", "limits", "startup"): + run_instance(c, instance, results) + finally: + c.e.close() + ids = [r["id"] for r in results] + missing = [i for i in EXPECTED if i not in ids] + extra = [i for i in ids if i not in EXPECTED] + passed = sum(1 for r in results if 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"summary: {passed} PASS of {len(EXPECTED)} rows; work dir {work}") + return 0 if (passed == len(EXPECTED) and not missing and not extra) else 1 + + +if __name__ == "__main__": + sys.exit(main())