diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d01381d..b7516a3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,6 +39,9 @@ jobs: - name: Clippy (stage1-probe) run: cargo clippy -p ap-proxy --all-targets --features stage1-probe -- -D warnings + - name: Clippy (matrix-upstream) + run: cargo clippy -p ap-proxy --all-targets --features matrix-upstream,stage1-probe -- -D warnings + - name: Unit and integration tests run: cargo test --workspace @@ -56,6 +59,9 @@ jobs: 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_HOLD_PAUSE target/release/auth-proxy; then + echo "hold-pause test hook 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 @@ -83,13 +89,16 @@ 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: Build the matrix binary without stage1-probe (separate target dir) + run: CARGO_TARGET_DIR=target/noprobe cargo build -p ap-proxy --features matrix-upstream + + - name: Passthrough matrix cargo target (Muse gate; both builds) + run: AP_MATRIX_NOPROBE_BIN="$PWD/target/noprobe/debug" 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 + python3 tests/matrix/passthrough.py --bin target/debug --noprobe-bin target/noprobe/debug --json matrix-pt.json | tee matrix-pt.txt - name: Upload matrix results if: always() diff --git a/Cargo.lock b/Cargo.lock index a35f183..e5310db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -72,6 +72,7 @@ dependencies = [ "futures-util", "getrandom 0.2.17", "h2", + "hmac", "http", "http-body-util", "hyper", @@ -82,6 +83,7 @@ dependencies = [ "rustls", "serde", "serde_json", + "sha2", "subtle", "tokio", "tokio-rustls", @@ -321,6 +323,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -364,6 +367,16 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "fiat-crypto" version = "0.2.9" @@ -513,6 +526,15 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.5.0" @@ -1202,6 +1224,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "signature" version = "2.2.0" @@ -1362,6 +1394,7 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.61.2", diff --git a/README.md b/README.md index 49453bc..acca101 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,24 @@ The gate constrains the agent, not the Muse platform: Muse's egress holds the re can call Discord directly. See `docs/design/muse-gated-passthrough.md`, `docs/runbooks/muse-stage1.md` and `deploy/muse/pilot-policy.example.toml`. +## Muse gated passthrough (stage 2, pilot) + +Stage 2 adds a third verdict, `hold`, for writes the owner wants to approve one by one. A held request +keeps its connection open. The gate tells the owner a request is waiting (a fixed text and a link, never +the content), the owner opens a separate approval page, and only an explicit approve forwards the request. +Deny, expiry (`hold_secs`), a caller who gives up, a policy reload that drops the identity, and shutdown +all end the request with a refusal and nothing sent upstream. The connection is the state: there is no +queue, and a restart forgets every held request. + +The gate constrains the agent, not the Muse platform. Muse's egress holds the real Discord token and can +call Discord directly. A stolen caller key lets someone send requests as that identity (the per-identity +cap and the cooldown bound the prompt spam) and does not give them approval rights. + +Not claimed: exactly-once delivery (if the request was forwarded and the response was lost, a retry can be +approved and forwarded again), protection against Muse itself, a measured end-to-end hold window through the +real front, or a measured disconnect signal through the front. See `docs/runbooks/muse-stage2.md` +and `docs/design/muse-gated-passthrough.md`. + ## Features Implemented and tested in Phase 1: diff --git a/crates/ap-client/tests/roundtrip.rs b/crates/ap-client/tests/roundtrip.rs index 6e8c194..72830fb 100644 --- a/crates/ap-client/tests/roundtrip.rs +++ b/crates/ap-client/tests/roundtrip.rs @@ -85,6 +85,7 @@ async fn start_server(root: &Path, caller_sha: &str) -> Server { let app = App::new( cfg_path, cfg, + &text, root.join("tokens"), ap_broker::expiry::file_in(&root.join("tokens")), Arc::new(FileStore::new(root.join("secrets"))), diff --git a/crates/ap-core/src/audit.rs b/crates/ap-core/src/audit.rs index 50a75a8..a881bc5 100644 --- a/crates/ap-core/src/audit.rs +++ b/crates/ap-core/src/audit.rs @@ -49,6 +49,64 @@ impl AuditRec { } } +/// Transitions a held request can write (design 3.9). The record type has no free-text field. +pub const HOLD_TRANSITIONS: &[&str] = &[ + "held", + "approved", + "denied", + "expired", + "abandoned", + "superseded", + "dropped_on_reload", + "forward_started", + "completed", + "abandoned_after_approve", + "connect_failed", + "audit_unavailable", + "notify_failed", +]; + +/// One audit line for a transition of a held request. Every key is always present (null when it +/// has no value), so the key set is fixed. There is no field for a header value, a query, a body, +/// a key or a notification target. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct HoldRec { + /// The hold entry id, which names the request across its transitions. + pub request_id: String, + pub identity: String, + pub route: Option, + pub method: String, + /// Route-relative path. Query and fragment are dropped and token segments redacted on write. + pub path: String, + /// Credential-blind digest of the outbound request (hex sha256). + pub digest: Option, + /// One of [`HOLD_TRANSITIONS`]. + pub transition: &'static str, + /// Approver identity, on decisions only. + pub approver: Option, + pub code: Option, + pub status: Option, + pub duration_ms: u64, + /// Whether the request carried an `Authorization` header. + pub auth_present: bool, + /// `scheme://host:port` the request goes to, on the `held` record only. + pub upstream: Option, + /// The policy generation the request was admitted under, on the `held` record only. + pub policy_generation: Option, +} + +impl HoldRec { + /// Serialize as one JSON line with a trailing newline. The path is cut to its path part and + /// its `webhooks`/`interactions` token segments are redacted here, so no caller has to. + pub fn to_json_line(&self) -> String { + let mut rec = self.clone(); + rec.path = crate::canon::redact_path(&path_only(&rec.path)); + let mut line = serde_json::to_string(&rec).unwrap_or_else(|_| "{}".to_string()); + line.push('\n'); + line + } +} + #[cfg(test)] mod tests { use super::*; @@ -137,4 +195,71 @@ mod tests { assert_eq!(v["code"], "policy_denied"); assert!(v["aws_target"].is_null()); } + + fn hold_sample() -> HoldRec { + HoldRec { + request_id: "0123abcd".into(), + identity: "muse".into(), + route: Some("discord".into()), + method: "POST".into(), + path: "/channels/1/messages?x=1".into(), + digest: Some("ab".repeat(32)), + transition: "held", + approver: None, + code: None, + status: None, + duration_ms: 3, + auth_present: true, + upstream: Some("https://discord.example.test:443".into()), + policy_generation: Some(1), + } + } + + #[test] + fn hold_json_keys_are_exactly_the_allowed_set() { + let v: serde_json::Value = + serde_json::from_str(hold_sample().to_json_line().trim_end()).unwrap(); + let mut keys: Vec<&str> = v.as_object().unwrap().keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!( + keys, + vec![ + "approver", + "auth_present", + "code", + "digest", + "duration_ms", + "identity", + "method", + "path", + "policy_generation", + "request_id", + "route", + "status", + "transition", + "upstream", + ] + ); + } + + #[test] + fn hold_line_drops_query_and_redacts_tokens() { + let mut r = hold_sample(); + r.path = "/webhooks/123/SECRETTOKEN/messages?wait=true#f".into(); + let line = r.to_json_line(); + assert!(!line.contains("SECRETTOKEN")); + assert!(!line.contains("wait=true")); + assert!(line.contains("/webhooks/123//messages")); + assert_eq!(line.matches('\n').count(), 1); + } + + #[test] + fn every_hold_transition_serializes() { + for t in HOLD_TRANSITIONS { + let mut r = hold_sample(); + r.transition = t; + let v: serde_json::Value = serde_json::from_str(r.to_json_line().trim_end()).unwrap(); + assert_eq!(v["transition"], *t); + } + } } diff --git a/crates/ap-core/src/canon.rs b/crates/ap-core/src/canon.rs index 543b7c2..4eec15a 100644 --- a/crates/ap-core/src/canon.rs +++ b/crates/ap-core/src/canon.rs @@ -113,6 +113,21 @@ const MAX_DECODE_LAYERS: usize = 4; /// percent-encode (non-ASCII, controls, space, DEL, `"`, `<`, `>`, backtick, `{`, `}`) are /// refused too, because for those the matched path would not be the path that is sent. pub fn path_ambiguous(p: &str) -> bool { + path_ambiguous_with(p, false) +} + +/// [`path_ambiguous`] plus one more refusal, used where a `hold` grant can be overridden by a +/// broader allow match (the passthrough pipeline): a percent-escape of an RFC 3986 unreserved +/// byte (`A-Z a-z 0-9 - . _ ~`), in any decode layer. `%6D` and `m` name the same resource, and +/// hold patterns compare raw bytes, so the spelling would let a caller pick the verdict. Refusing +/// keeps the form that policy matches byte-identical to the form that is sent and shown. The +/// sidecar pipeline has no hold verdict and no precedence between grants, so an unmatched spelling +/// there is a plain `no_grant`, and it keeps accepting these escapes. +pub fn path_ambiguous_passthrough(p: &str) -> bool { + path_ambiguous_with(p, true) +} + +fn path_ambiguous_with(p: &str, refuse_unreserved: bool) -> bool { if p.contains('\\') || p.bytes() .any(|b| b <= 0x20 || b >= 0x7f || b"\"<>`{}".contains(&b)) @@ -149,6 +164,7 @@ pub fn path_ambiguous(p: &str) -> bool { if b < 0x20 || b == 0x7f || matches!(b, b'.' | b'/' | b'\\') + || (refuse_unreserved && is_unreserved(b)) || (depth >= 2 && b == b';') { return true; @@ -173,6 +189,66 @@ pub fn path_ambiguous(p: &str) -> bool { (0..cur.len()).any(|i| cur[i] == b'%' && hex_pair(&cur, i).is_some()) } +/// RFC 3986 section 2.3 unreserved characters. +fn is_unreserved(b: u8) -> bool { + b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') +} + +/// Most percent-decode layers a caller-key search looks through. Deeper than the path check +/// goes, so the search never gives up before `path_ambiguous` would have. +const KEY_SEARCH_LAYERS: usize = MAX_DECODE_LAYERS + 4; + +/// True when `s` (a route-relative path or a query string) carries an `apk_` caller key, in +/// any percent-encoded spelling. +/// +/// `s` is searched raw, then after each percent-decode layer up to a fixed point (hex digits in +/// either case, decoded by value like [`path_ambiguous`]). On every layer the match is ASCII +/// case-insensitive and finds either the authenticated `key`'s 64 hex digits (the `apk_` prefix +/// may itself be encoded, so the digits are the needle) or any well-formed `apk_<64 hex>` key. +/// A string still decodable after [`KEY_SEARCH_LAYERS`] layers counts as carrying one: the +/// answer is fail-closed, never "not found". The key is never copied into a message. +pub fn echoes_caller_key(s: &str, key: &str) -> bool { + let digits = key.strip_prefix("apk_").unwrap_or(key).as_bytes(); + let mut cur = s.as_bytes().to_vec(); + for _ in 0..=KEY_SEARCH_LAYERS { + if has_key_text(&cur, digits) { + return true; + } + let mut out = Vec::with_capacity(cur.len()); + let mut decoded = false; + let mut i = 0; + while i < cur.len() { + if cur[i] == b'%' { + if let Some(b) = hex_pair(&cur, i) { + out.push(b); + decoded = true; + i += 3; + continue; + } + } + out.push(cur[i]); + i += 1; + } + if !decoded { + return false; + } + cur = out; + } + true +} + +fn has_key_text(hay: &[u8], digits: &[u8]) -> bool { + if !digits.is_empty() + && hay + .windows(digits.len()) + .any(|w| w.eq_ignore_ascii_case(digits)) + { + return true; + } + hay.windows(4 + 64) + .any(|w| w[..4].eq_ignore_ascii_case(b"apk_") && w[4..].iter().all(u8::is_ascii_hexdigit)) +} + fn hex_pair(b: &[u8], i: usize) -> Option { let d = |j: usize| b.get(j).and_then(|c| (*c as char).to_digit(16)); u8::try_from(d(i + 1)? * 16 + d(i + 2)?).ok() diff --git a/crates/ap-core/src/config.rs b/crates/ap-core/src/config.rs index 5e7dd91..160b996 100644 --- a/crates/ap-core/src/config.rs +++ b/crates/ap-core/src/config.rs @@ -65,6 +65,12 @@ pub struct Config { pub passthrough: Option, #[serde(default)] pub probe: Probe, + /// Approval plane (design 3.6). Passthrough deployments only. + #[serde(default)] + pub approval: Option, + /// Notifier (design 3.4 step 5). Absent means holds are not announced and simply expire. + #[serde(default)] + pub notify: Option, } /// How a route treats the request credential. @@ -78,7 +84,7 @@ pub enum RouteMode { Passthrough, } -/// What a matching grant does. Stage 1 supports `allow` only. +/// What a matching grant does. `hold` is valid only on passthrough grants with `path_patterns`. #[derive(Debug, Deserialize, Clone, Copy, Default, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum Decision { @@ -113,6 +119,83 @@ pub struct Passthrough { /// No byte from upstream, 1..=3600. #[serde(default = "default_upstream_idle_secs")] pub upstream_idle_secs: u64, + /// How long a held request waits for a human, 5..=600. + #[serde(default = "default_hold_secs")] + pub hold_secs: u64, + /// Largest body a held request may carry, 1..=8 MiB. + #[serde(default = "default_held_body_max_bytes")] + pub held_body_max_bytes: u64, + /// Held requests at once, 1..=1024. + #[serde(default = "default_max_held_total")] + pub max_held_total: usize, + /// Held requests at once per identity, 1..=`max_held_total`. + #[serde(default = "default_max_held_per_identity")] + pub max_held_per_identity: usize, + /// Seconds an identity is refused after a human deny, 0..=3600 (0 disables). + #[serde(default = "default_cooldown_secs")] + pub cooldown_secs: u64, +} + +fn default_hold_secs() -> u64 { + 120 +} + +fn default_held_body_max_bytes() -> u64 { + 1024 * 1024 +} + +fn default_max_held_total() -> usize { + 32 +} + +fn default_max_held_per_identity() -> usize { + 4 +} + +fn default_cooldown_secs() -> u64 { + 60 +} + +/// The approval listener and its single approver credential (design 3.6). No secret lives here: +/// the password is stored as a hash. +#[derive(Debug, Deserialize, Clone, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Approval { + /// Loopback address of the approval listener. Must differ from `listen.proxy`. + pub listen: SocketAddr, + /// Basic-auth user name. + pub user: String, + /// Lowercase hex sha256 of the approver password. + pub password_sha256: String, + /// Base URL the notification link is built from. http or https, no userinfo, query or fragment. + pub public_base_url: String, + /// Basic-auth realm. + #[serde(default = "default_realm")] + pub realm: String, +} + +fn default_realm() -> String { + "auth-proxy approval".to_string() +} + +/// How the owner is told that a request is waiting. +#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum NotifyKind { + Ntfy, +} + +/// Notifier settings. The topic and token are read from files at startup, never from this file. +#[derive(Debug, Deserialize, Clone, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Notify { + pub kind: NotifyKind, + pub base_url: String, + /// Absolute path of a regular file (mode 0600) holding the topic. + pub topic_file: String, + /// Absolute path of a regular file (mode 0600) holding a bearer token. Optional. + #[serde(default)] + pub token_file: Option, } fn default_caller_key_header() -> String { @@ -258,10 +341,16 @@ pub struct Grant { pub credential: String, pub route: String, pub methods: Vec, + /// Prefix paths. At least one of `paths` and `path_patterns` is required. + #[serde(default)] pub paths: Vec, + /// Whole-path segment patterns (`/a/*/b`): a segment is a literal or `*` for exactly one + /// non-empty segment. Passthrough routes only. Required for `hold`. + #[serde(default)] + pub path_patterns: Vec, #[serde(default)] pub aws_targets: Vec, - /// `allow` (default). `hold` is not supported in stage 1. + /// `allow` (default) or `hold` (passthrough routes, `path_patterns` only). #[serde(default)] pub decision: Decision, } @@ -374,6 +463,48 @@ fn valid_prefix_path(p: &str) -> Result<(), &'static str> { Ok(()) } +/// A whole-path pattern: `/`, then one or more segments, each a literal or `*`. No `%`, no +/// empty segment (so no `//` and no trailing `/`), no dot segment, and `*` only as a full segment. +fn valid_path_pattern(p: &str) -> Result<(), &'static str> { + if !p.starts_with('/') { + return Err("must start with /"); + } + if p.contains('%') { + return Err("must not contain %"); + } + for seg in p[1..].split('/') { + if seg.is_empty() { + return Err("must not contain an empty segment"); + } + if seg == "." || seg == ".." { + return Err("must not contain a dot segment"); + } + if seg.contains('*') && seg != "*" { + return Err("* is only allowed as a whole segment"); + } + if !seg.bytes().all(|b| b.is_ascii_graphic()) { + return Err("must be printable ASCII without spaces"); + } + } + Ok(()) +} + +/// `http(s)://host[:port][/path]` with no userinfo, query, fragment or whitespace. +fn valid_base_url(u: &str) -> bool { + let rest = match u + .strip_prefix("https://") + .or_else(|| u.strip_prefix("http://")) + { + Some(r) => r, + None => return false, + }; + let host = rest.split('/').next().unwrap_or(""); + !host.is_empty() + && u.len() <= 512 + && !u.contains(['@', '?', '#']) + && u.bytes().all(|b| b.is_ascii_graphic()) +} + /// 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); @@ -426,6 +557,89 @@ fn validate_passthrough(p: &Passthrough) -> Result<(), ConfigError> { return Err(invalid(format!("passthrough.{field} must be in 1..={max}"))); } } + for (field, v, min, max) in [ + ("hold_secs", p.hold_secs, 5, 600), + ( + "held_body_max_bytes", + p.held_body_max_bytes, + 1, + 8 * 1024 * 1024, + ), + ("cooldown_secs", p.cooldown_secs, 0, 3600), + ] { + if !(min..=max).contains(&v) { + return Err(invalid(format!( + "passthrough.{field} must be in {min}..={max}" + ))); + } + } + if !(1..=1024).contains(&p.max_held_total) { + return Err(invalid("passthrough.max_held_total must be in 1..=1024")); + } + if !(1..=p.max_held_total).contains(&p.max_held_per_identity) { + return Err(invalid( + "passthrough.max_held_per_identity must be in 1..=max_held_total", + )); + } + Ok(()) +} + +fn validate_approval(a: &Approval, proxy: SocketAddr) -> Result<(), ConfigError> { + if !a.listen.ip().is_loopback() { + return Err(invalid("approval.listen must be a loopback address")); + } + if a.listen.port() == 0 || a.listen.port() == proxy.port() { + return Err(invalid( + "approval.listen must have a port other than 0 and other than listen.proxy", + )); + } + if a.user.is_empty() + || a.user.len() > 64 + || !a.user.bytes().all(|b| b.is_ascii_graphic() && b != b':') + { + return Err(invalid( + "approval.user must be 1..=64 printable ASCII bytes without ':'", + )); + } + if !is_hex64_lower(&a.password_sha256) { + return Err(invalid( + "approval.password_sha256 must be 64 lowercase hex characters", + )); + } + if !valid_base_url(&a.public_base_url) { + return Err(invalid( + "approval.public_base_url must be an http(s) URL without userinfo, query or fragment", + )); + } + let realm_ok = !a.realm.is_empty() + && a.realm.len() <= 64 + && a.realm + .bytes() + .all(|b| (b == b' ' || b.is_ascii_graphic()) && b != b'"' && b != b'\\'); + if !realm_ok { + return Err(invalid( + "approval.realm must be 1..=64 printable ASCII bytes without quote or backslash", + )); + } + Ok(()) +} + +fn validate_notify(n: &Notify) -> Result<(), ConfigError> { + if !valid_base_url(&n.base_url) { + return Err(invalid( + "notify.base_url must be an http(s) URL without userinfo, query or fragment", + )); + } + for (field, path) in [ + ("topic_file", Some(&n.topic_file)), + ("token_file", n.token_file.as_ref()), + ] { + if let Some(p) = path { + if !p.starts_with('/') || p.len() > 1024 || p.bytes().any(|b| b == 0) { + return Err(invalid(format!("notify.{field} must be an absolute path"))); + } + } + } Ok(()) } @@ -484,6 +698,10 @@ impl Config { } let mut route_hosts: HashMap<&str, &str> = HashMap::new(); + // The upstream resource is `https://{host}:{port}{path}`, not the route name, so two + // passthrough routes on one authority would let the caller pick the route name that + // carries the weaker verdict. Refused outright. + let mut passthrough_authorities: HashMap<(String, u16), &str> = HashMap::new(); for r in &self.routes { if !valid_slug(&r.name, 32) { return Err(invalid(format!( @@ -543,6 +761,14 @@ impl Config { } } RouteMode::Passthrough => { + let authority = (r.host.trim_end_matches('.').to_ascii_lowercase(), r.port); + if let Some(first) = passthrough_authorities.insert(authority, r.name.as_str()) + { + return Err(invalid(format!( + "passthrough routes {first:?} and {:?} share one host and port; a held resource must have one route", + r.name + ))); + } if r.name == "ap" { return Err(invalid(format!( "passthrough route name {:?} is reserved", @@ -602,6 +828,17 @@ impl Config { if self.probe.enabled && passthrough_routes.is_empty() { return Err(invalid("[probe] needs a passthrough deployment")); } + if passthrough_routes.is_empty() && (self.approval.is_some() || self.notify.is_some()) { + return Err(invalid( + "[approval] and [notify] need a passthrough deployment", + )); + } + if let Some(a) = &self.approval { + validate_approval(a, self.listen.proxy)?; + } + if let Some(n) = &self.notify { + validate_notify(n)?; + } let mut credential_ids = HashSet::new(); let mut credential_routes: HashMap<&str, HashSet<&str>> = HashMap::new(); @@ -654,6 +891,36 @@ impl Config { if self.grants.len() > MAX_GRANTS { return Err(invalid(format!("at most {MAX_GRANTS} grants are allowed"))); } + // A hold pattern must not share a request with an allow grant of the same identity, + // route and method. Hold wins when both match, but a spelling of the held resource that + // the pattern does not claim (a trailing `/`, a path parameter) would still reach the + // allow grant, so the overlap is refused instead of relied on. + for h in self.grants.iter().filter(|g| g.decision == Decision::Hold) { + for a in self.grants.iter().filter(|g| { + g.decision == Decision::Allow + && g.identity == h.identity + && g.route == h.route + && g.methods.iter().any(|m| h.methods.contains(m)) + }) { + for hp in &h.path_patterns { + let clash = a + .paths + .iter() + .find(|p| crate::policy::prefix_overlaps_pattern(p, hp)) + .or_else(|| { + a.path_patterns + .iter() + .find(|p| crate::policy::patterns_overlap(p, hp)) + }); + if let Some(ap) = clash { + return Err(invalid(format!( + "grant for identity {:?} on route {:?}: allow path {:?} overlaps hold pattern {:?} for the same method; an allow grant must not cover a held resource", + a.identity, a.route, ap, hp + ))); + } + } + } + } for g in &self.grants { if !identity_names.contains(g.identity.as_str()) { return Err(invalid(format!( @@ -675,10 +942,15 @@ impl Config { g.route ))); } - if g.decision != Decision::Allow { - return Err(invalid( - "grant decision \"hold\" is not supported yet (stage 1 allows or denies)", - )); + if g.decision == Decision::Hold { + if g.path_patterns.is_empty() { + return Err(invalid("grant decision \"hold\" needs path_patterns")); + } + if !g.paths.is_empty() { + return Err(invalid( + "grant decision \"hold\" must not use prefix paths, only path_patterns", + )); + } } } else { let routes = credential_routes @@ -697,7 +969,12 @@ impl Config { } if g.decision != Decision::Allow { return Err(invalid( - "grant decision \"hold\" is not supported yet (stage 1 allows or denies)", + "grant decision \"hold\" is only valid on passthrough routes", + )); + } + if !g.path_patterns.is_empty() { + return Err(invalid( + "grant path_patterns are only valid on passthrough routes", )); } } @@ -716,9 +993,16 @@ impl Config { ))); } } - if g.paths.is_empty() { + if g.paths.is_empty() && g.path_patterns.is_empty() { return Err(invalid("grant paths must not be empty")); } + if g.path_patterns.len() > 64 { + return Err(invalid("grant has too many path_patterns")); + } + for p in &g.path_patterns { + valid_path_pattern(p) + .map_err(|why| invalid(format!("grant path_pattern {p:?}: {why}")))?; + } for p in &g.paths { let checked = if on_passthrough { valid_prefix_path(p) @@ -1443,11 +1727,213 @@ paths = ["/api/v10/channels/", "/api/v10/users/@me"] #[test] fn rejects_hold_decision_in_stage_1() { + // Hold on prefix paths is refused: a hold grant needs path_patterns. let text = pt_base().replace( "methods = [\"GET\"]", "decision = \"hold\"\nmethods = [\"GET\"]", ); - expect_invalid(&text, "not supported yet"); + expect_invalid(&text, "needs path_patterns"); + // Hold on a swap route is refused. + let swap = base().replace( + "methods = [", + "decision = \"hold\"\npath_patterns = [\"/a\"]\nmethods = [", + ); + expect_invalid(&swap, "only valid on passthrough routes"); + } + + fn hold_text() -> String { + pt_base().replace( + "methods = [\"GET\"]\npaths = [\"/api/v10/channels/\", \"/api/v10/users/@me\"]", + "decision = \"hold\"\nmethods = [\"POST\"]\npath_patterns = [\"/api/v10/channels/*/messages\"]", + ) + } + + #[test] + fn hold_grant_on_path_patterns_loads_with_defaults() { + let cfg = load(&hold_text()).unwrap(); + assert_eq!(cfg.grants[0].decision, Decision::Hold); + assert!(cfg.grants[0].paths.is_empty()); + let p = cfg.passthrough.unwrap(); + assert_eq!(p.hold_secs, 120); + assert_eq!(p.held_body_max_bytes, 1024 * 1024); + assert_eq!(p.max_held_total, 32); + assert_eq!(p.max_held_per_identity, 4); + assert_eq!(p.cooldown_secs, 60); + assert!(cfg.approval.is_none() && cfg.notify.is_none()); + } + + fn second_route(host: &str, port: Option) -> String { + let port = port.map_or(String::new(), |p| format!("port = {p}\n")); + format!( + "{}\n[[route]]\nname = \"discord2\"\nhost = \"{host}\"\n{port}mode = \"passthrough\"\n\n[[grant]]\nidentity = \"muse-pilot\"\nroute = \"discord2\"\nmethods = [\"POST\"]\npaths = [\"/\"]\n", + hold_text() + ) + } + + #[test] + fn two_passthrough_routes_on_one_host_and_port_are_refused() { + // The reproduced bypass: `discord2` shares the authority and allows POST on `/`. + expect_invalid( + &second_route("discord.com", None), + "share one host and port", + ); + // The default port spelled out is the same authority. + expect_invalid( + &second_route("discord.com", Some(443)), + "share one host and port", + ); + } + + #[test] + fn host_spellings_of_one_authority_are_still_refused() { + // Uppercase and a trailing dot never reach the authority check: the host rule refuses + // them first. Either way the config does not load. + for host in ["DISCORD.com", "discord.com."] { + assert!(load(&second_route(host, None)).is_err(), "{host}"); + } + } + + #[test] + fn passthrough_routes_on_different_ports_or_hosts_load() { + assert!(load(&second_route("discord.com", Some(8443))).is_ok()); + assert!(load(&second_route("other.example.test", None)).is_ok()); + } + + #[test] + fn hold_grant_rejects_prefix_paths_alongside_patterns() { + let text = hold_text().replace("path_patterns =", "paths = [\"/api/\"]\npath_patterns ="); + expect_invalid(&text, "must not use prefix paths"); + } + + #[test] + fn rejects_bad_path_patterns() { + for bad in [ + "channels/*", + "/a//b", + "/a/", + "/", + "/a/b*", + "/a/*x", + "/a/../b", + "/a/./b", + "/a/%2f", + "/a b", + ] { + let text = hold_text().replace("/api/v10/channels/*/messages", bad); + expect_invalid(&text, "path_pattern"); + } + } + + #[test] + fn allow_grant_may_use_path_patterns_and_swap_may_not() { + let text = pt_base().replace( + "paths = [\"/api/v10/channels/\", \"/api/v10/users/@me\"]", + "path_patterns = [\"/api/v10/users/*\"]", + ); + assert!(load(&text).is_ok()); + let swap = base().replace( + "paths = [\"/\"]", + "paths = [\"/\"]\npath_patterns = [\"/a\"]", + ); + expect_invalid(&swap, "only valid on passthrough routes"); + } + + #[test] + fn rejects_grant_without_paths_or_patterns() { + let text = pt_base().replace( + "paths = [\"/api/v10/channels/\", \"/api/v10/users/@me\"]", + "", + ); + expect_invalid(&text, "paths must not be empty"); + } + + #[test] + fn rejects_hold_limits_out_of_range() { + for (k, v) in [ + ("hold_secs", "4"), + ("hold_secs", "601"), + ("held_body_max_bytes", "0"), + ("held_body_max_bytes", "8388609"), + ("max_held_total", "0"), + ("max_held_total", "1025"), + ("max_held_per_identity", "0"), + ("max_held_per_identity", "33"), + ("cooldown_secs", "3601"), + ] { + let text = hold_text().replace( + "public_authority = \"gate.example.test\"", + &format!("public_authority = \"gate.example.test\"\n{k} = {v}"), + ); + expect_invalid(&text, k); + } + let ok = hold_text().replace( + "public_authority = \"gate.example.test\"", + "public_authority = \"gate.example.test\"\nhold_secs = 5\ncooldown_secs = 0", + ); + assert!(load(&ok).is_ok()); + } + + fn approval_block() -> String { + format!( + "\n[approval]\nlisten = \"127.0.0.1:8444\"\nuser = \"owner\"\npassword_sha256 = \"{H64}\"\npublic_base_url = \"https://approve.example.test\"\n\n[notify]\nkind = \"ntfy\"\nbase_url = \"https://ntfy.example.test\"\ntopic_file = \"/etc/ap/topic\"\ntoken_file = \"/etc/ap/token\"\n" + ) + } + + #[test] + fn approval_and_notify_load() { + let cfg = load(&(hold_text() + &approval_block())).unwrap(); + let a = cfg.approval.unwrap(); + assert_eq!(a.realm, "auth-proxy approval"); + assert_eq!(cfg.notify.unwrap().kind, NotifyKind::Ntfy); + } + + #[test] + fn rejects_bad_approval_and_notify() { + for (from, to, needle) in [ + ( + "127.0.0.1:8444", + "127.0.0.1:8443", + "other than listen.proxy", + ), + ("127.0.0.1:8444", "0.0.0.0:8444", "loopback"), + ("user = \"owner\"", "user = \"a:b\"", "approval.user"), + (H64, "ABC", "password_sha256"), + ( + "https://approve.example.test", + "https://u:p@x.test", + "public_base_url", + ), + ( + "https://approve.example.test", + "https://x.test/?q=1", + "public_base_url", + ), + ( + "https://approve.example.test", + "ftp://x.test", + "public_base_url", + ), + ( + "https://ntfy.example.test", + "ntfy.example.test", + "notify.base_url", + ), + ("/etc/ap/topic", "topic", "topic_file"), + ("/etc/ap/token", "token", "token_file"), + ] { + let text = hold_text() + &approval_block().replacen(from, to, 1); + expect_invalid(&text, needle); + } + let text = hold_text() + &approval_block() + "extra = 1\n"; + expect_parse_error(&text); + } + + #[test] + fn approval_needs_a_passthrough_deployment() { + expect_invalid( + &(base() + &approval_block()), + "need a passthrough deployment", + ); } #[test] diff --git a/crates/ap-core/src/error.rs b/crates/ap-core/src/error.rs index b31f623..56de3b4 100644 --- a/crates/ap-core/src/error.rs +++ b/crates/ap-core/src/error.rs @@ -35,6 +35,19 @@ pub enum Code { ConnectFailed, ProbeParams, CallerKeyAmbiguous, + // Held passthrough routes (stage 2). + HumanDenied, + Expired, + ContentType, + ContentEncoding, + CredentialMissing, + TableFull, + IdentityCap, + Cooldown, + Superseded, + Shutdown, + DroppedOnReload, + AuditUnavailable, } impl Code { @@ -69,6 +82,18 @@ impl Code { Code::ConnectFailed => "upstream connection failed", Code::ProbeParams => "probe parameters are not allowed", Code::CallerKeyAmbiguous => "caller key given in more than one place", + Code::HumanDenied => "a person denied this request", + Code::Expired => "no decision arrived in time", + Code::ContentType => "content type is not allowed on this route", + Code::ContentEncoding => "content encoding is not allowed on this route", + Code::CredentialMissing => "no Authorization header on a held route", + Code::TableFull => "too many requests are waiting for approval", + Code::IdentityCap => "too many requests from this caller are waiting for approval", + Code::Cooldown => "this caller is in a cooldown after a denial", + Code::Superseded => "a newer identical request replaced this one", + Code::Shutdown => "the gate is shutting down", + Code::DroppedOnReload => "policy changed while the request was waiting", + Code::AuditUnavailable => "the audit log is unavailable", } } @@ -82,7 +107,10 @@ impl Code { | Code::FramingRefused | Code::AuthorizationDuplicate | Code::ProbeParams - | Code::CallerKeyAmbiguous => 400, + | Code::CallerKeyAmbiguous + | Code::ContentType + | Code::ContentEncoding + | Code::CredentialMissing => 400, Code::CallerRejected | Code::SurrogateMissing | Code::SurrogateMalformed @@ -93,16 +121,25 @@ impl Code { | Code::SurrogateWrongRoute | Code::PolicyEmpty | Code::PolicyDenied - | Code::NoGrant => 403, + | Code::NoGrant + | Code::HumanDenied => 403, Code::RouteUnknown => 404, Code::ConnectRefused => 405, + Code::Expired => 410, Code::BodyTooLarge => 413, Code::WebsocketUnsupported => 501, Code::UpstreamUnavailable => 502, Code::PolicyUnavailable | Code::BrokerUnavailable | Code::BodyReadTimeout - | Code::ConnectFailed => 503, + | Code::ConnectFailed + | Code::TableFull + | Code::IdentityCap + | Code::Cooldown + | Code::Superseded + | Code::Shutdown + | Code::DroppedOnReload + | Code::AuditUnavailable => 503, } } @@ -137,6 +174,18 @@ impl Code { Code::ConnectFailed => "connect_failed", Code::ProbeParams => "probe_params", Code::CallerKeyAmbiguous => "caller_key_ambiguous", + Code::HumanDenied => "human_denied", + Code::Expired => "expired", + Code::ContentType => "content_type", + Code::ContentEncoding => "content_encoding", + Code::CredentialMissing => "credential_missing", + Code::TableFull => "table_full", + Code::IdentityCap => "identity_cap", + Code::Cooldown => "cooldown", + Code::Superseded => "superseded", + Code::Shutdown => "shutdown", + Code::DroppedOnReload => "dropped_on_reload", + Code::AuditUnavailable => "audit_unavailable", } } } @@ -256,6 +305,18 @@ mod tests { Code::ConnectFailed, Code::ProbeParams, Code::CallerKeyAmbiguous, + Code::HumanDenied, + Code::Expired, + Code::ContentType, + Code::ContentEncoding, + Code::CredentialMissing, + Code::TableFull, + Code::IdentityCap, + Code::Cooldown, + Code::Superseded, + Code::Shutdown, + Code::DroppedOnReload, + Code::AuditUnavailable, ]; let mut seen = std::collections::HashSet::new(); for c in all { @@ -266,6 +327,6 @@ mod tests { ); assert!(seen.insert(s), "duplicate {s}"); } - assert_eq!(seen.len(), 28); + assert_eq!(seen.len(), 40); } } diff --git a/crates/ap-core/src/outcome.rs b/crates/ap-core/src/outcome.rs index 2eb181d..caad923 100644 --- a/crates/ap-core/src/outcome.rs +++ b/crates/ap-core/src/outcome.rs @@ -33,20 +33,31 @@ pub const DECISION_HEADER: &str = "x-ap-decision"; pub fn passthrough_outcome(code: Code) -> (u16, Decision) { match code { Code::CallerRejected => (401, Decision::Rejected), - Code::RouteUnknown | Code::NoGrant => (423, Decision::Denied), + Code::RouteUnknown | Code::NoGrant | Code::HumanDenied => (423, Decision::Denied), + Code::Expired => (410, Decision::Expired), Code::AbsoluteForm | Code::HostRejected | Code::PathAmbiguous | Code::FramingRefused | Code::AuthorizationDuplicate | Code::ProbeParams - | Code::CallerKeyAmbiguous => (400, Decision::Denied), + | Code::CallerKeyAmbiguous + | Code::ContentType + | Code::ContentEncoding + | Code::CredentialMissing => (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) - } + Code::PolicyUnavailable + | Code::BodyReadTimeout + | Code::ConnectFailed + | Code::TableFull + | Code::IdentityCap + | Code::Cooldown + | Code::Superseded + | Code::Shutdown + | Code::DroppedOnReload + | Code::AuditUnavailable => (503, Decision::Unavailable), // Not produced by the passthrough pipeline. Fail closed with a generic refusal. _ => (503, Decision::Unavailable), } @@ -70,7 +81,7 @@ mod tests { use crate::error::render; #[test] - fn stage1_rows_of_the_outcome_table() { + fn rows_of_the_outcome_table() { let rows = [ (Code::NoGrant, 423, "denied", "no_grant"), (Code::RouteUnknown, 423, "denied", "route_unknown"), @@ -113,6 +124,28 @@ mod tests { "denied", "caller_key_ambiguous", ), + (Code::HumanDenied, 423, "denied", "human_denied"), + (Code::Expired, 410, "expired", "expired"), + (Code::ContentType, 400, "denied", "content_type"), + (Code::ContentEncoding, 400, "denied", "content_encoding"), + (Code::CredentialMissing, 400, "denied", "credential_missing"), + (Code::TableFull, 503, "unavailable", "table_full"), + (Code::IdentityCap, 503, "unavailable", "identity_cap"), + (Code::Cooldown, 503, "unavailable", "cooldown"), + (Code::Superseded, 503, "unavailable", "superseded"), + (Code::Shutdown, 503, "unavailable", "shutdown"), + ( + Code::DroppedOnReload, + 503, + "unavailable", + "dropped_on_reload", + ), + ( + Code::AuditUnavailable, + 503, + "unavailable", + "audit_unavailable", + ), ]; for (code, status, decision, name) in rows { let (s, d, body) = render_passthrough(code); diff --git a/crates/ap-core/src/policy.rs b/crates/ap-core/src/policy.rs index 7d256bb..a94e0f4 100644 --- a/crates/ap-core/src/policy.rs +++ b/crates/ap-core/src/policy.rs @@ -3,10 +3,81 @@ //! The snapshot answers one question: may this identity make this request on this route? //! Reloading is the caller's job (ap-proxy stats the file and swaps in a new snapshot). -use crate::config::{Config, Grant, Route}; +use crate::config::{Config, Decision, Grant, Route}; use crate::error::Code; use std::collections::HashMap; +/// What a matching grant does with a request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + Allow, + Hold, +} + +/// Whole-path segment match. A `*` pattern segment matches exactly one non-empty path segment; +/// every other segment must be equal. The segment counts must match, so a trailing `/` or a +/// longer path never matches. +fn pattern_matches(pattern: &str, path: &str) -> bool { + let (Some(pat), Some(path)) = (pattern.strip_prefix('/'), path.strip_prefix('/')) else { + return false; + }; + let mut p = pat.split('/'); + let mut s = path.split('/'); + loop { + match (p.next(), s.next()) { + (None, None) => return true, + (Some(a), Some(b)) => { + if b.is_empty() || (a != "*" && a != b) { + return false; + } + } + _ => return false, + } + } +} + +/// True when some path that starts with `prefix` also matches `pattern`, or would match it +/// once a trailing `/` is dropped. Conservative: it answers yes whenever a doubt remains. +pub(crate) fn prefix_overlaps_pattern(prefix: &str, pattern: &str) -> bool { + let (Some(pre), Some(pat)) = (prefix.strip_prefix('/'), pattern.strip_prefix('/')) else { + return true; + }; + let psegs: Vec<&str> = pat.split('/').collect(); + let segs: Vec<&str> = pre.split('/').collect(); + let (last, whole) = segs.split_last().expect("split yields one item"); + for (i, s) in whole.iter().enumerate() { + match psegs.get(i) { + Some(&p) if p == "*" && !s.is_empty() || p == *s => {} + _ => return false, + } + } + match psegs.get(whole.len()) { + Some(&p) => p == "*" || p.starts_with(last), + // The prefix names every segment of the pattern and ends in `/`: the trailing-slash + // spelling of a held resource. + None => last.is_empty(), + } +} + +/// True when one path could match both patterns, trailing `/` ignored. +pub(crate) fn patterns_overlap(a: &str, b: &str) -> bool { + let (Some(a), Some(b)) = (a.strip_prefix('/'), b.strip_prefix('/')) else { + return true; + }; + let trim = |s: &'_ str| -> Vec { + let mut v: Vec = s.split('/').map(str::to_string).collect(); + if v.len() > 1 && v.last().is_some_and(String::is_empty) { + v.pop(); + } + v + }; + let (x, y) = (trim(a), trim(b)); + x.len() == y.len() + && x.iter() + .zip(&y) + .all(|(p, q)| p == q || p == "*" || q == "*") +} + #[derive(Debug, Clone)] pub struct Snapshot { routes: HashMap, @@ -36,6 +107,51 @@ impl Snapshot { self.routes.get(name) } + /// Passthrough decision: `Hold` when a hold grant matches (hold beats allow), `Allow` when + /// only allow grants match. A grant matches on a `paths` prefix or a `path_patterns` entry + /// matched against the whole path. Errors follow `evaluate`: `policy_empty` without grants, + /// `policy_denied` when none matches. `evaluate` itself is unchanged. + pub fn evaluate_verdict( + &self, + identity: &str, + route: &str, + method: &str, + path: &str, + ) -> Result { + let grants = match self.grants.get(identity) { + Some(g) if !g.is_empty() => g, + _ => return Err(Code::PolicyEmpty), + }; + let mut verdict = None; + // The trailing-slash spelling of a held resource is the same resource. A hold pattern + // matches whole paths only, so it never claims `/x/` and an allow prefix could carry it + // unheld: it is denied instead, whatever allow grants say. + let mut hold_shadow = false; + for g in grants { + if g.route != route || !g.methods.iter().any(|m| m == method) { + continue; + } + if g.decision == Decision::Hold && path.len() > 1 { + if let Some(bare) = path.strip_suffix('/') { + hold_shadow |= g.path_patterns.iter().any(|p| pattern_matches(p, bare)); + } + } + let hit = g.paths.iter().any(|p| path.starts_with(p.as_str())) + || g.path_patterns.iter().any(|p| pattern_matches(p, path)); + if !hit { + continue; + } + match g.decision { + Decision::Hold => return Ok(Verdict::Hold), + Decision::Allow => verdict = Some(Verdict::Allow), + } + } + if hold_shadow { + return Err(Code::PolicyDenied); + } + verdict.ok_or(Code::PolicyDenied) + } + /// Decide whether `identity` may send `method` `path` to `route`. /// /// `path` is route-relative and already passed `canon::path_ambiguous`. @@ -188,6 +304,157 @@ mod tests { ); } + fn pt(grants: &str) -> Snapshot { + let text = format!( + "version = 1\n[listen]\nproxy = \"127.0.0.1:8443\"\n[passthrough]\npublic_authority = \"gate.example.test\"\n[[identity]]\nname = \"muse\"\ncaller_key_sha256 = \"{IDLE_KEY}\"\n[[route]]\nname = \"discord\"\nhost = \"discord.com\"\nmode = \"passthrough\"\n{grants}" + ); + Snapshot::from_config(&load(&text).expect("valid")) + } + + const HOLD: &str = "[[grant]]\nidentity = \"muse\"\nroute = \"discord\"\ndecision = \"hold\"\nmethods = [\"POST\"]\npath_patterns = [\"/api/v10/channels/*/messages\"]\n"; + const ALLOW: &str = "[[grant]]\nidentity = \"muse\"\nroute = \"discord\"\nmethods = [\"GET\", \"POST\"]\npaths = [\"/api/v10/channels/\"]\n"; + + #[test] + fn verdict_hold_matches_whole_path_only() { + let s = pt(HOLD); + let v = |m, p| s.evaluate_verdict("muse", "discord", m, p); + assert_eq!(v("POST", "/api/v10/channels/1/messages"), Ok(Verdict::Hold)); + assert_eq!( + v("POST", "/api/v10/channels/1/messages/2/reactions"), + Err(Code::PolicyDenied) + ); + assert_eq!( + v("POST", "/api/v10/channels/1/messages/"), + Err(Code::PolicyDenied) + ); + assert_eq!( + v("POST", "/api/v10/channels//messages"), + Err(Code::PolicyDenied) + ); + assert_eq!( + v("POST", "/api/v10/channels/1/2/messages"), + Err(Code::PolicyDenied) + ); + assert_eq!( + v("GET", "/api/v10/channels/1/messages"), + Err(Code::PolicyDenied) + ); + assert_eq!( + s.evaluate_verdict("muse", "other", "POST", "/api/v10/channels/1/messages"), + Err(Code::PolicyDenied) + ); + assert_eq!( + s.evaluate_verdict("nobody", "discord", "POST", "/api/v10/channels/1/messages"), + Err(Code::PolicyEmpty) + ); + } + + /// A snapshot that skips the loader's overlap refusal, to test the engine on its own: the + /// allow grant is loaded for GET, then widened to POST. + fn pt_overlapping(grants: &str) -> Snapshot { + let text = format!( + "version = 1\n[listen]\nproxy = \"127.0.0.1:8443\"\n[passthrough]\npublic_authority = \"gate.example.test\"\n[[identity]]\nname = \"muse\"\ncaller_key_sha256 = \"{IDLE_KEY}\"\n[[route]]\nname = \"discord\"\nhost = \"discord.com\"\nmode = \"passthrough\"\n{grants}" + ); + let mut cfg = load(&text).expect("valid"); + for g in &mut cfg.grants { + if g.decision == Decision::Allow { + g.methods.push("POST".into()); + } + } + Snapshot::from_config(&cfg) + } + + #[test] + fn verdict_hold_beats_allow_in_either_grant_order() { + let path = "/api/v10/channels/1/messages"; + let allow_get = ALLOW.replace("[\"GET\", \"POST\"]", "[\"GET\"]"); + for text in [format!("{allow_get}{HOLD}"), format!("{HOLD}{allow_get}")] { + let s = pt_overlapping(&text); + // The allow grant now covers POST too: hold still wins, in either order. + assert_eq!( + s.evaluate_verdict("muse", "discord", "POST", path), + Ok(Verdict::Hold) + ); + assert_eq!( + s.evaluate_verdict("muse", "discord", "GET", path), + Ok(Verdict::Allow) + ); + // The trailing-slash spelling is the same resource: never allowed unheld. + assert_eq!( + s.evaluate_verdict("muse", "discord", "POST", &format!("{path}/")), + Err(Code::PolicyDenied) + ); + assert_eq!( + s.evaluate_verdict( + "muse", + "discord", + "POST", + "/api/v10/channels/1/messages/2/reactions" + ), + Ok(Verdict::Allow) + ); + } + } + + #[test] + fn loader_refuses_an_allow_grant_that_overlaps_a_hold_pattern() { + let try_load = |grants: &str| { + let text = format!( + "version = 1\n[listen]\nproxy = \"127.0.0.1:8443\"\n[passthrough]\npublic_authority = \"gate.example.test\"\n[[identity]]\nname = \"muse\"\ncaller_key_sha256 = \"{IDLE_KEY}\"\n[[route]]\nname = \"discord\"\nhost = \"discord.com\"\nmode = \"passthrough\"\n{grants}" + ); + load(&text) + }; + let allow = |methods: &str, key: &str, val: &str| { + format!( + "[[grant]]\nidentity = \"muse\"\nroute = \"discord\"\nmethods = {methods}\n{key} = [\"{val}\"]\n" + ) + }; + // Overlapping: same method, prefix or pattern reaching the hold pattern, or its + // trailing-slash spelling. + for (key, val) in [ + ("paths", "/api/v10/channels/"), + ("paths", "/"), + ("paths", "/api"), + ("paths", "/api/v10/channels/1/mess"), + ("paths", "/api/v10/channels/1/messages"), + ("paths", "/api/v10/channels/1/messages/"), + ("path_patterns", "/api/v10/channels/*/messages"), + ("path_patterns", "/api/v10/channels/7/*"), + ("path_patterns", "/api/v10/*/*/messages"), + ] { + let err = try_load(&format!("{HOLD}{}", allow("[\"POST\"]", key, val))) + .expect_err(&format!("{key} {val} must be refused")); + assert!(err.to_string().contains("overlaps hold pattern"), "{err}"); + } + // Disjoint: another method, another route prefix, a longer or different path. + for (m, key, val) in [ + ("[\"GET\"]", "paths", "/api/v10/channels/"), + ("[\"POST\"]", "paths", "/api/v10/guilds/"), + ("[\"POST\"]", "paths", "/api/v10/channels/1/messages/2/"), + ("[\"POST\"]", "paths", "/api/v11/"), + ("[\"POST\"]", "path_patterns", "/api/v10/channels/*"), + ("[\"POST\"]", "path_patterns", "/api/v10/channels/*/pins"), + ] { + try_load(&format!("{HOLD}{}", allow(m, key, val))) + .unwrap_or_else(|e| panic!("{m} {key} {val} must load: {e}")); + } + } + + #[test] + fn evaluate_ignores_path_patterns() { + let s = pt(HOLD); + assert_eq!( + s.evaluate( + "muse", + "discord", + "POST", + "/api/v10/channels/1/messages", + &[] + ), + Err(Code::PolicyDenied) + ); + } + #[test] fn route_lookup_returns_configured_route() { let s = snapshot(); diff --git a/crates/ap-core/tests/canon_differential.rs b/crates/ap-core/tests/canon_differential.rs index 7247dd2..205d971 100644 --- a/crates/ap-core/tests/canon_differential.rs +++ b/crates/ap-core/tests/canon_differential.rs @@ -6,6 +6,7 @@ //! is fixed, so a failure reproduces; the same invariants run under cargo-fuzz for open-ended input. mod common; +use ap_core::canon::path_ambiguous_passthrough; use common::invariants::*; /// xorshift64*: deterministic, no dependency. @@ -298,3 +299,100 @@ fn generated_headers_hold_the_invariants() { check_headers(&pairs, "x-ap-caller-key"); } } + +/// The oracle closes the family: for requests aimed at every hold pattern, in every position and +/// spelling the generator knows, a request whose RFC 3986 same-resource form is held is never +/// forwarded unheld (see `check_gate`). The run must reach all three outcomes, or it proves +/// nothing. +#[test] +fn generated_hold_probes_are_never_forwarded_unheld() { + let mut r = Rng(SEED ^ 0x401D); + let (mut held, mut refused, mut denied, mut oracle_hits) = (0, 0, 0, 0); + for _ in 0..60_000 { + let (method, path) = hold_probe(&mut |n| r.below(n)); + check_gate(method, &path); + if oracle_matches_hold(&path) { + oracle_hits += 1; + match gate_shipped(method, &path) { + Gate::Held => held += 1, + Gate::Refused => refused += 1, + Gate::Denied => denied += 1, + Gate::Allowed => unreachable!("check_gate asserted"), + } + } + } + assert!(oracle_hits > 5_000, "oracle matched only {oracle_hits}"); + assert!(held > 500, "never held a plain probe: {held}"); + assert!(refused > 500, "never refused an encoded probe: {refused}"); + assert!(denied > 50, "never denied a trailing-slash probe: {denied}"); +} + +/// Named regression forms, one per pattern position and spelling, for the hold path and the +/// allow path. Every one is refused as ambiguous, so none reaches an allow prefix. +#[test] +fn unreserved_escapes_are_refused_in_every_pattern_position() { + let refused = [ + // literal segment, middle of the pattern + "/hold/1/%6Dessages", + "/hold/1/%6dessages", + "/hold/1/%4Dessages", + "/hold/1/mess%61ges", + "/hold/1/mess%41ges", + // first segment (literal) + "/%68old/1/messages", + "/%48old/1/messages", + // last segment + "/hold/1/message%73", + "/hold/1/message%53", + // wildcard segment + "/hold/%31/messages", + "/hold/%4D/messages", + "/hold/a%2Db/messages", + "/hold/a%2db/messages", + "/hold/a%2Eb/messages", + "/hold/a%2eb/messages", + "/hold/%7E/messages", + "/hold/%7e/messages", + "/hold/a%5Fb/messages", + // wildcard in first position, literal last + "/%4Dx/pin", + "/x/%70in", + "/x/pi%6e", + // layered + "/hold/1/%256Dessages", + "/hold/1/%256dessages", + "/hold/1/%25256Dessages", + "/%2568old/1/messages", + "/hold/%25%32%44/messages", + "/hold/1/%2%36Dessages", + // allow path + "/other/x/%6Dessages", + "/other/x/%4D", + "/other/x/a%2Db", + "/other/x/a%7Eb", + ]; + for p in refused { + for m in ["POST", "PUT", "GET"] { + assert!(path_ambiguous_passthrough(p), "{p:?} must be refused"); + assert_eq!(gate_shipped(m, p), Gate::Refused, "{m} {p:?}"); + check_gate(m, p); + } + } + // The plain spellings still reach their verdicts. + assert_eq!(gate_shipped("POST", "/hold/1/messages"), Gate::Held); + assert_eq!(gate_shipped("PUT", "/x/pin"), Gate::Held); + assert_eq!(gate_shipped("POST", "/other/x/anything"), Gate::Allowed); + assert_eq!(gate_shipped("GET", "/hold/1/messages"), Gate::Allowed); + // The trailing-slash spelling is the same resource and is never allowed unheld. + for p in [ + "/hold/1/messages/", + "/x/pin/", + "/api/v10/channels/1/messages/", + ] { + assert_eq!(gate_shipped("POST", p), Gate::Denied, "{p:?}"); + } + // Escapes of reserved, non-unreserved bytes that the gate does not read as separators still + // pass: `%20` names no unreserved character. + assert!(!path_ambiguous_passthrough("/other/x/a%20b")); + assert!(!path_ambiguous_passthrough("/other/x/a%3Bb")); +} diff --git a/crates/ap-core/tests/canon_regression.rs b/crates/ap-core/tests/canon_regression.rs index d527556..d1f476d 100644 --- a/crates/ap-core/tests/canon_regression.rs +++ b/crates/ap-core/tests/canon_regression.rs @@ -26,6 +26,90 @@ fn ambiguous_all(class: &str, paths: &[&str]) { } } +#[test] +fn percent_encoded_unreserved_characters_are_refused() { + // RFC 3986 2.3: `%41` and `A` are the same resource. Policy matches the raw bytes and the + // forwarder sends them, so the spelling must not be a choice the caller gets to make. + for p in [ + "/v1/%41", + "/v1/%61", + "/v1/%30", + "/v1/%39", + "/v1/%2D", + "/v1/%2d", + "/v1/%5F", + "/v1/%5f", + "/v1/%7E", + "/v1/%7e", + "/v1/%6D", + "/v1/%6d", + "/v1/%4D", + "/%761/x", + "/v1/x%79", + "/v1/%2541", + "/v1/%25256D", + "/v1/%2%36D", + ] { + assert!( + path_ambiguous_passthrough(p), + "escaped unreserved: {p:?} must be refused" + ); + // The sidecar pipeline has no hold verdict and keeps accepting these (matrix row C1-3). + assert!(!path_ambiguous(p), "{p:?}"); + } + // Escapes of bytes that are not unreserved stay data and pass. + for p in [ + "/v1/%20", + "/v1/%21", + "/v1/%3B", + "/v1/%40", + "/v1/100%25", + "/v1/%25", + ] { + assert!(!path_ambiguous_passthrough(p), "{p:?} must pass"); + } +} + +#[test] +fn caller_key_repeated_in_a_path_or_query_is_found_in_every_spelling() { + use ap_core::canon::echoes_caller_key; + let key = format!("apk_{}", "ab12".repeat(16)); + let enc = |s: &str| -> String { s.bytes().map(|b| format!("%{b:02x}")).collect() }; + let upper = key.to_uppercase(); + let other = format!("apk_{}", "cd34".repeat(16)); + let forms = [ + format!("/hold/{key}"), + format!("/hold/{upper}"), + format!("/hold/{}", &key["apk_".len()..]), + format!("/hold/{}", enc(&key)), + format!("/hold/{}", enc(&key).to_uppercase()), + format!("/hold/%61pk_{}", &key["apk_".len()..]), + format!("/hold/{}", enc(&enc(&key))), + format!("/hold/{}", enc(&enc(&enc(&key)))), + format!("/hold/x{key}y"), + format!("a={key}"), + format!("a=b&c={}", enc(&key)), + format!("/hold/{other}"), + format!("/hold/{}", enc(&other)), + ]; + for f in &forms { + assert!(echoes_caller_key(f, &key), "{f:?} must be found"); + } + for f in [ + "/hold/1/messages", + "/hold/apk_", + "/hold/apk_short", + "a=b&c=d", + "/hold/ab12ab12", + "/hold/%41%42%20", + ] { + assert!(!echoes_caller_key(f, &key), "{f:?} must not be found"); + } + // Still decodable after the layer limit: fail closed. + let deep = format!("/%{}41", "25".repeat(12)); + assert!(echoes_caller_key(&deep, &key)); +} + #[test] fn path_encoding_classes_are_refused() { ambiguous_all( diff --git a/crates/ap-core/tests/common/invariants.rs b/crates/ap-core/tests/common/invariants.rs index cfd4b1b..f0b831d 100644 --- a/crates/ap-core/tests/common/invariants.rs +++ b/crates/ap-core/tests/common/invariants.rs @@ -11,7 +11,8 @@ use ap_core::canon::{ caller_key_from_header, canonical_host, check_origin_form, framing_refused, is_caller_key, - parse_ap_path, parse_route_path, path_ambiguous, surrogate_from_headers, + parse_ap_path, parse_route_path, path_ambiguous, path_ambiguous_passthrough, + surrogate_from_headers, }; use ap_core::error::Code; use http::{HeaderMap, HeaderName, HeaderValue, Uri, Version}; @@ -83,6 +84,8 @@ pub fn check_path_against_parsers(p: &str) { /// Everything about a request path that must hold for any string. pub fn check_path(p: &str) { + check_gate("POST", p); + check_gate("PUT", p); check_ap_path(p); check_decode_oracle(p); check_path_against_parsers(p); @@ -223,15 +226,23 @@ pub fn check_origin(target: &str, hosts: &[Vec], http2: bool, expected: &str /// `path_ambiguous` must refuse; the reverse is not asserted because the production rule also /// refuses bytes the forwarder would re-encode, `%u` escapes and invalid UTF-8. pub fn check_decode_oracle(p: &str) { - if oracle_must_refuse(p) { + if oracle_must_refuse(p, false) { assert!( path_ambiguous(p), "decode oracle demands refusal but path_ambiguous accepted {p:?}" ); } + if oracle_must_refuse(p, true) { + assert!( + path_ambiguous_passthrough(p), + "decode oracle demands refusal but path_ambiguous_passthrough accepted {p:?}" + ); + } } -fn oracle_must_refuse(p: &str) -> bool { +/// `strict` adds the passthrough rule: an unreserved byte spelled as an escape names the same +/// resource as its plain form (RFC 3986 6.2.2.2), so match form and forward form would differ. +fn oracle_must_refuse(p: &str, strict: bool) -> bool { // (byte, depth that produced it; 0 = literal) let mut layer: Vec<(u8, usize)> = p.bytes().map(|b| (b, 0)).collect(); for depth in 1..=4 { @@ -251,7 +262,12 @@ fn oracle_must_refuse(p: &str) -> bool { .flatten(); match esc { Some(b) => { - if matches!(b, 0 | b'.' | b'/' | b'\\') || b < 0x20 || b == 0x7f { + if matches!(b, 0 | b'.' | b'/' | b'\\') + || b < 0x20 + || b == 0x7f + || (strict + && (b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'~'))) + { return true; } if b == b';' && depth >= 2 { @@ -287,3 +303,236 @@ fn has_dot_segment(layer: &[(u8, usize)]) -> bool { .skip(1) .any(|seg| matches!(seg.split(';').next(), Some(".") | Some(".."))) } + +// --------------------------------------------------------------------------------------------- +// Hold-gate oracle +// +// An RFC 3986 normaliser that shares no code with `canon.rs` or `policy.rs` computes the "same +// resource" form of a request path. If that form matches a hold pattern, the gate (the path +// canonicalization refusal, then the policy verdict) must hold the request or refuse it. It must +// never forward it unheld. Two policies are checked: the shipped shape, where the loader keeps +// allow grants disjoint from hold patterns, and an engine-only shape where an allow prefix `/` +// covers everything, which isolates what the matcher and canonicalization guarantee by +// themselves. +// --------------------------------------------------------------------------------------------- + +use ap_core::config::{load, Decision}; +use ap_core::policy::{Snapshot, Verdict}; +use std::sync::OnceLock; + +const HOLD_PATTERNS: &[&str] = &[ + "/hold/*/messages", + "/api/v10/channels/*/messages", + "/*/pin", + "/hold/pin/last", + "/webhooks/*/*", +]; + +const GATE_KEY: &str = "1111111111111111111111111111111111111111111111111111111111111111"; + +fn gate_policy_text() -> String { + let pats: Vec = HOLD_PATTERNS.iter().map(|p| format!("\"{p}\"")).collect(); + format!( + "version = 1\n[listen]\nproxy = \"127.0.0.1:8443\"\n[passthrough]\npublic_authority = \"gate.example.test\"\n\ + [[identity]]\nname = \"muse\"\ncaller_key_sha256 = \"{GATE_KEY}\"\n\ + [[route]]\nname = \"discord\"\nhost = \"discord.com\"\nmode = \"passthrough\"\n\ + [[grant]]\nidentity = \"muse\"\nroute = \"discord\"\ndecision = \"hold\"\nmethods = [\"POST\", \"PUT\"]\npath_patterns = [{}]\n\ + [[grant]]\nidentity = \"muse\"\nroute = \"discord\"\nmethods = [\"GET\"]\npaths = [\"/\"]\n\ + [[grant]]\nidentity = \"muse\"\nroute = \"discord\"\nmethods = [\"POST\", \"PUT\"]\npaths = [\"/other/x/\"]\n", + pats.join(", ") + ) +} + +/// (shipped shape, engine-only shape with an allow prefix `/` over the held methods). +fn gate_policies() -> &'static (Snapshot, Snapshot) { + static P: OnceLock<(Snapshot, Snapshot)> = OnceLock::new(); + P.get_or_init(|| { + let mut cfg = load(&gate_policy_text()).expect("gate policy loads"); + let shipped = Snapshot::from_config(&cfg); + for g in cfg + .grants + .iter_mut() + .filter(|g| g.decision == Decision::Allow) + { + g.methods = vec!["GET".into(), "POST".into(), "PUT".into()]; + g.paths = vec!["/".into()]; + } + (shipped, Snapshot::from_config(&cfg)) + }) +} + +#[derive(Debug, PartialEq, Eq)] +pub enum Gate { + Refused, + Held, + Allowed, + Denied, +} + +fn gate(snap: &Snapshot, method: &str, path: &str) -> Gate { + if path_ambiguous_passthrough(path) { + return Gate::Refused; + } + match snap.evaluate_verdict("muse", "discord", method, path) { + Ok(Verdict::Hold) => Gate::Held, + Ok(Verdict::Allow) => Gate::Allowed, + Err(_) => Gate::Denied, + } +} + +/// RFC 3986 normaliser, written from the RFC alone: decode escapes of unreserved characters +/// (and `%25`, so layered spellings collapse the way a double-decoding hop would read them) to +/// a fixed point, upper-case the hex of the escapes that remain, remove dot segments, collapse +/// empty segments and drop a trailing slash. Returns the path segments. +pub fn rfc3986_segments(path: &str) -> Vec { + fn escape_at(b: &[u8], i: usize) -> Option { + let h = |j: usize| b.get(j).and_then(|c| (*c as char).to_digit(16)); + if b.get(i) != Some(&b'%') { + return None; + } + Some((h(i + 1)? * 16 + h(i + 2)?) as u8) + } + let mut cur: Vec = path.bytes().collect(); + for _ in 0..16 { + let mut out = Vec::with_capacity(cur.len()); + let mut i = 0; + let mut changed = false; + while i < cur.len() { + match escape_at(&cur, i) { + Some(b) + if b.is_ascii_alphanumeric() + || matches!(b, b'-' | b'.' | b'_' | b'~' | b'%') => + { + out.push(b); + i += 3; + changed = true; + } + _ => { + out.push(cur[i]); + i += 1; + } + } + } + cur = out; + if !changed { + break; + } + } + // Upper-case the hex digits of the escapes that are left. + let mut i = 0; + while i < cur.len() { + if escape_at(&cur, i).is_some() { + cur[i + 1] = cur[i + 1].to_ascii_uppercase(); + cur[i + 2] = cur[i + 2].to_ascii_uppercase(); + i += 3; + } else { + i += 1; + } + } + let text = String::from_utf8_lossy(&cur).into_owned(); + // remove_dot_segments over the segments, empties collapsed. + let mut out: Vec = Vec::new(); + for seg in text.split('/') { + match seg { + "" | "." => {} + ".." => { + out.pop(); + } + s => out.push(s.to_string()), + } + } + out +} + +/// True when the normalised form of `path` is a whole-path match for one of the hold patterns. +pub fn oracle_matches_hold(path: &str) -> bool { + let segs = rfc3986_segments(path); + HOLD_PATTERNS.iter().any(|pat| { + let ps: Vec<&str> = pat.trim_start_matches('/').split('/').collect(); + ps.len() == segs.len() && ps.iter().zip(&segs).all(|(p, s)| *p == "*" || p == s) + }) +} + +/// The verdict of the shipped-shape policy, for tests that count outcomes. +pub fn gate_shipped(method: &str, path: &str) -> Gate { + gate(&gate_policies().0, method, path) +} + +/// A request whose same-resource form is held must be held or refused, under both policies. +pub fn check_gate(method: &str, path: &str) { + if !path.starts_with('/') || !oracle_matches_hold(path) { + return; + } + let (shipped, engine_only) = gate_policies(); + for (name, snap) in [("shipped", shipped), ("engine-only", engine_only)] { + let g = gate(snap, method, path); + assert_ne!( + g, + Gate::Allowed, + "{name} policy forwards {method} {path:?} unheld (normalised: {:?})", + rfc3986_segments(path) + ); + } +} + +/// Build a request aimed at a hold pattern from a stream of choices. `pick(n)` returns a value +/// below `n`. Used by the deterministic test (seeded generator) and by the fuzz target (input +/// bytes), so both explore the same space: every pattern, literal and wildcard segments, the +/// first and last position, each unreserved character written as an escape in either hex case, +/// layered escapes, dot and empty segments, and a trailing slash. +pub fn hold_probe(pick: &mut dyn FnMut(usize) -> usize) -> (&'static str, String) { + const FILL: &[&str] = &["1", "42", "abc", "Z9", "x-y", "a.b", "a_b", "t~", "m", "M"]; + let method = ["POST", "PUT"][pick(2)]; + let pat = HOLD_PATTERNS[pick(HOLD_PATTERNS.len())]; + // One probe in three is spelled plainly, so the run also reaches the `Held` outcome. + let plain = pick(3) == 0; + let mut path = String::new(); + for seg in pat.trim_start_matches('/').split('/') { + path.push_str(if plain { + "/" + } else { + ["/", "/", "/", "//", "/./", "/x/../"][pick(6)] + }); + let text = if seg == "*" { + FILL[pick(FILL.len())] + } else { + seg + }; + for ch in text.chars() { + // 0..=3: plain; otherwise an escape in one of four spellings. + match if plain { 0 } else { pick(8) } { + 0..=3 => path.push(ch), + n => { + let hex = if n % 2 == 0 { + format!("{:02X}", ch as u32) + } else { + format!("{:02x}", ch as u32) + }; + let esc = format!("%{hex}"); + match pick(6) { + 0 => path.push_str(&esc.replace('%', "%25")), + 1 => path.push_str(&esc.replace('%', "%2525")), + 2 => path.push_str(&format!("%{:02x}{}", b'%', hex)), + _ => path.push_str(&esc), + } + } + } + } + } + if pick(4) == 0 { + path.push('/'); + } + (method, path) +} + +/// Fuzz entry: shape the input bytes into a hold probe and run the oracle on it. +pub fn check_gate_bytes(data: &[u8]) { + let mut i = 0; + let mut pick = |n: usize| { + let b = data.get(i).copied().unwrap_or(0) as usize; + i += 1; + b % n + }; + let (method, path) = hold_probe(&mut pick); + check_gate(method, &path); +} diff --git a/crates/ap-proxy/Cargo.toml b/crates/ap-proxy/Cargo.toml index d749b05..f9d818c 100644 --- a/crates/ap-proxy/Cargo.toml +++ b/crates/ap-proxy/Cargo.toml @@ -16,9 +16,12 @@ path = "src/main.rs" ap-core = { workspace = true } ap-broker = { workspace = true } axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] } +base64 = "0.22" bytes = "1" ed25519-dalek = "2" futures-util = "0.3" +getrandom = "0.2" +hmac = "0.12" http = "1" libc = "0.2" hyper = { version = "1", features = ["server", "http1"] } @@ -26,8 +29,9 @@ hyper-util = { version = "0.1", features = ["tokio", "service"] } reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "http2", "stream"] } serde = { version = "1", features = ["derive"] } serde_json = "1" +sha2 = "0.10" subtle = "2" -tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "io-util"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "io-util", "signal"] } [features] default = [] @@ -48,11 +52,10 @@ path = "tests/matrix_passthrough.rs" required-features = ["matrix-upstream"] [dev-dependencies] -base64 = "0.22" h2 = "0.4" -getrandom = "0.2" http-body-util = "0.1" rcgen = "0.13" rustls = { version = "0.23", default-features = false, features = ["std", "tls12", "ring"] } +tokio = { version = "1", features = ["test-util"] } tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } tower = { version = "0.5", features = ["util"] } diff --git a/crates/ap-proxy/src/approval/auth.rs b/crates/ap-proxy/src/approval/auth.rs new file mode 100644 index 0000000..4608269 --- /dev/null +++ b/crates/ap-proxy/src/approval/auth.rs @@ -0,0 +1,159 @@ +//! The approver credential: HTTP Basic, one user, a stored sha256 of the password (design 3.6). +//! +//! The credential is unrelated to any caller key and is checked only on the approval listener. +//! The password is compared through its sha256 in constant time, so neither its length nor a +//! matching prefix shows in the response time. + +use std::fmt; + +use ap_core::config::Approval; +use base64::engine::general_purpose::STANDARD; +use base64::Engine; +use http::{header, HeaderMap}; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; + +/// The one approver, as the config names it. +pub struct Credentials { + user: String, + password_sha256: String, +} + +impl fmt::Debug for Credentials { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Credentials").finish_non_exhaustive() + } +} + +impl Credentials { + pub fn new(cfg: &Approval) -> Credentials { + Credentials { + user: cfg.user.clone(), + password_sha256: cfg.password_sha256.clone(), + } + } + + /// The approver's user name when `headers` carry exactly one `Authorization: Basic` header + /// with the right user and password. + pub fn authenticate(&self, headers: &HeaderMap) -> Option { + let mut values = headers.get_all(header::AUTHORIZATION).iter(); + let value = values.next()?; + if values.next().is_some() { + return None; + } + let (user, password) = parse_basic(value.as_bytes())?; + self.matches(&user, &password).then(|| self.user.clone()) + } + + fn matches(&self, user: &str, password: &str) -> bool { + let presented = hex_sha256(password.as_bytes()); + let user_ok = user.as_bytes().ct_eq(self.user.as_bytes()); + let pass_ok = presented.as_bytes().ct_eq(self.password_sha256.as_bytes()); + bool::from(user_ok & pass_ok) + } +} + +/// Split `Basic base64(user:password)`. The scheme name is case-insensitive. +pub fn parse_basic(value: &[u8]) -> Option<(String, String)> { + let text = std::str::from_utf8(value).ok()?; + let (scheme, rest) = text.split_once(' ')?; + if !scheme.eq_ignore_ascii_case("basic") { + return None; + } + let raw = STANDARD.decode(rest.trim_matches(' ')).ok()?; + let raw = String::from_utf8(raw).ok()?; + let (user, password) = raw.split_once(':')?; + Some((user.to_string(), password.to_string())) +} + +fn hex_sha256(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let digest = Sha256::digest(bytes); + let mut s = String::with_capacity(64); + for b in digest { + s.push(DIGITS[(b >> 4) as usize] as char); + s.push(DIGITS[(b & 0x0f) as usize] as char); + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + use http::HeaderValue; + + pub(crate) fn basic(user: &str, password: &str) -> HeaderValue { + HeaderValue::from_str(&format!( + "Basic {}", + STANDARD.encode(format!("{user}:{password}")) + )) + .unwrap() + } + + fn creds() -> Credentials { + Credentials { + user: "owner".into(), + password_sha256: hex_sha256(b"pw-0001"), + } + } + + fn headers(v: &[HeaderValue]) -> HeaderMap { + let mut h = HeaderMap::new(); + for x in v { + h.append(header::AUTHORIZATION, x.clone()); + } + h + } + + #[test] + fn right_user_and_password_authenticate() { + let c = creds(); + assert_eq!( + c.authenticate(&headers(&[basic("owner", "pw-0001")])), + Some("owner".to_string()) + ); + } + + #[test] + fn wrong_user_or_password_or_shape_is_refused() { + let c = creds(); + for h in [ + headers(&[]), + headers(&[basic("owner", "pw-0002")]), + headers(&[basic("other", "pw-0001")]), + headers(&[basic("owner", "")]), + headers(&[HeaderValue::from_static("Bearer pw-0001")]), + headers(&[HeaderValue::from_static("Basic !!!not-base64")]), + headers(&[HeaderValue::from_static("Basic b3duZXI=")]), + // Two Authorization headers, even when one is right. + headers(&[basic("owner", "pw-0001"), basic("owner", "pw-0001")]), + ] { + assert_eq!(c.authenticate(&h), None); + } + } + + #[test] + fn a_password_with_a_colon_and_a_lowercase_scheme_work() { + let c = Credentials { + user: "owner".into(), + password_sha256: hex_sha256(b"a:b"), + }; + let v = HeaderValue::from_str(&format!("basic {}", STANDARD.encode("owner:a:b"))).unwrap(); + assert!(c.authenticate(&headers(&[v])).is_some()); + } + + #[test] + fn the_stored_hash_is_compared_with_ct_eq_over_equal_length_hex() { + // The comparison input is always 64 hex bytes whatever the password length, so the + // constant-time compare never short-circuits on length. + for pw in ["", "x", &"y".repeat(5000)] { + assert_eq!(hex_sha256(pw.as_bytes()).len(), 64); + } + } + + #[test] + fn debug_shows_no_secret() { + let text = format!("{:?}", creds()); + assert!(!text.contains("owner") && !text.contains(&hex_sha256(b"pw-0001"))); + } +} diff --git a/crates/ap-proxy/src/approval/csrf.rs b/crates/ap-proxy/src/approval/csrf.rs new file mode 100644 index 0000000..8cb2e8c --- /dev/null +++ b/crates/ap-proxy/src/approval/csrf.rs @@ -0,0 +1,170 @@ +//! Per-page CSRF tokens (design 3.6): random, bound to one entry id, single use. +//! +//! A browser sends Basic credentials on every request to the origin, so a hostile page could +//! post to the approval listener. The token proves the POST came from a page the approver was +//! shown for that entry. The store is bounded: 4 tokens per entry, 256 in all, and the oldest +//! goes first. A token also dies with its entry or after `ttl`. + +use std::fmt; +use std::sync::{Mutex, MutexGuard}; +use std::time::Duration; + +use subtle::ConstantTimeEq; +use tokio::time::Instant; + +use crate::hold::digest::random_hex; + +pub const MAX_PER_ENTRY: usize = 4; +pub const MAX_TOTAL: usize = 256; + +struct Token { + value: String, + entry: String, + expires: Instant, +} + +#[derive(Default)] +pub struct Csrf { + tokens: Mutex>, +} + +impl fmt::Debug for Csrf { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Csrf") + .field("tokens", &self.len()) + .finish_non_exhaustive() + } +} + +impl Csrf { + pub fn new() -> Csrf { + Csrf::default() + } + + fn lock(&self) -> MutexGuard<'_, Vec> { + match self.tokens.lock() { + Ok(g) => g, + Err(poisoned) => poisoned.into_inner(), + } + } + + pub fn len(&self) -> usize { + self.lock().len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// A fresh token for `entry`. `live` says whether an entry id is still `Pending`; tokens of + /// entries that are not are dropped here. + pub fn issue(&self, entry: &str, ttl: Duration, live: impl Fn(&str) -> bool) -> String { + let now = Instant::now(); + let mut g = self.lock(); + g.retain(|t| t.expires > now && live(&t.entry)); + let own = g.iter().filter(|t| t.entry == entry).count(); + if own >= MAX_PER_ENTRY { + if let Some(i) = g.iter().position(|t| t.entry == entry) { + g.remove(i); + } + } + if g.len() >= MAX_TOTAL { + g.remove(0); + } + let value = random_hex(16); + g.push(Token { + value: value.clone(), + entry: entry.to_string(), + expires: now + ttl, + }); + value + } + + /// Use `presented` for `entry`. The token is spent whenever it exists, whether or not it was + /// issued for this entry, so a token cannot be retried against another entry. Returns `true` + /// only for a live token issued for exactly `entry`. + pub fn consume(&self, presented: &str, entry: &str) -> bool { + let now = Instant::now(); + let mut g = self.lock(); + // Compare against every token, so the time does not depend on which one matched. + let mut found = None; + for (i, t) in g.iter().enumerate() { + if bool::from(t.value.as_bytes().ct_eq(presented.as_bytes())) { + found = Some(i); + } + } + let Some(i) = found else { + return false; + }; + let t = g.remove(i); + t.entry == entry && t.expires > now + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TTL: Duration = Duration::from_secs(60); + + #[tokio::test] + async fn a_token_works_once_for_its_entry() { + let c = Csrf::new(); + let t = c.issue("e1", TTL, |_| true); + assert!(c.consume(&t, "e1")); + assert!(!c.consume(&t, "e1"), "single use"); + } + + #[tokio::test] + async fn a_token_for_another_entry_is_refused_and_spent() { + let c = Csrf::new(); + let t = c.issue("e1", TTL, |_| true); + assert!(!c.consume(&t, "e2")); + assert!(!c.consume(&t, "e1"), "the wrong-entry attempt spent it"); + assert!(!c.consume("", "e1")); + assert!(!c.consume("nope", "e1")); + } + + #[tokio::test(start_paused = true)] + async fn a_token_expires() { + let c = Csrf::new(); + let t = c.issue("e1", TTL, |_| true); + tokio::time::advance(TTL + Duration::from_secs(1)).await; + assert!(!c.consume(&t, "e1")); + } + + #[tokio::test] + async fn tokens_of_a_dead_entry_are_dropped_on_the_next_issue() { + let c = Csrf::new(); + let t = c.issue("gone", TTL, |_| true); + let _ = c.issue("e2", TTL, |id| id != "gone"); + assert_eq!(c.len(), 1); + assert!(!c.consume(&t, "gone")); + } + + #[tokio::test] + async fn the_store_is_bounded_per_entry_and_in_total() { + let c = Csrf::new(); + let first = c.issue("e1", TTL, |_| true); + for _ in 0..MAX_PER_ENTRY { + c.issue("e1", TTL, |_| true); + } + assert_eq!(c.len(), MAX_PER_ENTRY); + assert!(!c.consume(&first, "e1"), "the oldest was evicted"); + for i in 0..(MAX_TOTAL + 10) { + c.issue(&format!("n{i}"), TTL, |_| true); + } + assert_eq!(c.len(), MAX_TOTAL); + } + + #[tokio::test] + async fn tokens_are_random_and_debug_shows_none() { + let c = Csrf::new(); + let a = c.issue("e1", TTL, |_| true); + let b = c.issue("e1", TTL, |_| true); + assert_ne!(a, b); + assert_eq!(a.len(), 32); + let text = format!("{c:?}"); + assert!(!text.contains(&a) && !text.contains(&b)); + } +} diff --git a/crates/ap-proxy/src/approval/mod.rs b/crates/ap-proxy/src/approval/mod.rs new file mode 100644 index 0000000..c90f0cf --- /dev/null +++ b/crates/ap-proxy/src/approval/mod.rs @@ -0,0 +1,382 @@ +//! The approval plane (design 3.6): a separate listener, a separate router and a separate +//! credential. The public router mounts none of these routes, and nothing here accepts a caller +//! key. +//! +//! API, client-agnostic: +//! +//! - `GET /pending` lists the pending entries. +//! - `GET /pending/` shows one entry (HTML, or JSON with `Accept: application/json`). +//! - `POST /pending//approve` and `.../deny` carry the page's CSRF token in a form or JSON +//! `csrf` field and answer `{"result": "..."}`. +//! +//! Every response, errors included, goes through [`harden`]. A failed authentication waits a +//! fixed 250 ms before the 401. + +pub mod auth; +pub mod csrf; +pub mod page; + +use std::sync::Arc; +use std::time::Duration; + +use ap_core::config::Approval; +use axum::body::Body; +use futures_util::StreamExt; +use http::{header, HeaderMap, HeaderValue, Method, Request, Response, StatusCode}; +use serde_json::{json, Value}; + +use crate::hold::{ApproveResult, DenyResult, State, Table}; + +/// Most bytes a POST body may carry. +pub const BODY_LIMIT: usize = 1024; +/// How long a POST body may take to arrive. +const BODY_READ: Duration = Duration::from_secs(10); +/// Wait before a 401, so a password guess costs time. +pub const FAIL_DELAY: Duration = Duration::from_millis(250); + +/// The state of the approval listener. +pub struct ApprovalApp { + table: Arc, + /// The policy in force now, read at each approve (`None`: no valid policy, which refuses). + policy: PolicySource, + creds: auth::Credentials, + csrf: csrf::Csrf, + realm: String, + fail_delay: Duration, +} + +impl std::fmt::Debug for ApprovalApp { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ApprovalApp").finish_non_exhaustive() + } +} + +/// Where the approval plane reads the policy that an approve is checked against. +pub type PolicySource = Arc Option> + Send + Sync>; + +impl ApprovalApp { + pub fn new(table: Arc
, cfg: &Approval, policy: PolicySource) -> Arc { + Self::build(table, cfg, FAIL_DELAY, policy) + } + + fn build( + table: Arc
, + cfg: &Approval, + fail_delay: Duration, + policy: PolicySource, + ) -> Arc { + Arc::new(ApprovalApp { + table, + policy, + creds: auth::Credentials::new(cfg), + csrf: csrf::Csrf::new(), + realm: cfg.realm.clone(), + fail_delay, + }) + } + + fn new_token(&self, id: &str) -> String { + let table = &self.table; + self.csrf.issue(id, table.limits().hold, |e| { + table.state(e) == Some(State::Pending) + }) + } +} + +/// Serve one request. Never fails: every outcome is a response. +pub async fn handle(app: Arc, req: Request) -> Response { + harden(route(&app, req).await) +} + +/// Add the six response headers of design 3.6 to `resp`, whatever its status. +pub fn harden(mut resp: Response) -> Response { + let h = resp.headers_mut(); + h.insert( + header::CONTENT_SECURITY_POLICY, + HeaderValue::from_static("default-src 'none'; frame-ancestors 'none'; form-action 'self'"), + ); + h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); + h.insert( + header::REFERRER_POLICY, + HeaderValue::from_static("no-referrer"), + ); + h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + h.insert(header::PRAGMA, HeaderValue::from_static("no-cache")); + h.insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + resp +} + +fn wants_json(headers: &HeaderMap) -> bool { + let accepts = headers + .get_all(header::ACCEPT) + .iter() + .any(|v| has_json(v.as_bytes())); + accepts || is_json_body(headers) +} + +fn is_json_body(headers: &HeaderMap) -> bool { + headers + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.split(';').next()) + .is_some_and(|m| m.trim().eq_ignore_ascii_case("application/json")) +} + +fn has_json(v: &[u8]) -> bool { + String::from_utf8_lossy(v) + .to_ascii_lowercase() + .contains("application/json") +} + +fn respond(status: StatusCode, content_type: &'static str, body: String) -> Response { + let mut r = Response::new(Body::from(body)); + *r.status_mut() = status; + r.headers_mut() + .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type)); + r +} + +fn json_response(status: StatusCode, v: &Value) -> Response { + respond(status, "application/json", v.to_string()) +} + +fn html_response(status: StatusCode, html: String) -> Response { + respond(status, "text/html; charset=utf-8", html) +} + +/// A refusal or result in the client's format: `{"result": ...}` or a small page. +fn result( + status: StatusCode, + json_wanted: bool, + result: &str, + newest: Option<&str>, +) -> Response { + if json_wanted { + let mut v = json!({ "result": result }); + if let Some(n) = newest { + v["newest"] = json!(n); + } + json_response(status, &v) + } else { + html_response(status, page::message(result, result, newest)) + } +} + +fn unauthorized(app: &ApprovalApp, json_wanted: bool) -> Response { + let mut r = result(StatusCode::UNAUTHORIZED, json_wanted, "unauthorized", None); + // The realm was validated at load: printable ASCII without a quote or a backslash. + let value = format!("Basic realm=\"{}\", charset=\"UTF-8\"", app.realm); + if let Ok(v) = HeaderValue::from_str(&value) { + r.headers_mut().insert(header::WWW_AUTHENTICATE, v); + } + r +} + +fn not_allowed(allow: &'static str, json_wanted: bool) -> Response { + let mut r = result( + StatusCode::METHOD_NOT_ALLOWED, + json_wanted, + "method_not_allowed", + None, + ); + r.headers_mut() + .insert(header::ALLOW, HeaderValue::from_static(allow)); + r +} + +/// An entry id as the table issues it: 32 lowercase hex characters. +fn valid_id(s: &str) -> bool { + s.len() == 32 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +async fn route(app: &ApprovalApp, req: Request) -> Response { + let (parts, body) = req.into_parts(); + let json_wanted = wants_json(&parts.headers); + let Some(approver) = app.creds.authenticate(&parts.headers) else { + tokio::time::sleep(app.fail_delay).await; + return unauthorized(app, json_wanted); + }; + let segments: Vec<&str> = parts.uri.path().split('/').collect(); + match segments.as_slice() { + ["", "pending"] => match parts.method { + Method::GET => list(app, json_wanted), + _ => not_allowed("GET", json_wanted), + }, + ["", "pending", id] if valid_id(id) => match parts.method { + Method::GET => show(app, id, json_wanted), + _ => not_allowed("GET", json_wanted), + }, + ["", "pending", id, action @ ("approve" | "deny")] if valid_id(id) => { + if parts.method != Method::POST { + return not_allowed("POST", json_wanted); + } + decide( + app, + &approver, + id, + *action == "approve", + &parts.headers, + body, + ) + .await + } + _ => result(StatusCode::NOT_FOUND, json_wanted, "not_found", None), + } +} + +fn list(app: &ApprovalApp, json_wanted: bool) -> Response { + let items = app.table.list(); + if json_wanted { + let pending: Vec = items.iter().map(page::summary_json).collect(); + json_response(StatusCode::OK, &json!({ "pending": pending })) + } else { + html_response(StatusCode::OK, page::list(&items)) + } +} + +fn show(app: &ApprovalApp, id: &str, json_wanted: bool) -> Response { + let Some(view) = app.table.view(id) else { + return result(StatusCode::NOT_FOUND, json_wanted, "not_found", None); + }; + let token = (view.state == State::Pending).then(|| app.new_token(id)); + if json_wanted { + json_response(StatusCode::OK, &page::entry_json(&view, token.as_deref())) + } else { + html_response(StatusCode::OK, page::entry(&view, token.as_deref())) + } +} + +/// Read a POST body of at most [`BODY_LIMIT`] bytes. +async fn read_body(headers: &HeaderMap, body: Body) -> Result, StatusCode> { + let declared = headers + .get(header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()); + if declared.is_some_and(|n| n > BODY_LIMIT as u64) { + return Err(StatusCode::PAYLOAD_TOO_LARGE); + } + let mut stream = body.into_data_stream(); + let read = async { + let mut buf = Vec::new(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(|_| StatusCode::BAD_REQUEST)?; + if buf.len() + chunk.len() > BODY_LIMIT { + return Err(StatusCode::PAYLOAD_TOO_LARGE); + } + buf.extend_from_slice(&chunk); + } + Ok(buf) + }; + tokio::time::timeout(BODY_READ, read) + .await + .map_err(|_| StatusCode::BAD_REQUEST)? +} + +/// The `csrf` field of a form or JSON body. `Err` is a malformed body; `Ok(None)` is a missing +/// field. +fn csrf_field(headers: &HeaderMap, body: &[u8]) -> Result, ()> { + if is_json_body(headers) { + let v: Value = serde_json::from_slice(body).map_err(|_| ())?; + let obj = v.as_object().ok_or(())?; + return Ok(obj.get("csrf").and_then(Value::as_str).map(str::to_string)); + } + let text = std::str::from_utf8(body).map_err(|_| ())?; + Ok(text + .split('&') + .filter_map(|pair| pair.split_once('=')) + .find(|(k, _)| *k == "csrf") + .map(|(_, v)| v.to_string())) +} + +/// Approve `id` against the policy in force at the moment of the transition: `policy` is read +/// inside the table's critical section, by the same callback that decides, so no snapshot taken +/// earlier can be used. A grant removed after that read is caught by the start claim. +pub(crate) async fn approve_checked( + table: &Table, + policy: &PolicySource, + id: &str, + approver: &str, +) -> ApproveResult { + table + .approve_if(id, approver, |identity, req| { + policy().is_some_and(|s| crate::passthrough::still_held(&s, identity, req)) + }) + .await +} + +async fn decide( + app: &ApprovalApp, + approver: &str, + id: &str, + approve: bool, + headers: &HeaderMap, + body: Body, +) -> Response { + let json_wanted = wants_json(headers); + let bytes = match read_body(headers, body).await { + Ok(b) => b, + Err(status) => { + let name = if status == StatusCode::PAYLOAD_TOO_LARGE { + "payload_too_large" + } else { + "bad_request" + }; + return result(status, json_wanted, name, None); + } + }; + let Ok(token) = csrf_field(headers, &bytes) else { + return result(StatusCode::BAD_REQUEST, json_wanted, "bad_request", None); + }; + let token_ok = token.is_some_and(|t| app.csrf.consume(&t, id)); + if !token_ok { + return result(StatusCode::FORBIDDEN, json_wanted, "csrf_refused", None); + } + let (status, name, newest) = if approve { + approve_outcome(approve_checked(&app.table, &app.policy, id, approver).await) + } else { + deny_outcome(app.table.deny(id, approver)) + }; + result(status, json_wanted, name, newest.as_deref()) +} + +/// `200` only for success. A request that was decided already or can no longer run is a +/// conflict (409) or gone (410); an approve whose outcome is unknown is 504, since the request +/// may have reached Discord. +fn approve_outcome(r: ApproveResult) -> (StatusCode, &'static str, Option) { + let name = r.as_str(); + match r { + ApproveResult::Success => (StatusCode::OK, name, None), + ApproveResult::Superseded { newest } => (StatusCode::CONFLICT, name, Some(newest)), + ApproveResult::AlreadyDecided | ApproveResult::ApprovedButAbandoned => { + (StatusCode::CONFLICT, name, None) + } + ApproveResult::Expired + | ApproveResult::Dropped + | ApproveResult::PolicyChanged + | ApproveResult::Gone => (StatusCode::GONE, name, None), + ApproveResult::ApprovedUnconfirmed => (StatusCode::GATEWAY_TIMEOUT, name, None), + ApproveResult::AuditUnavailable | ApproveResult::ConnectFailed => { + (StatusCode::SERVICE_UNAVAILABLE, name, None) + } + ApproveResult::NotFound => (StatusCode::NOT_FOUND, name, None), + } +} + +fn deny_outcome(r: DenyResult) -> (StatusCode, &'static str, Option) { + let name = r.as_str(); + match r { + DenyResult::Denied => (StatusCode::OK, name, None), + DenyResult::Superseded { newest } => (StatusCode::CONFLICT, name, Some(newest)), + DenyResult::AlreadyDecided => (StatusCode::CONFLICT, name, None), + DenyResult::Expired | DenyResult::Dropped | DenyResult::Gone => { + (StatusCode::GONE, name, None) + } + DenyResult::NotFound => (StatusCode::NOT_FOUND, name, None), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ap-proxy/src/approval/page.rs b/crates/ap-proxy/src/approval/page.rs new file mode 100644 index 0000000..555a635 --- /dev/null +++ b/crates/ap-proxy/src/approval/page.rs @@ -0,0 +1,340 @@ +//! The approval pages (design 3.6) and the JSON views the same API serves. +//! +//! Every value that came from a request is escaped here, and the pages carry no script and no +//! inline style. A credential header value is never in a [`View`], so it cannot reach a page; the +//! page shows that the header is present. + +use serde_json::{json, Value}; + +use crate::hold::{State, View, ViewContent}; + +/// Escape text for an HTML text node or a double-quoted attribute value. +pub fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 8); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +/// The stable name of a state, as the JSON API and the page show it. +pub fn state_str(s: State) -> &'static str { + match s { + State::Pending => "pending", + State::Approved => "approved", + State::Denied => "denied", + State::Expired => "expired", + State::Abandoned => "abandoned", + State::Superseded => "superseded", + State::Dropped => "dropped", + } +} + +fn shell(title: &str, body: &str) -> String { + format!( + "\n\ +\ +{}\n{body}\n", + escape(title) + ) +} + +/// A one-line message page (errors and results). +pub fn message(title: &str, text: &str, newest: Option<&str>) -> String { + let mut b = format!("

{}

\n

{}

\n", escape(title), escape(text)); + if let Some(n) = newest { + b.push_str(&format!( + "

Newer request: {0}

\n", + escape(n) + )); + } + b.push_str("

Pending requests

\n"); + shell(title, &b) +} + +/// The list of pending entries. +pub fn list(items: &[View]) -> String { + let mut b = String::from("

Pending requests

\n"); + if items.is_empty() { + b.push_str("

No request is waiting.

\n"); + } else { + b.push_str("
    \n"); + for v in items { + let Some(c) = &v.content else { continue }; + b.push_str(&format!( + "
  • {method} {route}{path} ({identity})
  • \n", + id = escape(&v.id), + method = escape(&c.method), + route = escape(&c.route), + path = escape(&c.path), + identity = escape(&v.identity), + )); + } + b.push_str("
\n"); + } + shell("Pending requests", &b) +} + +fn row(name: &str, value: &str) -> String { + format!("
\n", escape(name), value) +} + +fn content_table(v: &View, c: &ViewContent) -> String { + let mut t = String::from("
{}{}
\n"); + t.push_str(&row("Identity", &escape(&v.identity))); + t.push_str(&row("Method", &escape(&c.method))); + t.push_str(&row("Route", &escape(&c.route))); + t.push_str(&row("Sent to", &escape(&c.upstream))); + t.push_str(&row("Path", &escape(&c.path))); + t.push_str(&row( + "Query", + &c.query + .as_deref() + .map_or_else(|| "(none)".to_string(), escape), + )); + t.push_str(&row( + "Content type", + &c.content_type + .as_deref() + .map_or_else(|| "(none)".to_string(), escape), + )); + t.push_str(&row("Body size", &format!("{} bytes", c.body_len))); + t.push_str(&row("Digest", &escape(&c.digest))); + t.push_str(&row("Caller connection", "unknown")); + t.push_str("
\n"); + t +} + +fn headers_table(c: &ViewContent) -> String { + let mut t = String::from("

Headers that will be forwarded

\n\n"); + for h in &c.headers { + let value = match &h.value { + Some(v) => escape(v), + None => "present (value not shown)".to_string(), + }; + t.push_str(&row(&h.name, &value)); + } + t.push_str("
\n"); + t +} + +fn buttons(id: &str, csrf: Option<&str>) -> String { + let mut b = String::new(); + for (action, label) in [("approve", "Approve"), ("deny", "Deny")] { + match csrf { + Some(token) => b.push_str(&format!( + "
\ +\ +
\n", + id = escape(id), + token = escape(token), + )), + None => b.push_str(&format!( + "
\n" + )), + } + } + b +} + +/// The page for one entry. `csrf` is the token for the approve and deny forms; without it the +/// buttons are disabled (every state but `Pending`). +pub fn entry(v: &View, csrf: Option<&str>) -> String { + let mut b = format!( + "

Request {}

\n

State: {}

\n", + escape(&v.id), + state_str(v.state) + ); + match v.state { + State::Superseded => { + b.push_str("

Superseded. A newer identical request replaced this one; nothing was sent for it."); + if let Some(n) = &v.superseded_by { + b.push_str(&format!( + " Decide on the newest request {0}.", + escape(n) + )); + } + b.push_str("

\n"); + } + State::Pending => {} + other => b.push_str(&format!( + "

This request is {} and can no longer be decided.

\n", + state_str(other) + )), + } + if let Some(c) = &v.content { + b.push_str(&content_table(v, c)); + if c.body_lossy { + b.push_str("

The body is not valid UTF-8. Invalid bytes are shown as U+FFFD; Discord receives the original bytes.

\n"); + } + b.push_str(&format!( + "

Body

\n
{}
\n", + escape(&c.body_text) + )); + b.push_str(&headers_table(c)); + } + b.push_str(&buttons(&v.id, csrf)); + b.push_str("

Pending requests

\n"); + shell(&format!("Request {}", v.id), &b) +} + +/// The summary of one pending entry, for the JSON list. +pub fn summary_json(v: &View) -> Value { + match &v.content { + Some(c) => json!({ + "id": v.id, + "identity": v.identity, + "method": c.method, + "route": c.route, + "path": c.path, + "body_len": c.body_len, + }), + None => json!({"id": v.id, "state": state_str(v.state)}), + } +} + +/// The JSON for one entry. `csrf` is present only while the entry is `Pending`. +pub fn entry_json(v: &View, csrf: Option<&str>) -> Value { + let mut out = json!({ + "id": v.id, + "state": state_str(v.state), + "identity": v.identity, + }); + let map = out.as_object_mut().expect("object"); + if let Some(n) = &v.superseded_by { + map.insert("newest".into(), json!(n)); + } + if let Some(c) = &v.content { + let headers: Vec = c + .headers + .iter() + .map(|h| match &h.value { + Some(value) => json!({"name": h.name, "value": value}), + None => json!({"name": h.name, "credential": "present"}), + }) + .collect(); + map.insert("method".into(), json!(c.method)); + map.insert("route".into(), json!(c.route)); + map.insert("upstream".into(), json!(c.upstream)); + map.insert("path".into(), json!(c.path)); + map.insert("query".into(), json!(c.query)); + map.insert("content_type".into(), json!(c.content_type)); + map.insert("body_len".into(), json!(c.body_len)); + map.insert("body".into(), json!(c.body_text)); + map.insert("body_lossy".into(), json!(c.body_lossy)); + map.insert("digest".into(), json!(c.digest)); + map.insert("headers".into(), json!(headers)); + map.insert("connection".into(), json!("unknown")); + } + if let Some(t) = csrf { + map.insert("csrf".into(), json!(t)); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hold::ViewHeader; + + fn pending(body: &str) -> View { + View { + id: "a".repeat(32), + state: State::Pending, + identity: "muse-pilot".into(), + superseded_by: None, + content: Some(ViewContent { + method: "POST".into(), + route: "discord".into(), + upstream: "https://discord.example.test:443".into(), + path: "/webhooks/1/".into(), + query: Some("wait=true".into()), + content_type: Some("application/json".into()), + body_len: body.len(), + body_text: body.into(), + body_lossy: false, + digest: "d".repeat(64), + headers: vec![ + ViewHeader { + name: "authorization".into(), + value: None, + }, + ViewHeader { + name: "x-note".into(), + value: Some("v".into()), + }, + ], + }), + } + } + + #[test] + fn escape_covers_the_five_characters() { + assert_eq!( + escape("&'"), + "<a href="x">&'" + ); + } + + #[test] + fn script_body_and_header_values_are_escaped() { + let html = entry(&pending(""), Some("tok")); + assert!(!html.contains(""}"#, + ) + .await; + let page = env.get(&format!("/pending/{id}"), "").await; + assert_eq!(page.status, 200); + page.assert_hardened("page"); + assert!(page + .header("content-type") + .unwrap() + .starts_with("text/html")); + let html = &page.body; + assert!(!html.contains("