From 6ff7e2a05d81631865e47bfe6c9ad0702b6e6d95 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:36:48 -0500 Subject: [PATCH 01/16] feat(ap-core): hold verdict, path_patterns, approval/notify config, new outcome codes Config: Grant.path_patterns (paths optional, one required), hold allowed on passthrough grants with path_patterns only, [passthrough] hold limits, [approval] and [notify] tables with validation. Policy: Verdict and Snapshot::evaluate_verdict (whole-path segment match, hold beats allow). Codes: HumanDenied, Expired, ContentType, ContentEncoding, CredentialMissing, TableFull, IdentityCap, Cooldown, Superseded, Shutdown, DroppedOnReload, AuditUnavailable with the design 3.5 outcome rows. Verified on macmini: cargo fmt --all --check ok; cargo clippy --workspace --all-targets -D warnings ok; cargo test -p ap-core 189 passed; cargo test --workspace all ok (sidecar rendering tests unchanged). --- crates/ap-core/src/config.rs | 425 +++++++++++++++++++++++++++++++++- crates/ap-core/src/error.rs | 69 +++++- crates/ap-core/src/outcome.rs | 45 +++- crates/ap-core/src/policy.rs | 148 +++++++++++- 4 files changed, 667 insertions(+), 20 deletions(-) diff --git a/crates/ap-core/src/config.rs b/crates/ap-core/src/config.rs index 5e7dd91..26eaf67 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(()) } @@ -602,6 +816,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(); @@ -675,10 +900,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 +927,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 +951,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 +1685,176 @@ 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()); + } + + #[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..6464ca7 100644 --- a/crates/ap-core/src/policy.rs +++ b/crates/ap-core/src/policy.rs @@ -3,10 +3,39 @@ //! 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, + } + } +} + #[derive(Debug, Clone)] pub struct Snapshot { routes: HashMap, @@ -36,6 +65,38 @@ 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; + for g in grants { + let hit = g.route == route + && g.methods.iter().any(|m| m == method) + && (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), + } + } + 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 +249,91 @@ 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) + ); + } + + #[test] + fn verdict_hold_beats_allow_in_either_grant_order() { + let path = "/api/v10/channels/1/messages"; + for text in [format!("{ALLOW}{HOLD}"), format!("{HOLD}{ALLOW}")] { + let s = pt(&text); + assert_eq!( + s.evaluate_verdict("muse", "discord", "POST", path), + Ok(Verdict::Hold) + ); + assert_eq!( + s.evaluate_verdict("muse", "discord", "GET", path), + Ok(Verdict::Allow) + ); + assert_eq!( + s.evaluate_verdict( + "muse", + "discord", + "POST", + "/api/v10/channels/1/messages/2/reactions" + ), + Ok(Verdict::Allow) + ); + } + } + + #[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(); From 8c088d43a6354cf861272fbfbf21a55a62bea935 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:43:26 -0500 Subject: [PATCH 02/16] feat(ap-proxy): hold table, entry state machine, digest and HoldRec audit Library only, no pipeline wiring (design 3.4 steps 4-8, 3.9). - hold::Table: admit (cooldown, dedupe/supersede, caps; audit persist runs before any change), approve with 2 s confirm oneshot, deny, expire, abandon, drop_identities_missing, drop_all, drain_pending, view. Every row of the approve table is an ApproveResult. Cooldown starts only on deny/expire. Hand-written Debug on everything that holds headers, bodies or the fingerprint. - hold::digest: length-prefixed encoding; credential-blind audit digest (sha256) and per-process HMAC-SHA256 equality fingerprint. - ap-core: HoldRec with a fixed key set; ap-proxy AuditSink gains try_write_line/try_write_hold (Err on write or flush failure) and a best-effort write_hold. - ap-proxy deps: hmac, sha2, getrandom (normal), tokio test-util (dev). Verified on macmini (cargo target on the RAID volume): - cargo fmt --all --check: ok - cargo clippy --workspace --all-targets -- -D warnings: ok - cargo clippy -p ap-proxy --features stage1-probe --all-targets -- -D warnings: ok - cargo test -p ap-proxy hold::: 38 passed - cargo test --workspace: all suites passed (ap-proxy lib 111 passed) --- Cargo.lock | 12 + crates/ap-core/src/audit.rs | 117 +++++ crates/ap-proxy/Cargo.toml | 5 +- crates/ap-proxy/src/audit_sink.rs | 146 +++++- crates/ap-proxy/src/hold/digest.rs | 255 +++++++++++ crates/ap-proxy/src/hold/entry.rs | 283 ++++++++++++ crates/ap-proxy/src/hold/mod.rs | 447 ++++++++++++++++++ crates/ap-proxy/src/hold/tests.rs | 704 +++++++++++++++++++++++++++++ crates/ap-proxy/src/lib.rs | 1 + 9 files changed, 1960 insertions(+), 10 deletions(-) create mode 100644 crates/ap-proxy/src/hold/digest.rs create mode 100644 crates/ap-proxy/src/hold/entry.rs create mode 100644 crates/ap-proxy/src/hold/mod.rs create mode 100644 crates/ap-proxy/src/hold/tests.rs diff --git a/Cargo.lock b/Cargo.lock index c7179eb..598e994 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -67,6 +67,7 @@ dependencies = [ "futures-util", "getrandom 0.2.17", "h2", + "hmac", "http", "http-body-util", "hyper", @@ -76,6 +77,7 @@ dependencies = [ "rustls", "serde", "serde_json", + "sha2", "subtle", "tokio", "tokio-rustls", @@ -315,6 +317,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -507,6 +510,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" diff --git a/crates/ap-core/src/audit.rs b/crates/ap-core/src/audit.rs index 50a75a8..6544dd0 100644 --- a/crates/ap-core/src/audit.rs +++ b/crates/ap-core/src/audit.rs @@ -49,6 +49,60 @@ 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, +} + +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 +191,67 @@ 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, + } + } + + #[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", + "request_id", + "route", + "status", + "transition", + ] + ); + } + + #[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-proxy/Cargo.toml b/crates/ap-proxy/Cargo.toml index f1dea2c..fce3e46 100644 --- a/crates/ap-proxy/Cargo.toml +++ b/crates/ap-proxy/Cargo.toml @@ -19,12 +19,15 @@ axum = { version = "0.8", default-features = false, features = ["http1", "tokio" bytes = "1" ed25519-dalek = "2" futures-util = "0.3" +getrandom = "0.2" +hmac = "0.12" http = "1" hyper = { version = "1", features = ["server", "http1"] } 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"] } @@ -49,9 +52,9 @@ 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/audit_sink.rs b/crates/ap-proxy/src/audit_sink.rs index e2e145c..411bcb2 100644 --- a/crates/ap-proxy/src/audit_sink.rs +++ b/crates/ap-proxy/src/audit_sink.rs @@ -1,13 +1,14 @@ //! Audit sink: one JSON line per decision. The pipeline holds one sink for the process. //! -//! A write failure is counted and never refuses a request. Durable, fail-closed audit is out of -//! Phase 1 (RFC Q5). +//! `write_line` and `write_rec` count a write failure and never refuse a request. The `try_` +//! methods return the failure, for the held (write) routes whose `held` and `forward_started` +//! records must exist before the action (design 3.9). use std::io::{self, Write}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; -use ap_core::audit::AuditRec; +use ap_core::audit::{AuditRec, HoldRec}; /// Standard output, locked for each write. struct Stdout; @@ -41,19 +42,43 @@ impl AuditSink { AuditSink::new(Box::new(Stdout)) } - /// Write one decision line. A newline is added when `line` lacks one. - pub fn write_line(&self, line: &str) { + /// Write one line and report whether the write and the flush both succeeded. + fn write_checked(&self, line: &str) -> io::Result<()> { let mut w = match self.writer.lock() { Ok(w) => w, Err(poisoned) => poisoned.into_inner(), }; - let mut ok = w.write_all(line.as_bytes()).is_ok(); - if ok && !line.ends_with('\n') { - ok = w.write_all(b"\n").is_ok(); + let mut result = w.write_all(line.as_bytes()); + if result.is_ok() && !line.ends_with('\n') { + result = w.write_all(b"\n"); } - if !(ok && w.flush().is_ok()) { + let result = result.and_then(|()| w.flush()); + if result.is_err() { self.failures.fetch_add(1, Ordering::Relaxed); } + result + } + + /// Write one decision line. A newline is added when `line` lacks one. A failure is counted + /// and otherwise ignored. + pub fn write_line(&self, line: &str) { + let _ = self.write_checked(line); + } + + /// Write one line and return the error when the write or the flush fails. The failure is + /// counted as well. + pub fn try_write_line(&self, line: &str) -> io::Result<()> { + self.write_checked(line) + } + + /// Write a held-request transition, ignoring a failure (counted). + pub fn write_hold(&self, rec: &HoldRec) { + self.write_line(&rec.to_json_line()); + } + + /// Write a held-request transition and return the error when it did not reach the sink. + pub fn try_write_hold(&self, rec: &HoldRec) -> io::Result<()> { + self.try_write_line(&rec.to_json_line()) } /// Write a request decision. @@ -66,3 +91,106 @@ impl AuditSink { self.failures.load(Ordering::Relaxed) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[derive(Clone, Default)] + struct Shared(Arc>>); + + impl Write for Shared { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + /// Fails the write, the flush, or neither. + struct Faulty { + fail_write: bool, + fail_flush: bool, + } + + impl Write for Faulty { + fn write(&mut self, buf: &[u8]) -> io::Result { + if self.fail_write { + Err(io::Error::other("write")) + } else { + Ok(buf.len()) + } + } + fn flush(&mut self) -> io::Result<()> { + if self.fail_flush { + Err(io::Error::other("flush")) + } else { + Ok(()) + } + } + } + + fn hold_rec() -> HoldRec { + HoldRec { + request_id: "id1".into(), + identity: "muse".into(), + route: Some("discord".into()), + method: "POST".into(), + path: "/channels/1/messages".into(), + digest: None, + transition: "held", + approver: None, + code: None, + status: None, + duration_ms: 0, + auth_present: true, + } + } + + #[test] + fn try_write_succeeds_and_writes_one_line() { + let buf = Shared::default(); + let sink = AuditSink::new(Box::new(buf.clone())); + sink.try_write_hold(&hold_rec()).unwrap(); + sink.try_write_line("{\"a\":1}").unwrap(); + let text = String::from_utf8(buf.0.lock().unwrap().clone()).unwrap(); + assert_eq!(text.lines().count(), 2); + assert!(text.ends_with('\n')); + assert_eq!(sink.failures(), 0); + } + + #[test] + fn try_write_returns_err_on_write_failure() { + let sink = AuditSink::new(Box::new(Faulty { + fail_write: true, + fail_flush: false, + })); + assert!(sink.try_write_hold(&hold_rec()).is_err()); + assert!(sink.try_write_line("x").is_err()); + assert_eq!(sink.failures(), 2); + } + + #[test] + fn try_write_returns_err_on_flush_failure() { + let sink = AuditSink::new(Box::new(Faulty { + fail_write: false, + fail_flush: true, + })); + assert!(sink.try_write_hold(&hold_rec()).is_err()); + assert_eq!(sink.failures(), 1); + } + + #[test] + fn best_effort_writes_swallow_the_failure() { + let sink = AuditSink::new(Box::new(Faulty { + fail_write: true, + fail_flush: false, + })); + sink.write_hold(&hold_rec()); + sink.write_line("x"); + assert_eq!(sink.failures(), 2); + } +} diff --git a/crates/ap-proxy/src/hold/digest.rs b/crates/ap-proxy/src/hold/digest.rs new file mode 100644 index 0000000..0284edd --- /dev/null +++ b/crates/ap-proxy/src/hold/digest.rs @@ -0,0 +1,255 @@ +//! The two values computed over a held request (design 3.4 step 4). +//! +//! Both start from one length-prefixed encoding of the complete outbound semantic request: method, +//! route, raw path, raw query, the forwarded header set in order, and the body. Length prefixes +//! make field boundaries unambiguous, so moving a byte between two fields changes the encoding. +//! +//! - The *audit digest* replaces credential header values with a fixed marker, so it can be shown +//! and logged and reveals nothing about a credential. +//! - The *equality fingerprint* keeps the credential values and is an HMAC-SHA256 under a random +//! per-process key. It lives in memory only and decides whether two requests are the same. + +use std::fmt; + +use hmac::{Hmac, Mac}; +use sha2::{Digest, Sha256}; + +use super::entry::HeldRequest; + +/// Stands in for a credential header value in the audit digest. +const CREDENTIAL_MARKER: &[u8] = b""; +const DOMAIN: &[u8] = b"ap-hold-v1"; + +fn put(buf: &mut Vec, bytes: &[u8]) { + buf.extend_from_slice(&(bytes.len() as u64).to_be_bytes()); + buf.extend_from_slice(bytes); +} + +/// The length-prefixed encoding. With `blind`, credential header values become the marker. +fn encode(req: &HeldRequest, blind: bool) -> Vec { + let mut buf = Vec::with_capacity(256 + req.body.len()); + put(&mut buf, DOMAIN); + put(&mut buf, req.method.as_bytes()); + put(&mut buf, req.route.as_bytes()); + put(&mut buf, req.path.as_bytes()); + match &req.query { + Some(q) => { + buf.push(1); + put(&mut buf, q.as_bytes()); + } + None => buf.push(0), + } + buf.extend_from_slice(&(req.headers.len() as u64).to_be_bytes()); + for (name, value) in &req.headers { + put(&mut buf, name.as_bytes()); + if blind && HeldRequest::is_credential(name) { + put(&mut buf, CREDENTIAL_MARKER); + } else { + put(&mut buf, value); + } + } + put(&mut buf, &req.body); + buf +} + +fn hex(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(bytes.len() * 2); + for b in bytes { + s.push(DIGITS[(b >> 4) as usize] as char); + s.push(DIGITS[(b & 0x0f) as usize] as char); + } + s +} + +/// Hex sha256 of the credential-blind encoding. Safe to show and to write to the audit stream. +pub fn audit_digest(req: &HeldRequest) -> String { + hex(&Sha256::digest(encode(req, true))) +} + +/// Random lowercase hex of `n` bytes, from the operating system. +pub(super) fn random_hex(n: usize) -> String { + let mut buf = vec![0u8; n]; + getrandom::getrandom(&mut buf).expect("operating system random source failed"); + hex(&buf) +} + +/// HMAC-SHA256 over the credential-inclusive encoding. Compared only for equality, never shown. +#[derive(Clone, PartialEq, Eq)] +pub struct Fingerprint([u8; 32]); + +impl fmt::Debug for Fingerprint { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Fingerprint(..)") + } +} + +impl Fingerprint { + /// Hex form, for tests that check the value never leaks. + #[cfg(test)] + pub(crate) fn hex_for_test(&self) -> String { + hex(&self.0) + } +} + +/// Computes fingerprints under one random key, generated per process. +pub struct Fingerprinter { + key: [u8; 32], +} + +impl fmt::Debug for Fingerprinter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Fingerprinter(..)") + } +} + +impl Default for Fingerprinter { + fn default() -> Self { + Fingerprinter::new() + } +} + +impl Fingerprinter { + pub fn new() -> Self { + let mut key = [0u8; 32]; + getrandom::getrandom(&mut key).expect("operating system random source failed"); + Fingerprinter { key } + } + + pub fn fingerprint(&self, req: &HeldRequest) -> Fingerprint { + let mut mac = as Mac>::new_from_slice(&self.key) + .expect("HMAC accepts a key of any length"); + mac.update(&encode(req, false)); + Fingerprint(mac.finalize().into_bytes().into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use bytes::Bytes; + + fn req() -> HeldRequest { + HeldRequest { + method: "POST".into(), + route: "discord".into(), + path: "/channels/1/messages".into(), + query: Some("wait=true".into()), + headers: vec![ + ("authorization".into(), b"Bot SECRET-ONE".to_vec()), + ("content-type".into(), b"application/json".to_vec()), + ("x-api-key".into(), b"KEY-ONE".to_vec()), + ], + body: Bytes::from_static(b"{\"content\":\"hi\"}"), + } + } + + #[test] + fn digest_is_stable_hex_sha256() { + let d = audit_digest(&req()); + assert_eq!(d, audit_digest(&req())); + assert_eq!(d.len(), 64); + assert!(d + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))); + } + + #[test] + fn digest_is_credential_blind() { + let mut other = req(); + other.headers[0].1 = b"Bot SECRET-TWO".to_vec(); + other.headers[2].1 = b"KEY-TWO".to_vec(); + assert_eq!(audit_digest(&req()), audit_digest(&other)); + } + + #[test] + fn digest_still_sees_everything_else() { + let base = audit_digest(&req()); + let mut r = req(); + r.body = Bytes::from_static(b"{\"content\":\"ho\"}"); + assert_ne!(base, audit_digest(&r)); + let mut r = req(); + r.headers[1].1 = b"application/json; charset=utf-8".to_vec(); + assert_ne!(base, audit_digest(&r)); + let mut r = req(); + r.query = None; + assert_ne!(base, audit_digest(&r)); + let mut r = req(); + r.query = Some(String::new()); + assert_ne!(audit_digest(&r), { + let mut n = req(); + n.query = None; + audit_digest(&n) + }); + let mut r = req(); + r.method = "PUT".into(); + assert_ne!(base, audit_digest(&r)); + let mut r = req(); + r.headers.remove(0); + assert_ne!( + base, + audit_digest(&r), + "dropping Authorization changes the digest" + ); + } + + #[test] + fn encoding_is_length_prefixed() { + let mut a = req(); + a.route = "ab".into(); + a.path = "c".into(); + let mut b = req(); + b.route = "a".into(); + b.path = "bc".into(); + assert_ne!(audit_digest(&a), audit_digest(&b)); + let mut a = req(); + a.headers = vec![("a".into(), b"bc".to_vec())]; + let mut b = req(); + b.headers = vec![("ab".into(), b"c".to_vec())]; + assert_ne!(audit_digest(&a), audit_digest(&b)); + } + + #[test] + fn repeated_header_order_matters() { + let mut a = req(); + a.headers = vec![("x-a".into(), b"1".to_vec()), ("x-a".into(), b"2".to_vec())]; + let mut b = req(); + b.headers = vec![("x-a".into(), b"2".to_vec()), ("x-a".into(), b"1".to_vec())]; + assert_ne!(audit_digest(&a), audit_digest(&b)); + } + + #[test] + fn fingerprint_sees_credentials() { + let fp = Fingerprinter::new(); + let mut other = req(); + other.headers[0].1 = b"Bot SECRET-TWO".to_vec(); + assert_eq!(fp.fingerprint(&req()), fp.fingerprint(&req())); + assert_ne!(fp.fingerprint(&req()), fp.fingerprint(&other)); + let mut other = req(); + other.headers[2].1 = b"KEY-TWO".to_vec(); + assert_ne!(fp.fingerprint(&req()), fp.fingerprint(&other)); + } + + #[test] + fn fingerprint_key_is_per_instance() { + let a = Fingerprinter::new(); + let b = Fingerprinter::new(); + assert_ne!(a.fingerprint(&req()), b.fingerprint(&req())); + } + + #[test] + fn debug_hides_fingerprint_and_key() { + let fp = Fingerprinter::new(); + let f = fp.fingerprint(&req()); + let shown = format!("{f:?} {fp:?}"); + assert!(!shown.contains(&f.hex_for_test())); + assert_eq!(shown, "Fingerprint(..) Fingerprinter(..)"); + } + + #[test] + fn random_hex_has_requested_length_and_differs() { + let a = random_hex(16); + assert_eq!(a.len(), 32); + assert_ne!(a, random_hex(16)); + } +} diff --git a/crates/ap-proxy/src/hold/entry.rs b/crates/ap-proxy/src/hold/entry.rs new file mode 100644 index 0000000..0311d7e --- /dev/null +++ b/crates/ap-proxy/src/hold/entry.rs @@ -0,0 +1,283 @@ +//! Hold entry types: the immutable request, the state machine's states, and the messages the +//! table sends to the waiting handler (design 3.4 steps 6 and 8). +//! +//! `HeldRequest`, `Entry` and `View` hold headers, a body or a fingerprint, so each has a +//! hand-written `Debug` that prints sizes and names only. + +use std::fmt; +use std::sync::Arc; + +use bytes::Bytes; +use tokio::sync::oneshot; + +use super::digest::Fingerprint; + +/// The complete outbound semantic request of a held entry. Immutable once admitted: the entry id +/// names exactly these bytes. +#[derive(Clone)] +pub struct HeldRequest { + pub method: String, + pub route: String, + /// Route-relative raw path, as matched by policy and forwarded. + pub path: String, + /// Raw query without the `?`. + pub query: Option, + /// The forwarded header set after the strip algorithm, repeated headers in order. Names are + /// lowercase. + pub headers: Vec<(String, Vec)>, + pub body: Bytes, +} + +impl HeldRequest { + /// Whether a forwarded header carries a credential (`Authorization` or any `AUTH_HEADERS` + /// member). + pub fn is_credential(name: &str) -> bool { + ap_core::headers::AUTH_HEADERS + .iter() + .any(|c| c.eq_ignore_ascii_case(name)) + } + + /// Whether the request carries an `Authorization` header. + pub fn auth_present(&self) -> bool { + self.headers + .iter() + .any(|(n, _)| n.eq_ignore_ascii_case("authorization")) + } +} + +impl fmt::Debug for HeldRequest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("HeldRequest") + .field("method", &self.method) + .field("route", &self.route) + .field("headers", &self.headers.len()) + .field("body_len", &self.body.len()) + .finish_non_exhaustive() + } +} + +/// Where an entry is in its life. `Pending` moves to exactly one of the others, once. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + Pending, + Approved, + Denied, + Expired, + /// The caller went away before any decision. + Abandoned, + /// A newer identical request from the same identity replaced it. + Superseded, + /// Removed by a policy reload or by shutdown. + Dropped, +} + +/// What the waiting handler learns. Sent at most once, by the transition that wins. +#[derive(Debug)] +pub enum Decision { + /// A human approved. The handler must answer `confirm` (design 3.4 step 8). + Approved { + approver: String, + confirm: ConfirmTx, + }, + Denied { + approver: String, + }, + /// Replaced by `newest`. + Superseded { + newest: String, + }, + /// Identity removed by a reload, or the policy file went away. + Dropped, + /// The gate is shutting down. + Shutdown, +} + +/// The handler's answer to an approve call. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Confirm { + /// Milestone 2: the first request byte was handed to the upstream connection. + Started, + /// The caller is gone before milestone 2; nothing was sent. + Abandoned, + /// The `forward_started` audit write failed; nothing was sent. + AuditUnavailable, + /// The upstream connection could not be established; nothing was sent. + ConnectFailed, +} + +/// The handler's end of the approve confirmation. Dropping it without sending reads as +/// `approved_but_abandoned`. +#[derive(Debug)] +pub struct ConfirmTx(pub(super) oneshot::Sender); + +impl ConfirmTx { + pub fn send(self, c: Confirm) { + let _ = self.0.send(c); + } +} + +/// The result of an approve call (design 3.4, approve table). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ApproveResult { + /// Pending, and the forward reached milestone 2. + Success, + /// The entry was replaced; carries the newest entry id. + Superseded { + newest: String, + }, + /// Approved or denied already. + AlreadyDecided, + Expired, + Dropped, + /// The caller disconnected before any decision. + Gone, + /// Approved, but the handler was gone before milestone 2. Nothing was sent. + ApprovedButAbandoned, + /// Approved, and no confirmation arrived within 2 s. + ApprovedUnconfirmed, + /// Approved, but the `forward_started` audit write failed. Nothing was sent. + AuditUnavailable, + /// Approved, but the upstream connection failed. Nothing was sent. + ConnectFailed, + /// No such entry (never existed, or forgotten after it was decided). + NotFound, +} + +impl ApproveResult { + /// Stable identifier for the approval API. + pub fn as_str(&self) -> &'static str { + match self { + ApproveResult::Success => "success", + ApproveResult::Superseded { .. } => "superseded", + ApproveResult::AlreadyDecided => "already_decided", + ApproveResult::Expired => "expired", + ApproveResult::Dropped => "dropped", + ApproveResult::Gone => "gone", + ApproveResult::ApprovedButAbandoned => "approved_but_abandoned", + ApproveResult::ApprovedUnconfirmed => "approved_unconfirmed", + ApproveResult::AuditUnavailable => "audit_unavailable", + ApproveResult::ConnectFailed => "connect_failed", + ApproveResult::NotFound => "not_found", + } + } +} + +/// The result of a deny call. A deny on a decided entry changes nothing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DenyResult { + Denied, + Superseded { newest: String }, + AlreadyDecided, + Expired, + Dropped, + Gone, + NotFound, +} + +impl DenyResult { + pub fn as_str(&self) -> &'static str { + match self { + DenyResult::Denied => "denied", + DenyResult::Superseded { .. } => "superseded", + DenyResult::AlreadyDecided => "already_decided", + DenyResult::Expired => "expired", + DenyResult::Dropped => "dropped", + DenyResult::Gone => "gone", + DenyResult::NotFound => "not_found", + } + } +} + +/// A `Pending` entry. +pub(super) struct Entry { + pub identity: String, + pub fingerprint: Fingerprint, + pub digest: String, + pub req: Arc, + pub tx: Option>, +} + +impl fmt::Debug for Entry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Entry") + .field("identity", &self.identity) + .field("req", &self.req) + .finish_non_exhaustive() + } +} + +/// What the table remembers about an entry after it left `Pending`: the state only, no request. +#[derive(Debug, Clone)] +pub(super) struct Done { + pub state: State, + pub identity: String, + pub superseded_by: Option, +} + +/// One header as the approver sees it. `value` is `None` for a credential header, which the page +/// shows as present. +#[derive(Clone, PartialEq, Eq)] +pub struct ViewHeader { + pub name: String, + pub value: Option, +} + +/// The request content of a `Pending` entry, as the approval page shows it. +#[derive(Clone)] +pub struct ViewContent { + pub method: String, + pub route: String, + /// Path with `webhooks`/`interactions` token segments redacted. + pub path: String, + pub query: Option, + pub content_type: Option, + pub body_len: usize, + /// The body as lossy UTF-8 text. The page must escape it. + pub body_text: String, + /// The body was not valid UTF-8 and `body_text` replaced some bytes. + pub body_lossy: bool, + pub digest: String, + pub headers: Vec, +} + +/// What the approval API may show about an entry. Credential header values are never in it. +#[derive(Clone)] +pub struct View { + pub id: String, + pub state: State, + pub identity: String, + /// The newest entry id, when `state` is `Superseded`. + pub superseded_by: Option, + /// Present while the entry is `Pending`. + pub content: Option, +} + +impl fmt::Debug for View { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("View") + .field("id", &self.id) + .field("state", &self.state) + .field("identity", &self.identity) + .field("content", &self.content.is_some()) + .finish_non_exhaustive() + } +} + +impl fmt::Debug for ViewContent { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ViewContent") + .field("method", &self.method) + .field("route", &self.route) + .field("body_len", &self.body_len) + .finish_non_exhaustive() + } +} + +impl fmt::Debug for ViewHeader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ViewHeader") + .field("name", &self.name) + .field("value_shown", &self.value.is_some()) + .finish() + } +} diff --git a/crates/ap-proxy/src/hold/mod.rs b/crates/ap-proxy/src/hold/mod.rs new file mode 100644 index 0000000..cef8e68 --- /dev/null +++ b/crates/ap-proxy/src/hold/mod.rs @@ -0,0 +1,447 @@ +//! The hold table (design 3.4 steps 4 to 8, the approve table, cooldown, and 3.7 caps). +//! +//! Library only: nothing here reads a socket or writes an audit line by itself. A handler admits +//! a request, waits on the returned [`Decision`] channel, and writes the audit record for the +//! transition it learns about. One mutex guards every entry, the per-identity cooldown and the +//! supersede lookup, so the first transition out of `Pending` wins and no later one can happen. +//! +//! Only `Pending` entries count against the caps. A decided entry is reduced to a tombstone +//! (state, identity, newest id) so a late approve still gets the right answer, and the tombstones +//! are bounded. +//! +//! Nothing in this module prints a header, a body or a fingerprint, and every type that holds one +//! has a hand-written `Debug`. + +pub mod digest; +pub mod entry; + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::fmt; +use std::io; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use ap_core::canon::redact_path; +use ap_core::config::Passthrough; +use ap_core::error::Code; +use tokio::sync::oneshot; +use tokio::time::Instant; + +pub use entry::{ + ApproveResult, Confirm, ConfirmTx, Decision, DenyResult, HeldRequest, State, View, ViewContent, + ViewHeader, +}; +use entry::{Done, Entry}; + +/// How long an approve call waits for the handler's confirmation (design 3.4 step 8). +pub const CONFIRM_TIMEOUT: Duration = Duration::from_secs(2); + +/// Decided entries remembered so a late approve, deny or page view gets a precise answer. +const DONE_MAX: usize = 1024; + +/// The bounds of the table. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// How long a handler waits for a decision before it calls [`Table::expire`]. + pub hold: Duration, + pub max_total: usize, + pub max_per_identity: usize, + /// Refusal window after a human deny or an expiry. Zero disables it. + pub cooldown: Duration, +} + +impl Limits { + pub fn from_config(pt: &Passthrough) -> Limits { + Limits { + hold: Duration::from_secs(pt.hold_secs), + max_total: pt.max_held_total, + max_per_identity: pt.max_held_per_identity, + cooldown: Duration::from_secs(pt.cooldown_secs), + } + } +} + +/// What [`Table::admit`] decided. +#[derive(Debug)] +pub enum Admission { + /// The request is held. `superseded` names the older entry it replaced, if any; a notifier + /// fires only when it is `None`. + Held(Held), + /// Refused; nothing was inserted and no older entry changed. + Refused(Code), +} + +/// The handler's side of a new entry. +#[derive(Debug)] +pub struct Held { + pub id: String, + /// Credential-blind digest, as written to the `held` audit record. + pub digest: String, + /// Resolves when a transition other than expiry or abandonment wins. + pub decision: oneshot::Receiver, + pub superseded: Option, +} + +struct Inner { + pending: HashMap, + done: HashMap, + done_order: VecDeque, + /// Identity to the instant its cooldown ends. + cooldown: HashMap, + /// Set by `drain_pending`: no new entry is admitted. + closed: bool, +} + +impl Inner { + /// Move `id` out of `Pending` into a tombstone with `state`. Returns the entry. + fn finish(&mut self, id: &str, state: State, superseded_by: Option) -> Option { + let entry = self.pending.remove(id)?; + self.done.insert( + id.to_string(), + Done { + state, + identity: entry.identity.clone(), + superseded_by, + }, + ); + self.done_order.push_back(id.to_string()); + while self.done_order.len() > DONE_MAX { + if let Some(old) = self.done_order.pop_front() { + self.done.remove(&old); + } + } + Some(entry) + } +} + +/// Entries, cooldowns and the equality key, behind one mutex. +pub struct Table { + limits: Limits, + fingerprinter: digest::Fingerprinter, + inner: Mutex, +} + +impl fmt::Debug for Table { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Table") + .field("limits", &self.limits) + .field("pending", &self.pending_len()) + .finish_non_exhaustive() + } +} + +impl Table { + pub fn new(limits: Limits) -> Table { + Table { + limits, + fingerprinter: digest::Fingerprinter::new(), + inner: Mutex::new(Inner { + pending: HashMap::new(), + done: HashMap::new(), + done_order: VecDeque::new(), + cooldown: HashMap::new(), + closed: false, + }), + } + } + + pub fn limits(&self) -> &Limits { + &self.limits + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + match self.inner.lock() { + Ok(g) => g, + Err(poisoned) => poisoned.into_inner(), + } + } + + /// Number of `Pending` entries. + pub fn pending_len(&self) -> usize { + self.lock().pending.len() + } + + /// The state of `id`, if the table still knows it. + pub fn state(&self, id: &str) -> Option { + let g = self.lock(); + if g.pending.contains_key(id) { + Some(State::Pending) + } else { + g.done.get(id).map(|d| d.state) + } + } + + fn start_cooldown(&self, g: &mut Inner, identity: &str) { + if !self.limits.cooldown.is_zero() { + g.cooldown + .insert(identity.to_string(), Instant::now() + self.limits.cooldown); + } + } + + /// Admit a new hold, in the order of design 3.4 step 5: cooldown, then dedupe, then the caps. + /// + /// `persist` writes the fallible `held` audit record. It runs under the table lock, after + /// every check passed and before anything changes, so a failure refuses with + /// `audit_unavailable` and leaves the table as it was: no entry, no supersede, no cooldown. + /// It receives the new id and the audit digest and must not call back into the table. + pub fn admit(&self, identity: &str, req: Arc, persist: F) -> Admission + where + F: FnOnce(&str, &str) -> io::Result<()>, + { + let fingerprint = self.fingerprinter.fingerprint(&req); + let digest = digest::audit_digest(&req); + let now = Instant::now(); + let mut g = self.lock(); + if g.closed { + return Admission::Refused(Code::Shutdown); + } + g.cooldown.retain(|_, until| *until > now); + if g.cooldown.contains_key(identity) { + return Admission::Refused(Code::Cooldown); + } + let duplicate = g + .pending + .iter() + .find(|(_, e)| e.identity == identity && e.fingerprint == fingerprint) + .map(|(id, _)| id.clone()); + if duplicate.is_none() { + let own = g + .pending + .values() + .filter(|e| e.identity == identity) + .count(); + if own >= self.limits.max_per_identity { + return Admission::Refused(Code::IdentityCap); + } + if g.pending.len() >= self.limits.max_total { + return Admission::Refused(Code::TableFull); + } + } + let id = digest::random_hex(16); + if persist(&id, &digest).is_err() { + return Admission::Refused(Code::AuditUnavailable); + } + if let Some(old_id) = &duplicate { + if let Some(mut old) = g.finish(old_id, State::Superseded, Some(id.clone())) { + if let Some(tx) = old.tx.take() { + let _ = tx.send(Decision::Superseded { newest: id.clone() }); + } + } + // Older tombstones that pointed at the replaced entry now point at the newest one. + for d in g.done.values_mut() { + if d.superseded_by.as_deref() == Some(old_id.as_str()) { + d.superseded_by = Some(id.clone()); + } + } + } + let (tx, rx) = oneshot::channel(); + g.pending.insert( + id.clone(), + Entry { + identity: identity.to_string(), + fingerprint, + digest: digest.clone(), + req, + tx: Some(tx), + }, + ); + Admission::Held(Held { + id, + digest, + decision: rx, + superseded: duplicate, + }) + } + + /// Approve `id` for `approver` and wait for the handler's confirmation. + /// + /// The first transition out of `Pending` wins, so two concurrent approves give one result + /// from the handler and `AlreadyDecided` for the other. + pub async fn approve(&self, id: &str, approver: &str) -> ApproveResult { + let confirmed = { + let mut g = self.lock(); + match g.finish(id, State::Approved, None) { + Some(mut entry) => { + let (ctx, crx) = oneshot::channel(); + let decision = Decision::Approved { + approver: approver.to_string(), + confirm: ConfirmTx(ctx), + }; + match entry.tx.take().map(|tx| tx.send(decision)) { + Some(Ok(())) => crx, + // The handler is already gone, so nothing can be sent. + _ => return ApproveResult::ApprovedButAbandoned, + } + } + None => return Self::approve_when_decided(&g, id), + } + }; + match tokio::time::timeout(CONFIRM_TIMEOUT, confirmed).await { + Ok(Ok(Confirm::Started)) => ApproveResult::Success, + Ok(Ok(Confirm::Abandoned)) | Ok(Err(_)) => ApproveResult::ApprovedButAbandoned, + Ok(Ok(Confirm::AuditUnavailable)) => ApproveResult::AuditUnavailable, + Ok(Ok(Confirm::ConnectFailed)) => ApproveResult::ConnectFailed, + Err(_) => ApproveResult::ApprovedUnconfirmed, + } + } + + fn approve_when_decided(g: &Inner, id: &str) -> ApproveResult { + match g.done.get(id) { + None => ApproveResult::NotFound, + Some(d) => match d.state { + State::Approved | State::Denied | State::Pending => ApproveResult::AlreadyDecided, + State::Expired => ApproveResult::Expired, + State::Dropped => ApproveResult::Dropped, + State::Abandoned => ApproveResult::Gone, + State::Superseded => ApproveResult::Superseded { + newest: d.superseded_by.clone().unwrap_or_default(), + }, + }, + } + } + + /// Deny `id`. A human deny starts the identity's cooldown and frees the slot at once. + pub fn deny(&self, id: &str, approver: &str) -> DenyResult { + let mut g = self.lock(); + match g.finish(id, State::Denied, None) { + Some(mut entry) => { + self.start_cooldown(&mut g, &entry.identity); + if let Some(tx) = entry.tx.take() { + let _ = tx.send(Decision::Denied { + approver: approver.to_string(), + }); + } + DenyResult::Denied + } + None => match g.done.get(id) { + None => DenyResult::NotFound, + Some(d) => match d.state { + State::Approved | State::Denied | State::Pending => DenyResult::AlreadyDecided, + State::Expired => DenyResult::Expired, + State::Dropped => DenyResult::Dropped, + State::Abandoned => DenyResult::Gone, + State::Superseded => DenyResult::Superseded { + newest: d.superseded_by.clone().unwrap_or_default(), + }, + }, + }, + } + } + + /// `hold_secs` elapsed. Called by the handler whose timer fired. Returns `true` when the + /// entry moved to `Expired`, which also starts the cooldown; `false` means another + /// transition won first and the decision is already in the handler's channel. + pub fn expire(&self, id: &str) -> bool { + let mut g = self.lock(); + match g.finish(id, State::Expired, None) { + Some(entry) => { + self.start_cooldown(&mut g, &entry.identity); + true + } + None => false, + } + } + + /// The caller went away. Called from the handler's drop guard. Returns `true` when the entry + /// moved to `Abandoned`; `false` when a decision already won (the handler then sees it as + /// `abandoned_after_approve`, or has nothing to do). No cooldown. + pub fn abandon(&self, id: &str) -> bool { + self.lock().finish(id, State::Abandoned, None).is_some() + } + + fn drop_where(&self, mut pred: P, decision: D) -> usize + where + P: FnMut(&str) -> bool, + D: Fn() -> Decision, + { + let mut g = self.lock(); + let ids: Vec = g + .pending + .iter() + .filter(|(_, e)| pred(&e.identity)) + .map(|(id, _)| id.clone()) + .collect(); + for id in &ids { + if let Some(mut e) = g.finish(id, State::Dropped, None) { + if let Some(tx) = e.tx.take() { + let _ = tx.send(decision()); + } + } + } + ids.len() + } + + /// A policy reload kept only the identities in `present`: drop the `Pending` entries of the + /// others. Entries of identities that remain are untouched. Returns the number dropped. + pub fn drop_identities_missing(&self, present: &HashSet) -> usize { + self.drop_where(|identity| !present.contains(identity), || Decision::Dropped) + } + + /// The policy file went away: drop every `Pending` entry. + pub fn drop_all(&self) -> usize { + self.drop_where(|_| true, || Decision::Dropped) + } + + /// Shutdown: answer every `Pending` entry `Shutdown` and refuse new admissions. Entries past + /// approval are not in the table any more and run on in their handlers. + pub fn drain_pending(&self) -> usize { + self.lock().closed = true; + self.drop_where(|_| true, || Decision::Shutdown) + } + + /// What the approval API may show about `id`. Credential header values are left out, and + /// request content is present only while the entry is `Pending`. + pub fn view(&self, id: &str) -> Option { + let g = self.lock(); + if let Some(e) = g.pending.get(id) { + let req = &e.req; + let content_type = req + .headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case("content-type")) + .map(|(_, v)| String::from_utf8_lossy(v).into_owned()); + let body_text = String::from_utf8_lossy(&req.body); + let body_lossy = std::str::from_utf8(&req.body).is_err(); + let headers = req + .headers + .iter() + .map(|(n, v)| ViewHeader { + name: n.clone(), + value: if HeldRequest::is_credential(n) { + None + } else { + Some(String::from_utf8_lossy(v).into_owned()) + }, + }) + .collect(); + return Some(View { + id: id.to_string(), + state: State::Pending, + identity: e.identity.clone(), + superseded_by: None, + content: Some(ViewContent { + method: req.method.clone(), + route: req.route.clone(), + path: redact_path(&req.path), + query: req.query.clone(), + content_type, + body_len: req.body.len(), + body_text: body_text.into_owned(), + body_lossy, + digest: e.digest.clone(), + headers, + }), + }); + } + g.done.get(id).map(|d| View { + id: id.to_string(), + state: d.state, + identity: d.identity.clone(), + superseded_by: d.superseded_by.clone(), + content: None, + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ap-proxy/src/hold/tests.rs b/crates/ap-proxy/src/hold/tests.rs new file mode 100644 index 0000000..48c7960 --- /dev/null +++ b/crates/ap-proxy/src/hold/tests.rs @@ -0,0 +1,704 @@ +//! Deterministic tests for the hold table. Time is paused, so the 2 s confirm window and the +//! cooldown run on the virtual clock. + +use std::collections::HashSet; +use std::io; +use std::sync::Arc; +use std::time::Duration; + +use bytes::Bytes; +use tokio::sync::oneshot::error::TryRecvError; + +use super::*; + +const SECRET_AUTH: &str = "Bot SENTINEL-AUTH-VALUE"; +const SECRET_BODY: &str = "SENTINEL-BODY-TEXT"; +const SECRET_KEY: &str = "SENTINEL-API-KEY"; + +fn limits(total: usize, per: usize, cooldown_secs: u64) -> Limits { + Limits { + hold: Duration::from_secs(120), + max_total: total, + max_per_identity: per, + cooldown: Duration::from_secs(cooldown_secs), + } +} + +fn table(total: usize, per: usize, cooldown_secs: u64) -> Arc { + Arc::new(Table::new(limits(total, per, cooldown_secs))) +} + +fn req(auth: &str, body: &str) -> Arc { + Arc::new(HeldRequest { + method: "POST".into(), + route: "discord".into(), + path: "/channels/1/messages".into(), + query: Some("wait=true".into()), + headers: vec![ + ("authorization".into(), auth.as_bytes().to_vec()), + ("content-type".into(), b"application/json".to_vec()), + ("x-api-key".into(), SECRET_KEY.as_bytes().to_vec()), + ], + body: Bytes::copy_from_slice(body.as_bytes()), + }) +} + +fn ok(_: &str, _: &str) -> io::Result<()> { + Ok(()) +} + +fn admit(t: &Table, identity: &str, r: Arc) -> Admission { + t.admit(identity, r, ok) +} + +fn held(t: &Table, identity: &str, r: Arc) -> Held { + match admit(t, identity, r) { + Admission::Held(h) => h, + Admission::Refused(c) => panic!("refused: {}", c.code_str()), + } +} + +fn refused(a: Admission) -> Code { + match a { + Admission::Refused(c) => c, + Admission::Held(h) => panic!("held {}", h.id), + } +} + +/// How a simulated handler answers an approve. +#[derive(Clone, Copy)] +enum Mode { + Send(Confirm), + DropIt, + /// Keep the confirm sender alive and never answer. + Hold, +} + +/// Run a handler for `h` that answers an approve as `mode`. The task returns the decision label. +fn handler(h: Held, mode: Mode) -> tokio::task::JoinHandle<&'static str> { + tokio::spawn(async move { + match h.decision.await { + Ok(Decision::Approved { confirm, .. }) => { + match mode { + Mode::Send(c) => confirm.send(c), + Mode::DropIt => drop(confirm), + Mode::Hold => std::future::pending::<()>().await, + } + "approved" + } + Ok(Decision::Denied { .. }) => "denied", + Ok(Decision::Superseded { .. }) => "superseded", + Ok(Decision::Dropped) => "dropped", + Ok(Decision::Shutdown) => "shutdown", + Err(_) => "no_decision", + } + }) +} + +// ---- state machine ------------------------------------------------------------------------- + +#[tokio::test(start_paused = true)] +async fn approve_success_then_already_decided() { + let t = table(8, 4, 60); + let h = held(&t, "muse", req(SECRET_AUTH, "a")); + let id = h.id.clone(); + let task = handler(h, Mode::Send(Confirm::Started)); + assert_eq!(t.approve(&id, "alice").await, ApproveResult::Success); + assert_eq!(task.await.unwrap(), "approved"); + assert_eq!(t.state(&id), Some(State::Approved)); + assert_eq!(t.approve(&id, "alice").await, ApproveResult::AlreadyDecided); + assert_eq!(t.deny(&id, "alice"), DenyResult::AlreadyDecided); + assert!(!t.expire(&id)); + assert!(!t.abandon(&id)); + assert_eq!(t.pending_len(), 0); +} + +#[tokio::test(start_paused = true)] +async fn approve_result_rows() { + // Approved, handler answers Abandoned before milestone 2. + let t = table(8, 4, 0); + let h = held(&t, "muse", req(SECRET_AUTH, "1")); + let id = h.id.clone(); + let _task = handler(h, Mode::Send(Confirm::Abandoned)); + assert_eq!( + t.approve(&id, "a").await, + ApproveResult::ApprovedButAbandoned + ); + + // Approved, handler drops the confirm sender. + let h = held(&t, "muse", req(SECRET_AUTH, "2")); + let id = h.id.clone(); + let _task = handler(h, Mode::DropIt); + assert_eq!( + t.approve(&id, "a").await, + ApproveResult::ApprovedButAbandoned + ); + + // Approved, handler future already gone (decision receiver dropped). + let h = held(&t, "muse", req(SECRET_AUTH, "3")); + let id = h.id.clone(); + drop(h.decision); + assert_eq!( + t.approve(&id, "a").await, + ApproveResult::ApprovedButAbandoned + ); + assert!(!t.abandon(&id), "the approve already won"); + assert_eq!(t.state(&id), Some(State::Approved)); + + // Approved, no confirmation within 2 s. + let h = held(&t, "muse", req(SECRET_AUTH, "4")); + let id = h.id.clone(); + let _task = handler(h, Mode::Hold); + let before = tokio::time::Instant::now(); + assert_eq!( + t.approve(&id, "a").await, + ApproveResult::ApprovedUnconfirmed + ); + assert_eq!(before.elapsed(), CONFIRM_TIMEOUT); + + // Approved, audit write failed / connect failed. + let h = held(&t, "muse", req(SECRET_AUTH, "5")); + let id = h.id.clone(); + let _task = handler(h, Mode::Send(Confirm::AuditUnavailable)); + assert_eq!(t.approve(&id, "a").await, ApproveResult::AuditUnavailable); + let h = held(&t, "muse", req(SECRET_AUTH, "6")); + let id = h.id.clone(); + let _task = handler(h, Mode::Send(Confirm::ConnectFailed)); + assert_eq!(t.approve(&id, "a").await, ApproveResult::ConnectFailed); +} + +#[tokio::test(start_paused = true)] +async fn approve_rows_for_decided_states() { + let t = table(8, 4, 0); + + let h = held(&t, "muse", req(SECRET_AUTH, "denied")); + let id = h.id.clone(); + assert_eq!(t.deny(&id, "bob"), DenyResult::Denied); + assert_eq!(t.approve(&id, "a").await, ApproveResult::AlreadyDecided); + assert_eq!(t.deny(&id, "bob"), DenyResult::AlreadyDecided); + + let h = held(&t, "muse", req(SECRET_AUTH, "expired")); + let id = h.id.clone(); + assert!(t.expire(&id)); + assert_eq!(t.approve(&id, "a").await, ApproveResult::Expired); + assert_eq!(t.deny(&id, "a"), DenyResult::Expired); + assert!(!t.expire(&id), "a second expire does nothing"); + + let h = held(&t, "muse", req(SECRET_AUTH, "abandoned")); + let id = h.id.clone(); + assert!(t.abandon(&id)); + assert_eq!(t.approve(&id, "a").await, ApproveResult::Gone); + assert_eq!(t.deny(&id, "a"), DenyResult::Gone); + + let h = held(&t, "other", req(SECRET_AUTH, "dropped")); + let id = h.id.clone(); + assert_eq!(t.drop_identities_missing(&HashSet::new()), 1); + assert_eq!(t.approve(&id, "a").await, ApproveResult::Dropped); + assert_eq!(t.deny(&id, "a"), DenyResult::Dropped); + + assert_eq!(t.approve("no-such-id", "a").await, ApproveResult::NotFound); + assert_eq!(t.deny("no-such-id", "a"), DenyResult::NotFound); + drop(h.decision); +} + +#[tokio::test(start_paused = true)] +async fn approve_on_superseded_names_the_newest_entry() { + let t = table(8, 4, 60); + let first = held(&t, "muse", req(SECRET_AUTH, "same")); + let first_id = first.id.clone(); + let second = held(&t, "muse", req(SECRET_AUTH, "same")); + assert_eq!(second.superseded.as_deref(), Some(first_id.as_str())); + assert_eq!( + t.approve(&first_id, "a").await, + ApproveResult::Superseded { + newest: second.id.clone() + } + ); + assert_eq!( + t.deny(&first_id, "a"), + DenyResult::Superseded { + newest: second.id.clone() + } + ); + assert_eq!(t.state(&first_id), Some(State::Superseded)); + assert_eq!(t.state(&second.id), Some(State::Pending)); +} + +#[tokio::test(start_paused = true)] +async fn each_transition_order_has_one_winner() { + #[derive(Clone, Copy)] + enum Act { + Approve, + Deny, + Expire, + } + use Act::*; + let orders = [ + [Approve, Deny, Expire], + [Approve, Expire, Deny], + [Deny, Approve, Expire], + [Deny, Expire, Approve], + [Expire, Approve, Deny], + [Expire, Deny, Approve], + ]; + for order in orders { + let t = table(8, 4, 0); + let h = held(&t, "muse", req(SECRET_AUTH, "race")); + let id = h.id.clone(); + let _handler = handler(h, Mode::Send(Confirm::Started)); + let mut tasks = Vec::new(); + for act in order { + let t = t.clone(); + let id = id.clone(); + tasks.push(tokio::spawn(async move { + match act { + Approve => t.approve(&id, "a").await == ApproveResult::Success, + Deny => t.deny(&id, "a") == DenyResult::Denied, + Expire => t.expire(&id), + } + })); + } + let mut wins = 0; + for task in tasks { + if task.await.unwrap() { + wins += 1; + } + } + assert_eq!(wins, 1, "exactly one of approve, deny and expire wins"); + assert_eq!(t.pending_len(), 0); + } +} + +#[tokio::test(start_paused = true)] +async fn two_concurrent_approves_one_success_one_already_decided() { + let t = table(8, 4, 60); + let h = held(&t, "muse", req(SECRET_AUTH, "x")); + let id = h.id.clone(); + let _handler = handler(h, Mode::Send(Confirm::Started)); + let a = { + let (t, id) = (t.clone(), id.clone()); + tokio::spawn(async move { t.approve(&id, "a").await }) + }; + let b = { + let (t, id) = (t.clone(), id.clone()); + tokio::spawn(async move { t.approve(&id, "b").await }) + }; + let mut got = vec![a.await.unwrap(), b.await.unwrap()]; + got.sort_by_key(|r| r.as_str()); + assert_eq!( + got, + vec![ApproveResult::AlreadyDecided, ApproveResult::Success] + ); +} + +#[tokio::test(start_paused = true)] +async fn expire_and_abandon_send_no_decision_but_free_the_slot() { + let t = table(8, 1, 0); + let mut h = held(&t, "muse", req(SECRET_AUTH, "e")); + assert!(t.expire(&h.id)); + assert!(matches!(h.decision.try_recv(), Err(TryRecvError::Closed))); + let mut h2 = held(&t, "muse", req(SECRET_AUTH, "f")); + assert!(t.abandon(&h2.id)); + assert!(matches!(h2.decision.try_recv(), Err(TryRecvError::Closed))); + assert_eq!(t.pending_len(), 0); +} + +// ---- admission ----------------------------------------------------------------------------- + +#[tokio::test(start_paused = true)] +async fn ten_rapid_retries_leave_one_entry() { + let t = table(8, 4, 60); + let mut all: Vec = Vec::new(); + for _ in 0..10 { + all.push(held(&t, "muse", req(SECRET_AUTH, "same"))); + } + assert_eq!(t.pending_len(), 1); + assert!(all[0].superseded.is_none(), "only the first one notifies"); + for i in 1..10 { + assert_eq!(all[i].superseded.as_deref(), Some(all[i - 1].id.as_str())); + } + let ids: Vec = all.iter().map(|h| h.id.clone()).collect(); + for (i, h) in all.iter_mut().enumerate().take(9) { + match h.decision.try_recv() { + Ok(Decision::Superseded { newest }) => assert_eq!(newest, ids[i + 1], "entry {i}"), + other => panic!("entry {i}: {other:?}"), + } + } + assert!(matches!( + all[9].decision.try_recv(), + Err(TryRecvError::Empty) + )); + // Every older id resolves to the newest entry, not just to its direct replacement. + for old in &ids[..9] { + assert_eq!( + t.approve(old, "a").await, + ApproveResult::Superseded { + newest: ids[9].clone() + } + ); + } +} + +#[tokio::test(start_paused = true)] +async fn changed_authorization_is_a_distinct_entry() { + let t = table(8, 4, 60); + let a = held(&t, "muse", req("Bot ONE", "same")); + let b = held(&t, "muse", req("Bot TWO", "same")); + assert!(b.superseded.is_none()); + assert_ne!(a.id, b.id); + assert_eq!(t.pending_len(), 2); + assert_eq!(t.state(&a.id), Some(State::Pending)); + // The audit digest is credential-blind, so it is the same for both. + assert_eq!(a.digest, b.digest); +} + +#[tokio::test(start_paused = true)] +async fn same_body_for_another_identity_is_not_a_duplicate() { + let t = table(8, 4, 60); + let a = held(&t, "muse", req(SECRET_AUTH, "same")); + let b = held(&t, "other", req(SECRET_AUTH, "same")); + assert!(b.superseded.is_none()); + assert_eq!(t.state(&a.id), Some(State::Pending)); + assert_eq!(t.pending_len(), 2); +} + +#[tokio::test(start_paused = true)] +async fn caps_per_identity_then_total() { + let t = table(3, 2, 60); + let _a = held(&t, "muse", req(SECRET_AUTH, "1")); + let _b = held(&t, "muse", req(SECRET_AUTH, "2")); + assert_eq!( + refused(admit(&t, "muse", req(SECRET_AUTH, "3"))), + Code::IdentityCap + ); + let _c = held(&t, "other", req(SECRET_AUTH, "4")); + assert_eq!( + refused(admit(&t, "other", req(SECRET_AUTH, "5"))), + Code::TableFull + ); + // An identity at both caps reports the per-identity cap first. + let t = table(2, 2, 60); + let _a = held(&t, "muse", req(SECRET_AUTH, "1")); + let _b = held(&t, "muse", req(SECRET_AUTH, "2")); + assert_eq!( + refused(admit(&t, "muse", req(SECRET_AUTH, "3"))), + Code::IdentityCap + ); + assert_eq!(t.pending_len(), 2); +} + +#[tokio::test(start_paused = true)] +async fn identical_retry_at_a_cap_supersedes() { + let t = table(2, 2, 60); + let a = held(&t, "muse", req(SECRET_AUTH, "1")); + let _b = held(&t, "muse", req(SECRET_AUTH, "2")); + // Per-identity and total caps are both full; the identical retry is not counted. + let again = held(&t, "muse", req(SECRET_AUTH, "1")); + assert_eq!(again.superseded.as_deref(), Some(a.id.as_str())); + assert_eq!(t.pending_len(), 2); + assert_eq!(t.state(&a.id), Some(State::Superseded)); +} + +#[tokio::test(start_paused = true)] +async fn deny_and_expire_free_the_slot_at_once() { + let t = table(8, 1, 0); + let a = held(&t, "muse", req(SECRET_AUTH, "1")); + assert_eq!( + refused(admit(&t, "muse", req(SECRET_AUTH, "2"))), + Code::IdentityCap + ); + assert_eq!(t.deny(&a.id, "bob"), DenyResult::Denied); + let b = held(&t, "muse", req(SECRET_AUTH, "2")); + assert!(t.expire(&b.id)); + let _c = held(&t, "muse", req(SECRET_AUTH, "3")); +} + +#[tokio::test(start_paused = true)] +async fn approved_entry_no_longer_counts_against_the_caps() { + let t = table(8, 1, 0); + let a = held(&t, "muse", req(SECRET_AUTH, "1")); + let id = a.id.clone(); + let _handler = handler(a, Mode::Send(Confirm::Started)); + assert_eq!(t.approve(&id, "a").await, ApproveResult::Success); + let _b = held(&t, "muse", req(SECRET_AUTH, "2")); +} + +// ---- cooldown ------------------------------------------------------------------------------ + +#[tokio::test(start_paused = true)] +async fn deny_starts_a_cooldown_that_ends() { + let t = table(8, 4, 60); + let a = held(&t, "muse", req(SECRET_AUTH, "1")); + assert_eq!(t.deny(&a.id, "bob"), DenyResult::Denied); + assert_eq!(t.pending_len(), 0, "the slot is free at once"); + assert_eq!( + refused(admit(&t, "muse", req(SECRET_AUTH, "1"))), + Code::Cooldown + ); + assert_eq!( + refused(admit(&t, "muse", req(SECRET_AUTH, "other body"))), + Code::Cooldown + ); + let _elsewhere = held(&t, "other", req(SECRET_AUTH, "1")); + tokio::time::advance(Duration::from_secs(59)).await; + assert_eq!( + refused(admit(&t, "muse", req(SECRET_AUTH, "1"))), + Code::Cooldown + ); + tokio::time::advance(Duration::from_secs(2)).await; + let _again = held(&t, "muse", req(SECRET_AUTH, "1")); +} + +#[tokio::test(start_paused = true)] +async fn expiry_starts_a_cooldown() { + let t = table(8, 4, 60); + let a = held(&t, "muse", req(SECRET_AUTH, "1")); + assert!(t.expire(&a.id)); + assert_eq!( + refused(admit(&t, "muse", req(SECRET_AUTH, "2"))), + Code::Cooldown + ); +} + +#[tokio::test(start_paused = true)] +async fn cooldown_zero_disables_it() { + let t = table(8, 4, 0); + let a = held(&t, "muse", req(SECRET_AUTH, "1")); + assert_eq!(t.deny(&a.id, "bob"), DenyResult::Denied); + let _b = held(&t, "muse", req(SECRET_AUTH, "1")); +} + +#[tokio::test(start_paused = true)] +async fn only_deny_and_expiry_start_a_cooldown() { + let t = table(8, 4, 60); + + let a = held(&t, "muse", req(SECRET_AUTH, "abandon")); + assert!(t.abandon(&a.id)); + let b = held(&t, "muse", req(SECRET_AUTH, "approve")); + let b_id = b.id.clone(); + let _h = handler(b, Mode::Send(Confirm::Started)); + assert_eq!(t.approve(&b_id, "a").await, ApproveResult::Success); + let _c = held(&t, "muse", req(SECRET_AUTH, "supersede")); + let _d = held(&t, "muse", req(SECRET_AUTH, "supersede")); + assert_eq!(t.drop_all(), 1); + let _e = held(&t, "muse", req(SECRET_AUTH, "after reload drop")); + + // A failed audit write is not the identity's doing. + let t2 = table(8, 4, 60); + let failing = t2.admit("muse", req(SECRET_AUTH, "x"), |_, _| { + Err(io::Error::other("disk")) + }); + assert_eq!(refused(failing), Code::AuditUnavailable); + let _ok = held(&t2, "muse", req(SECRET_AUTH, "x")); +} + +#[tokio::test(start_paused = true)] +async fn cooldown_beats_duplicate_and_leaves_pending_entries() { + let t = table(8, 4, 60); + let a = held(&t, "muse", req(SECRET_AUTH, "keeps waiting")); + let b = held(&t, "muse", req(SECRET_AUTH, "gets denied")); + assert_eq!(t.deny(&b.id, "bob"), DenyResult::Denied); + + // An identical retry of the still-pending `a` hits the cooldown first; it does not supersede. + assert_eq!( + refused(admit(&t, "muse", req(SECRET_AUTH, "keeps waiting"))), + Code::Cooldown + ); + assert_eq!(t.state(&a.id), Some(State::Pending)); + let a_id = a.id.clone(); + let _h = handler(a, Mode::Send(Confirm::Started)); + assert_eq!(t.approve(&a_id, "alice").await, ApproveResult::Success); +} + +// ---- audit-before-insert ------------------------------------------------------------------- + +#[tokio::test(start_paused = true)] +async fn failed_persist_changes_nothing() { + let t = table(8, 4, 60); + let mut old = held(&t, "muse", req(SECRET_AUTH, "same")); + let r = t.admit("muse", req(SECRET_AUTH, "same"), |_, _| { + Err(io::Error::other("sink down")) + }); + assert_eq!(refused(r), Code::AuditUnavailable); + assert_eq!(t.pending_len(), 1); + assert_eq!(t.state(&old.id), Some(State::Pending), "no supersede"); + assert!(matches!(old.decision.try_recv(), Err(TryRecvError::Empty))); +} + +#[tokio::test(start_paused = true)] +async fn persist_sees_the_id_and_digest_of_the_new_entry() { + let t = table(8, 4, 60); + let mut seen = None; + let r = t.admit("muse", req(SECRET_AUTH, "x"), |id, digest| { + seen = Some((id.to_string(), digest.to_string())); + Ok(()) + }); + let Admission::Held(h) = r else { + panic!("not held") + }; + assert_eq!(seen, Some((h.id.clone(), h.digest.clone()))); + assert_eq!(h.id.len(), 32); + assert_eq!(h.digest.len(), 64); + assert!(!h.digest.contains("SENTINEL")); +} + +#[tokio::test(start_paused = true)] +async fn persist_is_not_called_for_a_refusal() { + let t = table(1, 1, 60); + let _a = held(&t, "muse", req(SECRET_AUTH, "1")); + let mut called = false; + let r = t.admit("muse", req(SECRET_AUTH, "2"), |_, _| { + called = true; + Ok(()) + }); + assert_eq!(refused(r), Code::IdentityCap); + assert!(!called, "no held record for a refused request"); +} + +// ---- reload and shutdown ------------------------------------------------------------------ + +#[tokio::test(start_paused = true)] +async fn reload_drops_only_the_identities_that_are_gone() { + let t = table(8, 4, 60); + let a = held(&t, "gone", req(SECRET_AUTH, "1")); + let a2 = held(&t, "gone", req(SECRET_AUTH, "2")); + let b = held(&t, "stays", req(SECRET_AUTH, "1")); + let present: HashSet = ["stays".to_string()].into_iter().collect(); + assert_eq!(t.drop_identities_missing(&present), 2); + assert_eq!(t.state(&a.id), Some(State::Dropped)); + assert_eq!(t.state(&a2.id), Some(State::Dropped)); + assert_eq!(t.state(&b.id), Some(State::Pending)); + assert_eq!(t.pending_len(), 1); + assert_eq!(handler(a, Mode::DropIt).await.unwrap(), "dropped"); + // No cooldown: the identity did nothing wrong. + let _again = held(&t, "gone", req(SECRET_AUTH, "1")); + // Nothing more to drop for an unchanged set. + assert_eq!(t.drop_identities_missing(&present), 1); +} + +#[tokio::test(start_paused = true)] +async fn drain_answers_shutdown_and_closes_admission() { + let t = table(8, 4, 60); + let a = held(&t, "muse", req(SECRET_AUTH, "1")); + let b = held(&t, "other", req(SECRET_AUTH, "1")); + assert_eq!(t.drain_pending(), 2); + assert_eq!(handler(a, Mode::DropIt).await.unwrap(), "shutdown"); + assert_eq!(handler(b, Mode::DropIt).await.unwrap(), "shutdown"); + assert_eq!(t.pending_len(), 0); + assert_eq!( + refused(admit(&t, "muse", req(SECRET_AUTH, "2"))), + Code::Shutdown + ); +} + +#[tokio::test(start_paused = true)] +async fn tombstones_are_bounded() { + let t = table(8, 4, 0); + let first = held(&t, "muse", req(SECRET_AUTH, "first")); + assert_eq!(t.deny(&first.id, "a"), DenyResult::Denied); + for i in 0..1100 { + let h = held(&t, "muse", req(SECRET_AUTH, &format!("n{i}"))); + assert!(t.abandon(&h.id)); + } + assert_eq!( + t.state(&first.id), + None, + "the oldest tombstone was forgotten" + ); + assert_eq!(t.approve(&first.id, "a").await, ApproveResult::NotFound); +} + +// ---- view and Debug ------------------------------------------------------------------------ + +#[tokio::test(start_paused = true)] +async fn view_omits_credential_values_and_redacts_the_path() { + let t = table(8, 4, 60); + let mut r = (*req(SECRET_AUTH, SECRET_BODY)).clone(); + r.path = "/webhooks/123/WEBHOOK-TOKEN/messages".into(); + r.headers.push(("x-custom".into(), b"visible".to_vec())); + r.headers + .push(("cookie".into(), b"session=COOKIE-VALUE".to_vec())); + let h = held(&t, "muse", Arc::new(r)); + let v = t.view(&h.id).unwrap(); + assert_eq!(v.state, State::Pending); + let c = v.content.as_ref().unwrap(); + assert_eq!(c.path, "/webhooks/123//messages"); + assert_eq!(c.query.as_deref(), Some("wait=true")); + assert_eq!(c.content_type.as_deref(), Some("application/json")); + assert_eq!(c.body_len, SECRET_BODY.len()); + assert_eq!(c.body_text, SECRET_BODY); + assert!(!c.body_lossy); + assert_eq!(c.digest, h.digest); + for hd in &c.headers { + match hd.name.as_str() { + "authorization" | "x-api-key" | "cookie" => assert!(hd.value.is_none(), "{}", hd.name), + "content-type" | "x-custom" => assert!(hd.value.is_some(), "{}", hd.name), + other => panic!("unexpected header {other}"), + } + } + assert!(!c.headers.iter().any(|h| h + .value + .as_deref() + .is_some_and(|v| v.contains("SENTINEL") || v.contains("COOKIE-VALUE")))); +} + +#[tokio::test(start_paused = true)] +async fn view_marks_a_body_that_is_not_utf8() { + let t = table(8, 4, 60); + let mut r = (*req(SECRET_AUTH, "")).clone(); + r.body = Bytes::from_static(&[0x7b, 0xff, 0xfe, 0x7d]); + let h = held(&t, "muse", Arc::new(r)); + let c = t.view(&h.id).unwrap().content.unwrap(); + assert!(c.body_lossy); + assert_eq!(c.body_len, 4); +} + +#[tokio::test(start_paused = true)] +async fn view_of_a_decided_entry_has_no_content() { + let t = table(8, 4, 60); + let a = held(&t, "muse", req(SECRET_AUTH, "same")); + let b = held(&t, "muse", req(SECRET_AUTH, "same")); + let v = t.view(&a.id).unwrap(); + assert_eq!(v.state, State::Superseded); + assert_eq!(v.superseded_by.as_deref(), Some(b.id.as_str())); + assert!(v.content.is_none()); + assert!(t.view("unknown").is_none()); +} + +#[tokio::test(start_paused = true)] +async fn no_secret_or_fingerprint_in_any_debug_output() { + let t = table(8, 4, 60); + let r = req(SECRET_AUTH, SECRET_BODY); + let fp = t.fingerprinter.fingerprint(&r).hex_for_test(); + let h = held(&t, "muse", r.clone()); + let view = t.view(&h.id).unwrap(); + let mut shown = String::new(); + shown.push_str(&format!( + "{r:?}\n{t:?}\n{h:?}\n{view:?}\n{:?}\n", + view.content + )); + shown.push_str(&format!("{:?}\n", view.content.as_ref().unwrap().headers)); + { + let g = t.lock(); + for e in g.pending.values() { + shown.push_str(&format!("{e:?}\n{:?}\n", e.fingerprint)); + } + } + shown.push_str(&format!("{:?}\n", t.fingerprinter)); + let id = h.id.clone(); + let task = handler(h, Mode::Send(Confirm::Started)); + // The decision types hold the approver name and a sender, never the request. + assert_eq!(t.approve(&id, "alice").await, ApproveResult::Success); + task.await.unwrap(); + shown.push_str(&format!("{:?}\n", Admission::Refused(Code::Cooldown))); + for secret in [ + SECRET_AUTH, + "SENTINEL", + SECRET_BODY, + SECRET_KEY, + fp.as_str(), + ] { + assert!(!shown.contains(secret), "Debug leaked {secret}"); + } + assert!(shown.contains("Fingerprint(..)")); +} diff --git a/crates/ap-proxy/src/lib.rs b/crates/ap-proxy/src/lib.rs index cf83ea2..500e8a1 100644 --- a/crates/ap-proxy/src/lib.rs +++ b/crates/ap-proxy/src/lib.rs @@ -7,6 +7,7 @@ pub mod admin_http; pub mod audit_sink; pub mod evidence; pub mod forward; +pub mod hold; pub mod listener; #[cfg(feature = "matrix-upstream")] pub mod matrix_hooks; From 83bd421d57dcaeec0ff11e8a6becf42b8d3f5534 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:58:17 -0500 Subject: [PATCH 03/16] feat(ap-proxy): hold path in the passthrough pipeline A hold grant now buffers the request, parks it in the hold table and forwards it only after a human approves it (design 3.4, 3.5, 3.9). - passthrough/hold_path.rs: content-type, content-encoding, credential, declared-length and buffered-body checks; admission with the fallible `held` audit write; wait on decision, hold timer or caller drop (guard moves Pending to Abandoned); deny 423, expiry 410, superseded, dropped and shutdown 503; approved forward with two milestones, fallible `forward_started`, `completed` on the response stream, no synthetic answer after a reset. - forward: buffer_body, drain_body, held client (HTTP/1.1, no idle pool). - refusals after caller auth drain the unread body first (skipped for Expect: 100-continue), so a denied 1 MiB POST reads its 423. - PtApp gains the hold table, a notifier slot (None) and test pause gates (cfg(test) or matrix-upstream; AP_TEST_HOLD_PAUSE_MS only under the feature). notify.rs holds the trait only. Spike results: hyper drops the handler future on peer close, and no request byte leaves before forward_started, so neither plan fallback (decisions 5 and 6) was needed. An empty held body is sent chunked because hyper never polls a zero-length body. Verified on macmini: cargo fmt --check; clippy -D warnings (workspace all-targets, stage1-probe, matrix-upstream+stage1-probe) clean; cargo test --workspace ok (ap-proxy lib 137, 26 new hold tests); ap-proxy --features stage1-probe --lib ok (141); stage 1 black-box matrix 16/16 and matrix_passthrough test ok. --- crates/ap-proxy/src/forward.rs | 64 + crates/ap-proxy/src/lib.rs | 16 +- crates/ap-proxy/src/matrix_hooks.rs | 14 +- crates/ap-proxy/src/notify.rs | 36 + crates/ap-proxy/src/passthrough.rs | 201 ++- crates/ap-proxy/src/passthrough/hold_path.rs | 627 +++++++ crates/ap-proxy/src/passthrough/hold_tests.rs | 1472 +++++++++++++++++ crates/ap-proxy/src/passthrough/pause.rs | 125 ++ 8 files changed, 2528 insertions(+), 27 deletions(-) create mode 100644 crates/ap-proxy/src/notify.rs create mode 100644 crates/ap-proxy/src/passthrough/hold_path.rs create mode 100644 crates/ap-proxy/src/passthrough/hold_tests.rs create mode 100644 crates/ap-proxy/src/passthrough/pause.rs diff --git a/crates/ap-proxy/src/forward.rs b/crates/ap-proxy/src/forward.rs index 0f7e3a8..3949e11 100644 --- a/crates/ap-proxy/src/forward.rs +++ b/crates/ap-proxy/src/forward.rs @@ -42,6 +42,22 @@ pub fn client() -> Result { builder.build().map_err(|e| e.to_string()) } +/// Builder for the client that sends approved (held) requests. It speaks HTTP/1.1 only and keeps +/// no idle connections, so every approved request opens its own connection and the first poll of +/// its body stream happens before any request byte is flushed (design 3.4 step 8). +pub fn held_client_builder() -> ClientBuilder { + client_builder().http1_only().pool_max_idle_per_host(0) +} + +/// The client for approved requests, with the same test overrides as [`client`]. +pub fn held_client() -> Result { + #[cfg(feature = "matrix-upstream")] + let builder = crate::matrix_hooks::apply(held_client_builder())?; + #[cfg(not(feature = "matrix-upstream"))] + let builder = held_client_builder(); + builder.build().map_err(|e| e.to_string()) +} + /// The upstream URL for a route. `path_and_query` is the route-relative path with its query. pub fn upstream_url(route: &Route, path_and_query: &str) -> String { format!("https://{}:{}{}", route.host, route.port, path_and_query) @@ -225,6 +241,54 @@ pub fn guarded_body(body: Body, max: u64, stall: Duration, flags: BodyFlags) -> reqwest::Body::wrap_stream(stream) } +/// Why [`buffer_body`] gave up. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BufferError { + /// More than `max` bytes arrived. + Overflow, + /// A chunk took longer than the stall limit. + Stalled, + /// The caller's connection failed while the body was being read. + Read, +} + +/// Read a whole request body into memory. Bytes are counted against `max`, and each chunk must +/// arrive within `stall`. Used for held requests, which are kept in memory until a human decides. +pub async fn buffer_body(body: Body, max: u64, stall: Duration) -> Result { + let mut stream = Box::pin(body.into_data_stream()); + let mut buf: Vec = Vec::new(); + loop { + match tokio::time::timeout(stall, stream.next()).await { + Err(_) => return Err(BufferError::Stalled), + Ok(None) => return Ok(Bytes::from(buf)), + Ok(Some(Err(_))) => return Err(BufferError::Read), + Ok(Some(Ok(chunk))) => { + if (buf.len() as u64).saturating_add(chunk.len() as u64) > max { + return Err(BufferError::Overflow); + } + buf.extend_from_slice(&chunk); + } + } + } +} + +/// Read and discard up to `max` bytes of `body`, for at most `total`, so a client still writing a +/// large body can read the refusal instead of seeing a reset (design 3.4 step 1). Errors and the +/// time limit end the drain quietly. +pub async fn drain_body(body: Body, max: u64, total: Duration) { + let drain = async { + let mut stream = Box::pin(body.into_data_stream()); + let mut seen: u64 = 0; + while let Some(Ok(chunk)) = stream.next().await { + seen = seen.saturating_add(chunk.len() as u64); + if seen >= max { + break; + } + } + }; + let _ = tokio::time::timeout(total, drain).await; +} + /// Response-only hop-by-hop fields, in addition to `HOP_HEADERS`. const RESPONSE_HOP_HEADERS: &[&str] = &["proxy-authenticate"]; diff --git a/crates/ap-proxy/src/lib.rs b/crates/ap-proxy/src/lib.rs index 500e8a1..97920c0 100644 --- a/crates/ap-proxy/src/lib.rs +++ b/crates/ap-proxy/src/lib.rs @@ -11,6 +11,7 @@ pub mod hold; pub mod listener; #[cfg(feature = "matrix-upstream")] pub mod matrix_hooks; +pub mod notify; pub mod passthrough; pub mod pipeline; mod policy_store; @@ -229,6 +230,13 @@ async fn run_passthrough(opts: &Options, cfg: ap_core::config::Config) -> i32 { return 1; } }; + let held_client = match forward::held_client() { + Ok(c) => c, + Err(e) => { + eprintln!("auth-proxy: cannot build the upstream client: {e}"); + return 1; + } + }; let listen = cfg.listen.proxy; let listener = match listener::bind_loopback(listen).await { Ok(l) => l, @@ -243,7 +251,13 @@ async fn run_passthrough(opts: &Options, cfg: ap_core::config::Config) -> i32 { Some(l) => eprintln!("auth-proxy: panic at {}:{}", l.file(), l.line()), None => eprintln!("auth-proxy: panic"), })); - let app = passthrough::PtApp::new(opts.config.clone(), cfg, AuditSink::stdout(), client); + let app = passthrough::PtApp::with_held_client( + opts.config.clone(), + cfg, + AuditSink::stdout(), + client, + held_client, + ); let limits = listener::public::PublicLimits { max_connections: pt.max_connections, header_read: std::time::Duration::from_secs(pt.header_read_secs), diff --git a/crates/ap-proxy/src/matrix_hooks.rs b/crates/ap-proxy/src/matrix_hooks.rs index e23438d..ae69b4a 100644 --- a/crates/ap-proxy/src/matrix_hooks.rs +++ b/crates/ap-proxy/src/matrix_hooks.rs @@ -1,7 +1,7 @@ //! Test-only upstream overrides for the black-box matrix. Compiled only with the `matrix-upstream` //! feature, which is off by default and is never enabled in a release build. //! -//! The matrix runs the proxy against throwaway CAs and mock upstreams on loopback. Two environment +//! The matrix runs the proxy against throwaway CAs and mock upstreams on loopback. Three environment //! variables make that possible. Nothing in this module reads the config file, and a binary built //! without the feature contains none of this code. @@ -15,6 +15,18 @@ pub const ENV_CA: &str = "AP_TEST_UPSTREAM_CA"; /// Comma-separated `host=ip` pairs. Each host resolves to that address. The port comes from the URL. pub const ENV_RESOLVE: &str = "AP_TEST_RESOLVE"; +/// Milliseconds to pause between the `Approved` transition and the upstream send, so the matrix can +/// kill the process inside that window. Absent or unparsable means no pause. +pub const ENV_HOLD_PAUSE_MS: &str = "AP_TEST_HOLD_PAUSE_MS"; + +/// The configured pause, in milliseconds. +pub fn hold_pause_ms() -> u64 { + std::env::var(ENV_HOLD_PAUSE_MS) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0) +} + /// A request path that makes a passthrough handler panic, to exercise the panic hook. pub const PANIC_PATH: &str = "/__ap_test_panic"; diff --git a/crates/ap-proxy/src/notify.rs b/crates/ap-proxy/src/notify.rs new file mode 100644 index 0000000..905d4e3 --- /dev/null +++ b/crates/ap-proxy/src/notify.rs @@ -0,0 +1,36 @@ +//! Notification hook for new hold entries (design 3.4 step 5). +//! +//! This module holds the interface only. The gate stores an optional [`Notifier`] and calls it +//! for a new distinct entry, never for a supersede. The text is fixed and carries nothing from the +//! request. + +use std::fmt; +use std::future::Future; +use std::pin::Pin; + +/// The only text a notification may carry. +pub const TEXT: &str = "A gated request is waiting for approval."; + +/// A notification could not be delivered. It carries no detail, so no URL, topic or token can +/// reach a log through it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NotifyError; + +impl fmt::Display for NotifyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("notification failed") + } +} + +impl std::error::Error for NotifyError {} + +/// Sends one notification about a new held request. +pub trait Notifier: Send + Sync { + /// One attempt, no retry. `text` is [`TEXT`]; `approval_url` points at the entry's page. + fn notify( + &self, + request_id: &str, + text: &str, + approval_url: &str, + ) -> Pin> + Send + '_>>; +} diff --git a/crates/ap-proxy/src/passthrough.rs b/crates/ap-proxy/src/passthrough.rs index 3dcc1f1..b463586 100644 --- a/crates/ap-proxy/src/passthrough.rs +++ b/crates/ap-proxy/src/passthrough.rs @@ -6,6 +6,9 @@ //! not granted, writes included, is 423 `no_grant`), forward with the caller's own //! `Authorization` unchanged, and stream the response back. Every gate refusal carries //! `X-AP-Decision` and writes one audit line. Nothing request-supplied selects the upstream host. +//! +//! Stage 2: a grant with `decision = "hold"` sends the request to [`hold_path`], which buffers it, +//! parks it in the hold table and forwards it only after a human approves it. use std::io; use std::sync::atomic::Ordering; @@ -18,6 +21,7 @@ use ap_core::canon; use ap_core::config::{Config, Identity}; use ap_core::error::Code; use ap_core::outcome::{render_passthrough, DECISION_HEADER}; +use ap_core::policy::Verdict; use axum::body::Body; use bytes::Bytes; use futures_util::{Stream, StreamExt}; @@ -27,8 +31,15 @@ use subtle::ConstantTimeEq; use crate::audit_sink::AuditSink; use crate::evidence::Evidence; use crate::forward::{self, BodyFlags}; +use crate::hold; +use crate::notify::Notifier; use crate::policy_store::PolicyStore; +mod hold_path; +#[cfg(test)] +mod hold_tests; +#[cfg(any(test, feature = "matrix-upstream"))] +pub(crate) mod pause; #[cfg(test)] mod tests; @@ -49,23 +60,75 @@ pub struct PtApp { pub(crate) policy: PolicyStore, pub(crate) audit: AuditSink, client: reqwest::Client, + /// Sends approved requests: HTTP/1.1, one connection per request. + held_client: reqwest::Client, + /// Held requests waiting for a decision. + pub hold: Arc, + /// Told about each new distinct hold entry. `None` until a notifier is configured. + pub notifier: Option>, + #[cfg(any(test, feature = "matrix-upstream"))] + pub(crate) pause: pause::Pause, } impl PtApp { + /// An app that sends approved requests through `client` too. The hold table takes its limits + /// from the policy read at startup. + #[cfg(test)] pub(crate) fn new( policy_path: std::path::PathBuf, cfg: Config, audit: AuditSink, client: reqwest::Client, + ) -> Arc { + let held_client = client.clone(); + Self::with_held_client(policy_path, cfg, audit, client, held_client) + } + + /// An app with a separate client for approved requests (see `forward::held_client`). + pub(crate) fn with_held_client( + policy_path: std::path::PathBuf, + cfg: Config, + audit: AuditSink, + client: reqwest::Client, + held_client: reqwest::Client, + ) -> Arc { + let limits = cfg + .passthrough + .as_ref() + .map_or_else(default_limits, hold::Limits::from_config); + Self::build(policy_path, cfg, audit, client, held_client, limits) + } + + pub(crate) fn build( + policy_path: std::path::PathBuf, + cfg: Config, + audit: AuditSink, + client: reqwest::Client, + held_client: reqwest::Client, + limits: hold::Limits, ) -> Arc { Arc::new(PtApp { policy: PolicyStore::new(policy_path, cfg), audit, client, + held_client, + hold: Arc::new(hold::Table::new(limits)), + notifier: None, + #[cfg(any(test, feature = "matrix-upstream"))] + pause: pause::Pause::new(), }) } } +fn default_limits() -> hold::Limits { + hold::Limits { + hold: Duration::from_secs(120), + max_total: 32, + max_per_identity: 4, + cooldown: Duration::from_secs(60), + } +} + /// What the audit line knows so far. The caller key and `Authorization` never enter it. pub(crate) struct Trail { started: Instant, @@ -129,10 +192,16 @@ impl std::fmt::Debug for Trail { /// A gate refusal: audit line, evidence line, status, `X-AP-Decision` and JSON body. pub(crate) fn refuse(app: &PtApp, trail: &Trail, code: Code) -> Response { - let (status, decision, body) = render_passthrough(code); + let (status, _, _) = render_passthrough(code); app.audit .write_rec(&trail.rec("deny", Some(code.code_str()), status)); trail.write_evidence(&app.audit, status); + refusal_response(code) +} + +/// The answer for a refusal, without any audit line. +pub(crate) fn refusal_response(code: Code) -> Response { + let (status, decision, body) = render_passthrough(code); let mut r = Response::new(Body::from(body)); *r.status_mut() = StatusCode::from_u16(status).unwrap_or(StatusCode::SERVICE_UNAVAILABLE); r.headers_mut().insert( @@ -144,6 +213,55 @@ pub(crate) fn refuse(app: &PtApp, trail: &Trail, code: Code) -> Response { r } +/// How to drain an unread request body before a refusal (design 3.4 step 1). +pub(crate) struct Drain { + max: u64, + total: Duration, + skip: bool, +} + +impl Drain { + /// `skip` when no body will arrive: none declared, or `Expect: 100-continue` (hyper has not + /// sent `100 Continue`, so the client is waiting and the drain would only run out its timer). + pub(crate) fn new( + headers: &http::HeaderMap, + declared: Option, + pt: &ap_core::config::Passthrough, + ) -> Drain { + let has_body = + headers.contains_key(header::TRANSFER_ENCODING) || declared.is_some_and(|n| n > 0); + let expect = headers + .get_all(header::EXPECT) + .iter() + .filter_map(|v| v.to_str().ok()) + .any(|v| v.trim().eq_ignore_ascii_case("100-continue")); + Drain { + max: pt.held_body_max_bytes, + total: Duration::from_secs(pt.body_read_secs), + skip: !has_body || expect, + } + } + + async fn run(&self, body: Body) { + if !self.skip { + forward::drain_body(body, self.max, self.total).await; + } + } +} + +/// A refusal for a request whose body has not been read: drain it first, so a client still +/// writing can read the answer instead of seeing a reset. +pub(crate) async fn refuse_unread( + app: &PtApp, + trail: &Trail, + code: Code, + body: Body, + drain: &Drain, +) -> Response { + drain.run(body).await; + refuse(app, trail, code) +} + /// A failure after the first upstream request byte: one audit line, then the caller's /// connection is closed with no synthetic answer. fn abort(app: &PtApp, trail: &Trail, code: &str) -> ConnAbort { @@ -169,20 +287,38 @@ fn caller_identity<'a>(cfg: &'a Config, caller_key: &str) -> Option<&'a Identity found } -/// Writes the allow line when the response body ends, or when the client drops it. +/// What the stream audit writes when the response ends. +enum End { + /// An allowed request: the single `allow` line. + Allow, + /// An approved request: a `completed` transition, unless the upstream reset. + Held(hold_path::HeldEnd), +} + +/// Writes the final line when the response body ends, or when the client drops it. struct StreamAudit { app: Arc, trail: Trail, status: u16, reset: bool, + end: End, } impl Drop for StreamAudit { fn drop(&mut self) { - let code = self.reset.then_some("upstream_reset"); - self.app - .audit - .write_rec(&self.trail.rec("allow", code, self.status)); + match &self.end { + End::Allow => { + let code = self.reset.then_some("upstream_reset"); + self.app + .audit + .write_rec(&self.trail.rec("allow", code, self.status)); + } + End::Held(h) => { + if !self.reset { + self.app.audit.write_hold(&h.completed(self.status)); + } + } + } self.trail.write_evidence(&self.app.audit, self.status); } } @@ -328,42 +464,56 @@ pub async fn handle(app: Arc, req: Request) -> Result r, - Err(code) => return Ok(refuse(&app, &trail, code)), + Err(code) => return Ok(refuse_unread(&app, &trail, code, body, &drain).await), }; let Some(route) = policy.snap.route(route_name) else { - return Ok(refuse(&app, &trail, Code::RouteUnknown)); + return Ok(refuse_unread(&app, &trail, Code::RouteUnknown, body, &drain).await); }; trail.route = Some(route.name.clone()); trail.path = canon::redact_path(&path_only(&rel)); // 7. More than one Authorization header is refused: the gate cannot say which one is read. if parts.headers.get_all(header::AUTHORIZATION).iter().count() > 1 { - return Ok(refuse(&app, &trail, Code::AuthorizationDuplicate)); + return Ok(refuse_unread(&app, &trail, Code::AuthorizationDuplicate, body, &drain).await); } - // 8. Grant. Everything not granted is 423 no_grant. - if policy - .snap - .evaluate( - &identity.name, - &route.name, - parts.method.as_str(), - &rel, - &[], - ) - .is_err() - { - return Ok(refuse(&app, &trail, Code::NoGrant)); + // 8. Grant. Everything not granted is 423 no_grant. A hold grant sends the request down the + // hold path. + let verdict = + match policy + .snap + .evaluate_verdict(&identity.name, &route.name, parts.method.as_str(), &rel) + { + Ok(v) => v, + Err(_) => return Ok(refuse_unread(&app, &trail, Code::NoGrant, body, &drain).await), + }; + if verdict == Verdict::Hold { + return hold_path::run(hold_path::Request { + app, + trail, + parts, + body, + pt, + route, + rel: &rel, + identity: &identity.name, + drain, + }) + .await; } // 9. Declared length over the cap. - let max_body = policy.cfg.limits.max_body_bytes; - let declared = forward::declared_length(&parts.headers); if declared.is_some_and(|n| n > max_body) { - return Ok(refuse(&app, &trail, Code::BodyTooLarge)); + return Ok(refuse_unread(&app, &trail, Code::BodyTooLarge, body, &drain).await); } // 10. Forward. The path goes upstream raw, with the query raw. @@ -424,6 +574,7 @@ pub async fn handle(app: Arc, req: Request) -> Result { + pub app: Arc, + pub trail: Trail, + pub parts: http::request::Parts, + pub body: Body, + pub pt: &'a Passthrough, + pub route: &'a Route, + pub rel: &'a str, + pub identity: &'a str, + pub drain: Drain, +} + +/// What the audit records of one held request share. No header value, no body, no query. +#[derive(Clone)] +struct Ctx { + identity: String, + route: Option, + method: String, + /// Route-relative path with token segments already redacted. + path: String, + auth_present: bool, + started: Instant, +} + +impl Ctx { + fn rec( + &self, + id: &str, + digest: &str, + transition: &'static str, + approver: Option<&str>, + code: Option<&str>, + status: Option, + ) -> HoldRec { + HoldRec { + request_id: id.to_string(), + identity: self.identity.clone(), + route: self.route.clone(), + method: self.method.clone(), + path: self.path.clone(), + digest: Some(digest.to_string()), + transition, + approver: approver.map(str::to_string), + code: code.map(str::to_string), + status, + duration_ms: u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + auth_present: self.auth_present, + } + } +} + +/// What the response stream needs to write the `completed` line. +pub(super) struct HeldEnd { + ctx: Ctx, + id: String, + digest: String, +} + +impl HeldEnd { + pub(super) fn completed(&self, status: u16) -> HoldRec { + self.ctx.rec( + &self.id, + &self.digest, + "completed", + None, + None, + Some(status), + ) + } +} + +/// When milestone 1 happened. +struct Started { + at: Mutex>, + notify: Notify, +} + +impl Started { + fn new() -> Started { + Started { + at: Mutex::new(None), + notify: Notify::new(), + } + } + + fn set(&self) { + if let Ok(mut at) = self.at.lock() { + *at = Some(Instant::now()); + } + self.notify.notify_one(); + } + + fn get(&self) -> Option { + self.at.lock().ok().and_then(|g| *g) + } + + /// Resolves `limit` after milestone 1. An approved request's deadline counts from there. + async fn deadline(&self, limit: Duration) { + loop { + let n = self.notify.notified(); + tokio::pin!(n); + n.as_mut().enable(); + if let Some(at) = self.get() { + tokio::time::sleep_until(tokio::time::Instant::from_std(at + limit)).await; + return; + } + n.await; + } + } +} + +type SharedConfirm = Arc>>; + +fn take_confirm(c: &SharedConfirm) -> Option { + c.lock().ok().and_then(|mut g| g.take()) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Phase { + /// Waiting for a decision. + Pending, + /// A human approved; the forward has not reached milestone 1 yet. + Approved, + /// Nothing left for the guard to record. + Done, +} + +/// Owns the entry's side of the handler. Dropping it while the handler is still waiting means the +/// caller went away. +struct Guard { + app: Arc, + ctx: Ctx, + id: String, + digest: String, + phase: Phase, + rx: Option>, + started: Arc, +} + +impl Guard { + fn write( + &self, + transition: &'static str, + approver: Option<&str>, + code: Option<&str>, + status: Option, + ) { + self.app.audit.write_hold(&self.ctx.rec( + &self.id, + &self.digest, + transition, + approver, + code, + status, + )); + } + + /// The transition record a decision stands for. + fn record(&self, d: &Decision) { + match d { + Decision::Approved { approver, .. } => { + self.write("approved", Some(approver), None, None); + } + Decision::Denied { approver } => { + self.write("denied", Some(approver), Some("human_denied"), Some(423)); + } + Decision::Superseded { .. } => { + self.write("superseded", None, Some("superseded"), Some(503)); + } + Decision::Dropped => { + self.write( + "dropped_on_reload", + None, + Some("dropped_on_reload"), + Some(503), + ); + } + // Shutdown has no transition of its own; the handler writes a refusal line. + Decision::Shutdown => {} + } + } +} + +impl Drop for Guard { + fn drop(&mut self) { + match self.phase { + Phase::Done => {} + Phase::Pending => { + if self.app.hold.abandon(&self.id) { + self.write("abandoned", None, None, None); + } else if let Some(rx) = self.rx.as_mut() { + // A decision won before the caller left and was never read. + if let Ok(d) = rx.try_recv() { + self.record(&d); + if matches!(d, Decision::Approved { .. }) { + self.write("abandoned_after_approve", None, None, None); + } + } + } + } + Phase::Approved => { + if self.started.get().is_none() { + self.write("abandoned_after_approve", None, None, None); + } + } + } + } +} + +/// The approved request's body, as a stream the HTTP client polls. See the module doc for the two +/// milestones. +struct HeldBody { + app: Arc, + ctx: Ctx, + id: String, + digest: String, + first: bool, + body: Option, + confirm: SharedConfirm, + started: Arc, + audit_failed: Arc, + failed: bool, +} + +impl Stream for HeldBody { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + if this.failed { + return Poll::Ready(None); + } + if this.first { + this.first = false; + // Milestone 1: the connection exists and no request byte has been flushed. The record + // must reach the sink first; if it cannot, the body fails and nothing is sent. + let rec = this + .ctx + .rec(&this.id, &this.digest, "forward_started", None, None, None); + if this.app.audit.try_write_hold(&rec).is_err() { + this.failed = true; + this.audit_failed.store(true, Ordering::SeqCst); + if let Some(c) = take_confirm(&this.confirm) { + c.send(Confirm::AuditUnavailable); + } + return Poll::Ready(Some(Err(io::Error::other("audit write failed")))); + } + this.started.set(); + #[cfg(any(test, feature = "matrix-upstream"))] + this.app.pause.between_milestones(); + } + // Milestone 2: the first chunk is handed over (or, for an empty body, the end). + if let Some(c) = take_confirm(&this.confirm) { + c.send(Confirm::Started); + } + match this.body.take() { + Some(b) if !b.is_empty() => Poll::Ready(Some(Ok(b))), + _ => Poll::Ready(None), + } + } +} + +fn json_content_type(h: &HeaderMap) -> bool { + let mut it = h.get_all(header::CONTENT_TYPE).iter(); + let (Some(v), None) = (it.next(), it.next()) else { + return false; + }; + let Ok(s) = v.to_str() else { + return false; + }; + s.split(';') + .next() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case("application/json") +} + +fn identity_encoding(h: &HeaderMap) -> bool { + h.get_all(header::CONTENT_ENCODING).iter().all(|v| { + v.to_str().is_ok_and(|s| { + s.split(',').all(|t| { + let t = t.trim(); + t.is_empty() || t.eq_ignore_ascii_case("identity") + }) + }) + }) +} + +/// The final answer for a refusal that already has its transition record: evidence line, status, +/// `X-AP-Decision` and body. +fn finish(app: &PtApp, trail: &Trail, code: Code) -> Response { + let (status, _, _) = render_passthrough(code); + trail.write_evidence(&app.audit, status); + refusal_response(code) +} + +/// The caller's connection is closed with no answer, after the first request byte may have left. +fn abort(app: &PtApp, trail: &Trail) -> ConnAbort { + trail.write_evidence(&app.audit, 0); + ConnAbort +} + +pub(super) async fn run(r: Request<'_>) -> Result, ConnAbort> { + let Request { + app, + trail, + parts, + body, + pt, + route, + rel, + identity, + drain, + } = r; + + // 1-3. Refusals before the body is read. + if !json_content_type(&parts.headers) { + return Ok(refuse_unread(&app, &trail, Code::ContentType, body, &drain).await); + } + if !identity_encoding(&parts.headers) { + return Ok(refuse_unread(&app, &trail, Code::ContentEncoding, body, &drain).await); + } + if !parts.headers.contains_key(header::AUTHORIZATION) { + return Ok(refuse_unread(&app, &trail, Code::CredentialMissing, body, &drain).await); + } + let cap = pt.held_body_max_bytes; + if forward::declared_length(&parts.headers).is_some_and(|n| n > cap) { + return Ok(refuse_unread(&app, &trail, Code::BodyTooLarge, body, &drain).await); + } + + // 4. Read the body into memory. + let bytes = match forward::buffer_body(body, cap, Duration::from_secs(pt.body_read_secs)).await + { + Ok(b) => b, + Err(BufferError::Overflow) => return Ok(refuse(&app, &trail, Code::BodyTooLarge)), + Err(BufferError::Stalled | BufferError::Read) => { + return Ok(refuse(&app, &trail, Code::BodyReadTimeout)) + } + }; + + // 5. The complete outbound request, as it will be sent. The entry names exactly these bytes. + let mut headers = forward::passthrough_headers(&parts.headers, route, pt); + // The body is buffered, so its length is known. An empty body gets no `Content-Length`: hyper + // never polls the body of a zero-length request, so milestone 1 would not happen, and the + // request goes out chunked instead (its stream is polled before the head is flushed). + if bytes.is_empty() { + headers.remove(header::CONTENT_LENGTH); + } else { + headers.insert(header::CONTENT_LENGTH, HeaderValue::from(bytes.len())); + } + let query = parts.uri.query().map(str::to_string); + let req = Arc::new(HeldRequest { + method: parts.method.as_str().to_string(), + route: route.name.clone(), + path: rel.to_string(), + query: query.clone(), + headers: headers + .iter() + .map(|(n, v)| (n.as_str().to_string(), v.as_bytes().to_vec())) + .collect(), + body: bytes.clone(), + }); + let ctx = Ctx { + identity: identity.to_string(), + route: trail.route.clone(), + method: parts.method.as_str().to_string(), + path: trail.path.clone(), + auth_present: req.auth_present(), + started: trail.started, + }; + + // 6. Admission. The `held` record is written under the table lock, before anything changes. + let admission = app.hold.admit(identity, Arc::clone(&req), |id, digest| { + app.audit + .try_write_hold(&ctx.rec(id, digest, "held", None, None, None)) + }); + let held = match admission { + Admission::Refused(code) => return Ok(refuse(&app, &trail, code)), + Admission::Held(h) => h, + }; + // A notifier fires here for a new entry (`held.superseded.is_none()`). + let mut guard = Guard { + app: Arc::clone(&app), + ctx: ctx.clone(), + id: held.id, + digest: held.digest, + phase: Phase::Pending, + rx: Some(held.decision), + started: Arc::new(Started::new()), + }; + + // 7. Wait for a decision, the timer or the caller leaving (which drops this future). + enum Event { + Decision(Result), + Timer, + } + let hold = app.hold.limits().hold; + let event = { + let Some(rx) = guard.rx.as_mut() else { + return Ok(refuse(&app, &trail, Code::Shutdown)); + }; + tokio::select! { + d = rx => Event::Decision(d), + () = tokio::time::sleep(hold) => Event::Timer, + } + }; + let decision = match event { + Event::Decision(d) => d, + Event::Timer => { + if app.hold.expire(&guard.id) { + guard.phase = Phase::Done; + guard.write("expired", None, Some("expired"), Some(410)); + return Ok(finish(&app, &trail, Code::Expired)); + } + // Another transition won first; its decision is already in the channel. + match guard.rx.as_mut() { + Some(rx) => rx.await, + None => return Ok(refuse(&app, &trail, Code::Shutdown)), + } + } + }; + guard.rx = None; + let decision = match decision { + Ok(d) => d, + Err(_) => { + guard.phase = Phase::Done; + return Ok(refuse(&app, &trail, Code::Shutdown)); + } + }; + guard.record(&decision); + match decision { + Decision::Approved { confirm, .. } => { + guard.phase = Phase::Approved; + forward_approved(Forward { + app, + trail, + guard, + confirm, + headers, + bytes, + method: parts.method, + url: forward::upstream_url( + route, + &match &query { + Some(q) => format!("{rel}?{q}"), + None => rel.to_string(), + }, + ), + pt, + }) + .await + } + Decision::Denied { .. } => { + guard.phase = Phase::Done; + Ok(finish(&app, &trail, Code::HumanDenied)) + } + Decision::Superseded { .. } => { + guard.phase = Phase::Done; + Ok(finish(&app, &trail, Code::Superseded)) + } + Decision::Dropped => { + guard.phase = Phase::Done; + Ok(finish(&app, &trail, Code::DroppedOnReload)) + } + Decision::Shutdown => { + guard.phase = Phase::Done; + Ok(refuse(&app, &trail, Code::Shutdown)) + } + } +} + +struct Forward<'a> { + app: Arc, + trail: Trail, + guard: Guard, + confirm: ConfirmTx, + headers: HeaderMap, + bytes: Bytes, + method: http::Method, + url: String, + pt: &'a Passthrough, +} + +enum Sent { + Done(reqwest::Result), + Timeout, +} + +async fn forward_approved(f: Forward<'_>) -> Result, ConnAbort> { + let Forward { + app, + trail, + mut guard, + confirm, + headers, + bytes, + method, + url, + pt, + } = f; + let confirm: SharedConfirm = Arc::new(Mutex::new(Some(confirm))); + + #[cfg(any(test, feature = "matrix-upstream"))] + app.pause.after_approve().await; + + let audit_failed = Arc::new(AtomicBool::new(false)); + let stream = HeldBody { + app: Arc::clone(&app), + ctx: guard.ctx.clone(), + id: guard.id.clone(), + digest: guard.digest.clone(), + first: true, + body: Some(bytes), + confirm: Arc::clone(&confirm), + started: Arc::clone(&guard.started), + audit_failed: Arc::clone(&audit_failed), + failed: false, + }; + let send = app + .held_client + .request(method, url) + .headers(headers) + .body(reqwest::Body::wrap_stream(stream)) + .send(); + tokio::pin!(send); + let started = Arc::clone(&guard.started); + let limit = Duration::from_secs(pt.request_deadline_secs); + let sent = tokio::select! { + r = &mut send => Sent::Done(r), + () = started.deadline(limit) => Sent::Timeout, + }; + + let upstream = match sent { + Sent::Done(Ok(r)) => r, + Sent::Done(Err(_)) => { + guard.phase = Phase::Done; + if audit_failed.load(Ordering::SeqCst) { + guard.write( + "audit_unavailable", + None, + Some("audit_unavailable"), + Some(503), + ); + return Ok(finish(&app, &trail, Code::AuditUnavailable)); + } + if started.get().is_none() { + // The body was never polled: no connection, nothing sent. + if let Some(c) = take_confirm(&confirm) { + c.send(Confirm::ConnectFailed); + } + guard.write("connect_failed", None, Some("connect_failed"), Some(503)); + return Ok(finish(&app, &trail, Code::ConnectFailed)); + } + // After `forward_started`: no synthetic answer, and no `completed`. + return Err(abort(&app, &trail)); + } + Sent::Timeout => { + guard.phase = Phase::Done; + return Err(abort(&app, &trail)); + } + }; + + // The request is on its way; the guard has nothing left to record. + guard.phase = Phase::Done; + let status = upstream.status(); + let out_headers = forward::response_headers(upstream.headers()); + let deadline = started.get().unwrap_or_else(Instant::now) + limit; + let end = HeldEnd { + ctx: guard.ctx.clone(), + id: guard.id.clone(), + digest: guard.digest.clone(), + }; + let audit = StreamAudit { + app: Arc::clone(&app), + trail, + status: status.as_u16(), + reset: false, + end: End::Held(end), + }; + let idle = Duration::from_secs(pt.upstream_idle_secs); + let stream = audited(upstream.bytes_stream(), audit, deadline, idle); + let mut response = Response::new(Body::from_stream(stream)); + *response.status_mut() = status; + *response.headers_mut() = out_headers; + Ok(response) +} diff --git a/crates/ap-proxy/src/passthrough/hold_tests.rs b/crates/ap-proxy/src/passthrough/hold_tests.rs new file mode 100644 index 0000000..1b91ece --- /dev/null +++ b/crates/ap-proxy/src/passthrough/hold_tests.rs @@ -0,0 +1,1472 @@ +//! The hold path end to end (design stage 2 acceptance 1 to 6, 8, 13 to 18, 20, 23 to 25 and 29), +//! against a mock TLS upstream that records what it receives. + +use std::convert::Infallible; +use std::io::{self, Write}; +use std::net::SocketAddr; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use axum::body::Body; +use bytes::Bytes; +use futures_util::StreamExt; +use http::Request; +use http_body_util::combinators::UnsyncBoxBody; +use http_body_util::{BodyExt, Full, StreamBody}; +use hyper::body::{Frame, Incoming}; +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper_util::rt::TokioIo; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio_rustls::TlsAcceptor; + +use super::pause::Gate; +use super::*; +use crate::hold::{ApproveResult, DenyResult, Limits, State}; +use crate::test_support::{ + buffer_sink, caller_key, client_for, tls_server_config, Scratch, Upstream, HOST, +}; +use ap_broker::registry::sha256_hex; + +const AUTH: &str = "gate.example.test"; +const SENTINEL: &str = "SENTINEL-DISCORD-TOKEN-0001"; +const PATH_TOKEN: &str = "SENTINEL-PATH-TOKEN-0002"; + +// ---------------------------------------------------------------- mock upstreams + +#[derive(Clone, Debug)] +struct Recorded { + method: String, + uri: String, + headers: Vec<(String, Vec)>, + body: Bytes, +} + +type MockBody = UnsyncBoxBody; + +fn full(b: &'static str) -> MockBody { + Full::new(Bytes::from_static(b.as_bytes())) + .map_err(|never: Infallible| match never {}) + .boxed_unsync() +} + +/// A TLS upstream that records every request it fully receives. The last path segment picks the +/// behaviour: `teapot` answers 418 with `X-AP-*` headers, `reset-after-read` and +/// `reset-before-read` drop the connection, `stall` never answers, `stall-body` sends a head and +/// one chunk and then goes quiet, `trickle` sends a chunk every 300 ms forever. +struct Mock { + up: Upstream, + reqs: Arc>>, +} + +impl Mock { + async fn start() -> Mock { + let (server, ca_der) = tls_server_config(b"http/1.1"); + let acceptor = TlsAcceptor::from(Arc::new(server)); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind mock"); + let addr = listener.local_addr().expect("mock addr"); + let hits = Arc::new(AtomicUsize::new(0)); + let reqs: Arc>> = Arc::default(); + let (h, r) = (Arc::clone(&hits), Arc::clone(&reqs)); + tokio::spawn(async move { + while let Ok((tcp, _)) = listener.accept().await { + h.fetch_add(1, Ordering::SeqCst); + let acceptor = acceptor.clone(); + let reqs = Arc::clone(&r); + tokio::spawn(async move { + if let Ok(tls) = acceptor.accept(tcp).await { + let svc = service_fn(move |req| serve(req, Arc::clone(&reqs))); + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(tls), svc) + .await; + } + }); + } + }); + Mock { + up: Upstream::from_parts(addr, hits, ca_der), + reqs, + } + } + + fn recorded(&self) -> Vec { + self.reqs.lock().unwrap().clone() + } + + fn hits(&self) -> usize { + self.up.hits.load(Ordering::SeqCst) + } +} + +async fn serve( + req: hyper::Request, + reqs: Arc>>, +) -> Result, io::Error> { + let (parts, body) = req.into_parts(); + let tail = parts + .uri + .path() + .rsplit('/') + .next() + .unwrap_or("") + .to_string(); + if tail == "reset-before-read" { + return Err(io::Error::other("reset")); + } + let body = body + .collect() + .await + .map(|b| b.to_bytes()) + .unwrap_or_default(); + reqs.lock().unwrap().push(Recorded { + method: parts.method.to_string(), + uri: parts.uri.to_string(), + headers: parts + .headers + .iter() + .map(|(n, v)| (n.as_str().to_string(), v.as_bytes().to_vec())) + .collect(), + body, + }); + match tail.as_str() { + "teapot" => Ok(hyper::Response::builder() + .status(418) + .header("x-ap-decision", "denied") + .header("x-ap-other", "kept") + .header("x-plain", "yes") + .body(full("short and stout")) + .expect("teapot")), + "reset-after-read" => Err(io::Error::other("reset")), + "stall" => std::future::pending().await, + "stall-body" => { + let s = futures_util::stream::once(async { + Ok::<_, io::Error>(Frame::data(Bytes::from_static(b"a"))) + }) + .chain(futures_util::stream::pending()); + Ok(hyper::Response::new(StreamBody::new(s).boxed_unsync())) + } + "trickle" => { + let s = futures_util::stream::unfold((), |()| async { + tokio::time::sleep(Duration::from_millis(300)).await; + Some(( + Ok::<_, io::Error>(Frame::data(Bytes::from_static(b"t"))), + (), + )) + }); + Ok(hyper::Response::new(StreamBody::new(s).boxed_unsync())) + } + _ => Ok(hyper::Response::new(full("ok"))), + } +} + +/// A TLS upstream that completes handshakes and counts the request bytes it receives, answering +/// nothing. +struct Raw { + up: Upstream, + accepted: Arc, + bytes: Arc, +} + +impl Raw { + async fn start() -> Raw { + let (server, ca_der) = tls_server_config(b"http/1.1"); + let acceptor = TlsAcceptor::from(Arc::new(server)); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind raw"); + let addr = listener.local_addr().expect("raw addr"); + let accepted = Arc::new(AtomicUsize::new(0)); + let bytes = Arc::new(AtomicUsize::new(0)); + let (a, b) = (Arc::clone(&accepted), Arc::clone(&bytes)); + tokio::spawn(async move { + while let Ok((tcp, _)) = listener.accept().await { + let (acceptor, a, b) = (acceptor.clone(), Arc::clone(&a), Arc::clone(&b)); + tokio::spawn(async move { + let Ok(mut tls) = acceptor.accept(tcp).await else { + return; + }; + a.fetch_add(1, Ordering::SeqCst); + let mut buf = [0u8; 4096]; + while let Ok(n) = tls.read(&mut buf).await { + if n == 0 { + break; + } + b.fetch_add(n, Ordering::SeqCst); + } + }); + } + }); + Raw { + up: Upstream::from_parts(addr, Arc::new(AtomicUsize::new(0)), ca_der), + accepted, + bytes, + } + } +} + +// ---------------------------------------------------------------- audit sink that can fail + +#[derive(Clone, Default)] +struct Switch { + buf: Arc>>, + fail_all: Arc, + fail_on: Arc>>, +} + +impl Write for Switch { + fn write(&mut self, data: &[u8]) -> io::Result { + if self.fail_all.load(Ordering::SeqCst) { + return Err(io::Error::other("sink down")); + } + if let Some(pat) = self.fail_on.lock().unwrap().as_deref() { + if String::from_utf8_lossy(data).contains(pat) { + return Err(io::Error::other("sink rejects this line")); + } + } + self.buf.lock().unwrap().extend_from_slice(data); + Ok(data.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +// ---------------------------------------------------------------- fixture + +struct Opts { + limits: Limits, + /// Extra keys inside `[passthrough]`. + extra: String, + held_body_max: u64, + /// Text appended after the grants. + tail: String, + port: Option, + sink: Option, +} + +impl Default for Opts { + fn default() -> Opts { + Opts { + limits: Limits { + hold: Duration::from_secs(30), + max_total: 8, + max_per_identity: 4, + cooldown: Duration::ZERO, + }, + extra: String::new(), + held_body_max: 2048, + tail: String::new(), + port: None, + sink: None, + } + } +} + +struct Ht { + app: Arc, + key: String, + other_key: String, + audit: Arc>>, + policy: std::path::PathBuf, + _s: Scratch, +} + +impl Ht { + async fn new(tag: &str, up: &Upstream) -> Ht { + Self::with(tag, up, Opts::default()).await + } + + async fn with(tag: &str, up: &Upstream, o: Opts) -> Ht { + let s = Scratch::new(tag); + let key = caller_key(); + let other_key = caller_key(); + let port = o.port.unwrap_or(up.addr.port()); + let text = format!( + r#"version = 1 + +[listen] +proxy = "127.0.0.1:8443" + +[limits] +max_body_bytes = 1024 + +[passthrough] +public_authority = "{AUTH}" +body_read_secs = 1 +held_body_max_bytes = {max} +{extra} + +[[identity]] +name = "muse-pilot" +caller_key_sha256 = "{sha}" + +[[identity]] +name = "muse-other" +caller_key_sha256 = "{sha2}" + +[[route]] +name = "discord" +host = "{HOST}" +port = {port} +mode = "passthrough" + +[[grant]] +identity = "muse-pilot" +route = "discord" +methods = ["GET"] +paths = ["/api/", "/me"] + +[[grant]] +identity = "muse-pilot" +route = "discord" +methods = ["POST", "PUT"] +decision = "hold" +path_patterns = ["/hold/*", "/hold/*/messages", "/webhooks/*/*"] + +[[grant]] +identity = "muse-other" +route = "discord" +methods = ["POST"] +decision = "hold" +path_patterns = ["/hold/*"] +{tail} +"#, + max = o.held_body_max, + extra = o.extra, + tail = o.tail, + sha = sha256_hex(&key), + sha2 = sha256_hex(&other_key), + ); + let policy = s.path().join("policy.toml"); + std::fs::write(&policy, &text).unwrap(); + let cfg = ap_core::config::load(&text).expect("valid policy"); + let (sink, audit) = match o.sink { + Some(sw) => (AuditSink::new(Box::new(sw.clone())), sw.buf), + None => buffer_sink(), + }; + let client = client_for(up); + let app = PtApp::build(policy.clone(), cfg, sink, client.clone(), client, o.limits); + Ht { + app, + key, + other_key, + audit, + policy, + _s: s, + } + } + + fn builder(&self, key: &str, method: &str, path: &str) -> http::request::Builder { + Request::builder() + .method(method) + .uri(path) + .header("host", AUTH) + .header("x-ap-caller-key", key) + .header("authorization", format!("Bot {SENTINEL}")) + } + + fn post(&self, path: &str, body: &str) -> Request { + self.builder(&self.key, "POST", path) + .header("content-type", "application/json") + .header("content-length", body.len()) + .body(Body::from(body.to_string())) + .unwrap() + } + + fn post_other(&self, path: &str, body: &str) -> Request { + self.builder(&self.other_key, "POST", path) + .header("content-type", "application/json") + .header("content-length", body.len()) + .body(Body::from(body.to_string())) + .unwrap() + } + + fn spawn( + &self, + req: Request, + ) -> tokio::task::JoinHandle> { + let app = Arc::clone(&self.app); + tokio::spawn(async move { collect(handle(app, req).await).await }) + } + + async fn send(&self, req: Request) -> Result<(http::response::Parts, Bytes), ()> { + collect(handle(Arc::clone(&self.app), req).await).await + } + + fn text(&self) -> String { + String::from_utf8_lossy(&self.audit.lock().unwrap()).into_owned() + } + + fn lines(&self) -> Vec { + self.text() + .lines() + .filter_map(|l| serde_json::from_str(l).ok()) + .collect() + } + + fn transitions(&self) -> Vec { + self.lines() + .iter() + .filter_map(|v| v["transition"].as_str().map(str::to_string)) + .collect() + } + + fn count(&self, transition: &str) -> usize { + self.transitions() + .iter() + .filter(|t| *t == transition) + .count() + } + + fn held_ids(&self) -> Vec { + self.lines() + .iter() + .filter(|v| v["transition"] == "held") + .filter_map(|v| v["request_id"].as_str().map(str::to_string)) + .collect() + } + + /// The id of the `n`th (1-based) `held` record, once it exists. + async fn held(&self, n: usize) -> String { + for _ in 0..250 { + let ids = self.held_ids(); + if ids.len() >= n { + return ids[n - 1].clone(); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("hold {n} never appeared: {}", self.text()); + } + + /// Hold `req`, approve it, and return what the caller saw. + async fn approved(&self, req: Request) -> (http::response::Parts, Bytes) { + let n = self.held_ids().len() + 1; + let h = self.spawn(req); + let id = self.held(n).await; + assert_eq!( + self.app.hold.approve(&id, "alice").await, + ApproveResult::Success + ); + h.await.unwrap().unwrap() + } + + async fn serve(&self) -> SocketAddr { + let l = crate::listener::bind_loopback("127.0.0.1:0".parse().unwrap()) + .await + .unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(crate::listener::public::serve_public( + l, + Arc::clone(&self.app), + crate::listener::public::PublicLimits { + max_connections: 16, + header_read: Duration::from_secs(5), + }, + )); + addr + } + + fn assert_clean(&self) { + let t = self.text(); + for s in [ + SENTINEL, + PATH_TOKEN, + self.key.as_str(), + self.other_key.as_str(), + ] { + assert!(!t.contains(s), "{s} leaked into the audit stream: {t}"); + } + } +} + +async fn collect( + r: Result, ConnAbort>, +) -> Result<(http::response::Parts, Bytes), ()> { + match r { + Ok(resp) => { + let (p, b) = resp.into_parts(); + let bytes = b.collect().await.map(|c| c.to_bytes()).unwrap_or_default(); + Ok((p, bytes)) + } + Err(_) => Err(()), + } +} + +fn decision(p: &http::response::Parts) -> String { + p.headers + .get("x-ap-decision") + .map(|v| v.to_str().unwrap().to_string()) + .unwrap_or_default() +} + +fn code(b: &Bytes) -> String { + let v: serde_json::Value = serde_json::from_slice(b).unwrap(); + v["code"].as_str().unwrap().to_string() +} + +async fn until(what: &str, mut f: impl FnMut() -> bool) { + for _ in 0..250 { + if f() { + return; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("timed out waiting for {what}"); +} + +fn header_values<'a>(r: &'a Recorded, name: &str) -> Vec<&'a [u8]> { + r.headers + .iter() + .filter(|(n, _)| n == name) + .map(|(_, v)| v.as_slice()) + .collect() +} + +// ---------------------------------------------------------------- spike: disconnect and milestone + +#[tokio::test] +async fn hyper_drops_the_handler_future_when_the_peer_closes() { + let mock = Mock::start().await; + let t = Ht::new("spike-drop", &mock.up).await; + let addr = t.serve().await; + let mut c = TcpStream::connect(addr).await.unwrap(); + let req = format!( + "POST /discord/hold/ok HTTP/1.1\r\nHost: {AUTH}\r\nx-ap-caller-key: {}\r\nauthorization: Bot {SENTINEL}\r\ncontent-type: application/json\r\ncontent-length: 2\r\n\r\n{{}}", + t.key + ); + c.write_all(req.as_bytes()).await.unwrap(); + let id = t.held(1).await; + assert_eq!(t.app.hold.state(&id), Some(State::Pending)); + drop(c); + until("the entry to be abandoned", || { + t.app.hold.state(&id) == Some(State::Abandoned) + }) + .await; + assert_eq!(t.app.hold.pending_len(), 0); + assert_eq!(t.app.hold.approve(&id, "alice").await, ApproveResult::Gone); + assert_eq!(t.count("abandoned"), 1); + assert_eq!(t.count("abandoned_after_approve"), 0); + assert_eq!(mock.hits(), 0); + t.assert_clean(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn no_request_byte_leaves_before_forward_started_and_approve_waits_for_the_first_chunk() { + let raw = Raw::start().await; + let t = Ht::new("milestones", &raw.up).await; + let gate = Gate::new(); + t.app.pause.set_between_milestones(Arc::clone(&gate)); + let h = t.spawn(t.post("/discord/hold/ok", "{}")); + let id = t.held(1).await; + let table = Arc::clone(&t.app.hold); + let approve = tokio::spawn(async move { table.approve(&id, "alice").await }); + tokio::time::timeout(Duration::from_secs(5), gate.arrived()) + .await + .expect("handler reached the gap between the milestones"); + tokio::time::sleep(Duration::from_millis(300)).await; + // Connected, and forward_started is on the record, but not one request byte has arrived. + assert_eq!(raw.accepted.load(Ordering::SeqCst), 1); + assert_eq!(raw.bytes.load(Ordering::SeqCst), 0, "a byte left early"); + assert_eq!(t.count("forward_started"), 1); + assert!( + !approve.is_finished(), + "approve returned before the first byte" + ); + gate.release(); + let result = tokio::time::timeout(Duration::from_secs(5), approve) + .await + .unwrap() + .unwrap(); + assert_eq!(result, ApproveResult::Success); + until("request bytes", || raw.bytes.load(Ordering::SeqCst) > 0).await; + h.abort(); +} + +// ---------------------------------------------------------------- 1, 2, 3, 13 + +#[tokio::test] +async fn nothing_goes_upstream_before_approval_and_exactly_one_request_after() { + let mock = Mock::start().await; + let t = Ht::new("before-after", &mock.up).await; + let h = t.spawn(t.post("/discord/hold/ok", r#"{"content":"hi"}"#)); + let id = t.held(1).await; + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(mock.hits(), 0); + assert!(mock.recorded().is_empty()); + assert_eq!(t.app.hold.state(&id), Some(State::Pending)); + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::Success + ); + let (p, b) = h.await.unwrap().unwrap(); + assert_eq!(p.status, 200); + assert_eq!(&b[..], b"ok"); + assert_eq!(mock.recorded().len(), 1); + assert_eq!( + t.transitions(), + ["held", "approved", "forward_started", "completed"] + ); + t.assert_clean(); +} + +#[tokio::test] +async fn approved_request_arrives_unchanged_and_the_response_is_verbatim() { + let mock = Mock::start().await; + let t = Ht::new("verbatim", &mock.up).await; + let body = r#"{"content":"hello \u00e9","n":[1,2,3]}"#; + let req = t + .builder(&t.key, "POST", "/discord/hold/teapot?a=1&b=%2Fz") + .header("content-type", "application/json; charset=utf-8") + .header("accept", "application/json") + .header("content-length", body.len()) + .header("x-dup", "one") + .header("x-dup", "two") + .header("x-keep", "kept") + .header("expect", "100-continue") + .header("forwarded", "for=1") + .header("x-forwarded-for", "1.2.3.4") + .header("via", "1.1 front") + .header("cf-ray", "abc") + .header("tailscale-user-login", "someone") + .header("cookie", "a=b") + .header("proxy-authorization", "Basic x") + .header("x-api-key", "k") + .header("connection", "x-secret-hop") + .header("x-secret-hop", "1") + .body(Body::from(body)) + .unwrap(); + let (p, b) = t.approved(req).await; + // The upstream response, status, headers and body, including X-AP-* names. + assert_eq!(p.status, 418); + assert_eq!(p.headers.get("x-ap-decision").unwrap(), "denied"); + assert_eq!(p.headers.get("x-ap-other").unwrap(), "kept"); + assert_eq!(p.headers.get("x-plain").unwrap(), "yes"); + assert_eq!(&b[..], b"short and stout"); + // The request: one, with the same method, target, body and headers except the stripped ones. + let recs = mock.recorded(); + assert_eq!(recs.len(), 1); + let r = &recs[0]; + assert_eq!(r.method, "POST"); + assert!( + r.uri.ends_with("/hold/teapot?a=1&b=%2Fz"), + "target changed: {}", + r.uri + ); + assert_eq!(&r.body[..], body.as_bytes()); + assert_eq!( + header_values(r, "authorization"), + [format!("Bot {SENTINEL}").as_bytes()] + ); + assert_eq!(header_values(r, "x-dup"), [&b"one"[..], &b"two"[..]]); + assert_eq!(header_values(r, "x-keep"), [&b"kept"[..]]); + assert_eq!( + header_values(r, "content-type"), + [&b"application/json; charset=utf-8"[..]] + ); + assert_eq!( + header_values(r, "content-length"), + [body.len().to_string().as_bytes()] + ); + for gone in [ + "x-ap-caller-key", + "expect", + "forwarded", + "x-forwarded-for", + "via", + "cf-ray", + "tailscale-user-login", + "cookie", + "proxy-authorization", + "x-api-key", + "x-secret-hop", + ] { + assert!(header_values(r, gone).is_empty(), "{gone} reached upstream"); + } + t.assert_clean(); +} + +#[tokio::test] +async fn caller_key_is_stripped_in_both_forms() { + let mock = Mock::start().await; + let t = Ht::new("keystrip", &mock.up).await; + let by_header = t.post("/discord/hold/a", r#"{"k":"header"}"#); + let (p, _) = t.approved(by_header).await; + assert_eq!(p.status, 200); + let by_path = Request::builder() + .method("POST") + .uri(format!("/ap/{}/discord/hold/b", t.key)) + .header("host", AUTH) + .header("authorization", format!("Bot {SENTINEL}")) + .header("content-type", "application/json") + .header("content-length", "2") + .body(Body::from("{}")) + .unwrap(); + let (p, _) = t.approved(by_path).await; + assert_eq!(p.status, 200); + let recs = mock.recorded(); + assert_eq!(recs.len(), 2); + for r in &recs { + assert!(header_values(r, "x-ap-caller-key").is_empty()); + assert!( + !r.uri.contains("/ap/") && !r.uri.contains(&t.key), + "{}", + r.uri + ); + for (_, v) in &r.headers { + assert!(!String::from_utf8_lossy(v).contains(&t.key)); + } + } + assert!(recs[1].uri.ends_with("/hold/b")); + t.assert_clean(); +} + +#[tokio::test] +async fn an_empty_body_is_still_forwarded_and_confirmed() { + let mock = Mock::start().await; + let t = Ht::new("empty", &mock.up).await; + let (p, _) = t.approved(t.post("/discord/hold/ok", "")).await; + assert_eq!(p.status, 200); + let recs = mock.recorded(); + assert_eq!(recs.len(), 1); + assert!(recs[0].body.is_empty()); + // Chunked, because hyper never polls the body of a zero-length request, which would skip + // milestone 1. + assert_eq!( + header_values(&recs[0], "transfer-encoding"), + [&b"chunked"[..]] + ); + assert!(header_values(&recs[0], "content-length").is_empty()); + assert_eq!( + t.transitions(), + ["held", "approved", "forward_started", "completed"] + ); +} + +// ---------------------------------------------------------------- 4, 5, 23 + +#[tokio::test] +async fn deny_sends_nothing_and_a_cooldown_follows() { + let mock = Mock::start().await; + let mut o = Opts::default(); + o.limits.cooldown = Duration::from_secs(30); + let t = Ht::with("deny", &mock.up, o).await; + let h = t.spawn(t.post("/discord/hold/ok", "{}")); + let id = t.held(1).await; + assert_eq!(t.app.hold.deny(&id, "alice"), DenyResult::Denied); + let (p, b) = h.await.unwrap().unwrap(); + assert_eq!(p.status, 423); + assert_eq!(decision(&p), "denied"); + assert_eq!(code(&b), "human_denied"); + assert_eq!(mock.hits(), 0); + assert_eq!(t.transitions(), ["held", "denied"]); + let denied = t + .lines() + .into_iter() + .find(|v| v["transition"] == "denied") + .unwrap(); + assert_eq!(denied["approver"], "alice"); + // The slot is free, and the identity is in cooldown. + assert_eq!(t.app.hold.pending_len(), 0); + let (p, b) = t.send(t.post("/discord/hold/ok", "{}")).await.unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (503, "unavailable".into(), "cooldown".into()) + ); + // Approving the denied entry changes nothing. + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::AlreadyDecided + ); + assert_eq!(mock.hits(), 0); +} + +#[tokio::test] +async fn a_zero_cooldown_lets_the_next_request_be_held_at_once() { + let mock = Mock::start().await; + let t = Ht::new("nocool", &mock.up).await; + let h = t.spawn(t.post("/discord/hold/ok", "{}")); + let id = t.held(1).await; + t.app.hold.deny(&id, "alice"); + h.await.unwrap().unwrap(); + let h2 = t.spawn(t.post("/discord/hold/ok", "{}")); + let id2 = t.held(2).await; + assert_eq!(t.app.hold.state(&id2), Some(State::Pending)); + t.app.hold.deny(&id2, "alice"); + h2.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn expiry_answers_410_without_retry_after_and_sends_nothing() { + let mock = Mock::start().await; + let mut o = Opts::default(); + o.limits.hold = Duration::from_millis(400); + o.limits.cooldown = Duration::from_secs(30); + let t = Ht::with("expire", &mock.up, o).await; + let start = Instant::now(); + let (p, b) = t.send(t.post("/discord/hold/ok", "{}")).await.unwrap(); + assert!(start.elapsed() >= Duration::from_millis(350)); + assert_eq!(p.status, 410); + assert_eq!(decision(&p), "expired"); + assert_eq!(code(&b), "expired"); + assert!(p.headers.get("retry-after").is_none()); + assert_eq!(mock.hits(), 0); + assert_eq!(t.transitions(), ["held", "expired"]); + let id = t.held(1).await; + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::Expired + ); + // An expiry starts the cooldown. + let (p, b) = t.send(t.post("/discord/hold/ok", "{}")).await.unwrap(); + assert_eq!((p.status.as_u16(), code(&b)), (503, "cooldown".into())); +} + +// ---------------------------------------------------------------- 6, 14, 20 + +#[tokio::test] +async fn caps_and_unavailable_rows_send_nothing() { + let mock = Mock::start().await; + let mut o = Opts::default(); + o.limits.max_per_identity = 1; + o.limits.max_total = 2; + let t = Ht::with("caps", &mock.up, o).await; + let a1 = t.spawn(t.post("/discord/hold/ok", r#"{"n":1}"#)); + t.held(1).await; + // A second distinct request from the same identity: per-identity cap. + let (p, b) = t + .send(t.post("/discord/hold/ok", r#"{"n":2}"#)) + .await + .unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (503, "unavailable".into(), "identity_cap".into()) + ); + // Another identity is accepted. + let b1 = t.spawn(t.post_other("/discord/hold/ok", r#"{"n":3}"#)); + t.held(2).await; + assert_eq!(t.app.hold.pending_len(), 2); + // Policy file removed: 503 policy_unavailable. + std::fs::remove_file(&t.policy).unwrap(); + let (p, b) = t + .send(t.post("/discord/hold/ok", r#"{"n":4}"#)) + .await + .unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (503, "unavailable".into(), "policy_unavailable".into()) + ); + // Shutdown answers every Pending entry 503 shutdown. + assert_eq!(t.app.hold.drain_pending(), 2); + for h in [a1, b1] { + let (p, b) = h.await.unwrap().unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (503, "unavailable".into(), "shutdown".into()) + ); + } + assert_eq!(mock.hits(), 0); + t.assert_clean(); +} + +#[tokio::test] +async fn a_full_table_refuses_and_a_reload_drop_answers_503() { + let mock = Mock::start().await; + let mut o = Opts::default(); + o.limits.max_total = 2; + let t = Ht::with("full", &mock.up, o).await; + let a = t.spawn(t.post("/discord/hold/ok", r#"{"n":1}"#)); + let b = t.spawn(t.post("/discord/hold/ok", r#"{"n":2}"#)); + t.held(2).await; + let (p, body) = t + .send(t.post_other("/discord/hold/ok", r#"{"n":3}"#)) + .await + .unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&body)), + (503, "unavailable".into(), "table_full".into()) + ); + assert_eq!(t.app.hold.drop_all(), 2); + for h in [a, b] { + let (p, body) = h.await.unwrap().unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&body)), + (503, "unavailable".into(), "dropped_on_reload".into()) + ); + } + assert_eq!(t.count("dropped_on_reload"), 2); + assert_eq!(mock.hits(), 0); +} + +#[tokio::test] +async fn an_identical_retry_supersedes_and_one_approval_makes_one_request() { + let mock = Mock::start().await; + let t = Ht::new("supersede", &mock.up).await; + let first = t.spawn(t.post("/discord/hold/ok", r#"{"same":true}"#)); + let id1 = t.held(1).await; + // Ten rapid identical retries leave one entry. + let mut retries = Vec::new(); + for n in 2..=11 { + retries.push(t.spawn(t.post("/discord/hold/ok", r#"{"same":true}"#))); + t.held(n).await; + } + assert_eq!(t.app.hold.pending_len(), 1); + let (p, b) = first.await.unwrap().unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (503, "unavailable".into(), "superseded".into()) + ); + let newest = t.held(11).await; + assert!(matches!( + t.app.hold.approve(&id1, "alice").await, + ApproveResult::Superseded { newest: n } if n == newest + )); + // A changed Authorization is a different request with its own entry. + let other = t.spawn( + Request::builder() + .method("POST") + .uri("/discord/hold/ok") + .header("host", AUTH) + .header("x-ap-caller-key", t.key.as_str()) + .header("authorization", "Bot something-else") + .header("content-type", "application/json") + .header("content-length", 13) + .body(Body::from(r#"{"same":true}"#)) + .unwrap(), + ); + t.held(12).await; + assert_eq!(t.app.hold.pending_len(), 2); + assert_eq!( + t.app.hold.approve(&newest, "alice").await, + ApproveResult::Success + ); + let last = retries.pop().unwrap(); + assert_eq!(last.await.unwrap().unwrap().0.status, 200); + for r in retries { + let (p, _) = r.await.unwrap().unwrap(); + assert_eq!(p.status, 503); + } + assert_eq!(mock.recorded().len(), 1); + assert_eq!(t.count("superseded"), 10); + t.app.hold.deny(&t.held(12).await, "alice"); + other.await.unwrap().unwrap(); +} + +// ---------------------------------------------------------------- 8 + +#[tokio::test] +async fn disconnect_before_approve_frees_the_slot_and_approve_says_gone() { + let mock = Mock::start().await; + let t = Ht::new("gone", &mock.up).await; + let h = t.spawn(t.post("/discord/hold/ok", "{}")); + let id = t.held(1).await; + h.abort(); + until("abandoned", || { + t.app.hold.state(&id) == Some(State::Abandoned) + }) + .await; + assert_eq!(t.app.hold.pending_len(), 0); + assert_eq!(t.app.hold.approve(&id, "alice").await, ApproveResult::Gone); + assert_eq!(t.count("abandoned"), 1); + assert_eq!(t.count("abandoned_after_approve"), 0); + assert_eq!(mock.hits(), 0); +} + +#[tokio::test] +async fn disconnect_after_approve_before_the_send_sends_nothing() { + let mock = Mock::start().await; + let t = Ht::new("abandoned-after", &mock.up).await; + let gate = Gate::new(); + t.app.pause.set_after_approve(Arc::clone(&gate)); + let h = t.spawn(t.post("/discord/hold/ok", "{}")); + let id = t.held(1).await; + let table = Arc::clone(&t.app.hold); + let approve = tokio::spawn(async move { table.approve(&id, "alice").await }); + gate.arrived().await; + h.abort(); + assert_eq!(approve.await.unwrap(), ApproveResult::ApprovedButAbandoned); + until("abandoned_after_approve", || { + t.count("abandoned_after_approve") == 1 + }) + .await; + assert_eq!(t.count("forward_started"), 0); + assert_eq!(t.count("abandoned"), 0); + assert_eq!(mock.hits(), 0); +} + +// ---------------------------------------------------------------- 15 + +#[tokio::test] +async fn body_rules_refuse_before_anything_is_held_or_sent() { + let mock = Mock::start().await; + let t = Ht::new("rules", &mock.up).await; + let big = "x".repeat(3000); + let mk = |f: &dyn Fn(http::request::Builder) -> http::request::Builder, body: String| { + f(Request::builder() + .method("POST") + .uri("/discord/hold/ok") + .header("host", AUTH) + .header("x-ap-caller-key", t.key.as_str()) + .header("content-length", body.len())) + .body(Body::from(body)) + .unwrap() + }; + let json = |b: http::request::Builder| { + b.header("content-type", "application/json") + .header("authorization", "Bot t") + }; + let cases: Vec<(&str, Request, u16, &str)> = vec![ + ("over cap", mk(&json, big.clone()), 413, "body_too_large"), + ( + "compressed", + mk(&|b| json(b).header("content-encoding", "gzip"), "{}".into()), + 400, + "content_encoding", + ), + ( + "no authorization", + mk( + &|b| b.header("content-type", "application/json"), + "{}".into(), + ), + 400, + "credential_missing", + ), + ( + "multipart in cap", + mk( + &|b| { + b.header("content-type", "multipart/form-data; boundary=x") + .header("authorization", "Bot t") + }, + "--x--".into(), + ), + 400, + "content_type", + ), + ( + "multipart over cap", + mk( + &|b| { + b.header("content-type", "multipart/form-data; boundary=x") + .header("authorization", "Bot t") + }, + big.clone(), + ), + 400, + "content_type", + ), + ( + "no content type", + mk(&|b| b.header("authorization", "Bot t"), "{}".into()), + 400, + "content_type", + ), + ( + "text/plain", + mk( + &|b| { + b.header("content-type", "text/plain") + .header("authorization", "Bot t") + }, + "{}".into(), + ), + 400, + "content_type", + ), + ]; + for (name, req, status, c) in cases { + let (p, b) = t.send(req).await.unwrap(); + assert_eq!(p.status.as_u16(), status, "{name}"); + assert_eq!(decision(&p), "denied", "{name}"); + assert_eq!(code(&b), c, "{name}"); + } + // An undeclared (chunked) body over the cap. + let (tx, mut rx) = tokio::sync::mpsc::channel::>(4); + tx.send(Ok(Bytes::from(vec![b'x'; 3000]))).await.unwrap(); + drop(tx); + let chunked = Body::from_stream(futures_util::stream::poll_fn(move |cx| rx.poll_recv(cx))); + let req = t + .builder(&t.key, "POST", "/discord/hold/ok") + .header("content-type", "application/json") + .header("transfer-encoding", "chunked") + .body(chunked) + .unwrap(); + let (p, b) = t.send(req).await.unwrap(); + assert_eq!( + (p.status.as_u16(), code(&b)), + (413, "body_too_large".into()) + ); + assert_eq!(mock.hits(), 0); + assert_eq!(t.app.hold.pending_len(), 0); + assert!(t.held_ids().is_empty()); +} + +#[tokio::test] +async fn a_stalled_held_body_is_503_and_not_held() { + let mock = Mock::start().await; + let t = Ht::new("stall-body", &mock.up).await; + let (_tx, mut rx) = tokio::sync::mpsc::channel::>(4); + let stalled = Body::from_stream(futures_util::stream::poll_fn(move |cx| rx.poll_recv(cx))); + let req = t + .builder(&t.key, "POST", "/discord/hold/ok") + .header("content-type", "application/json") + .header("transfer-encoding", "chunked") + .body(stalled) + .unwrap(); + let (p, b) = t.send(req).await.unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (503, "unavailable".into(), "body_read_timeout".into()) + ); + assert!(t.held_ids().is_empty()); +} + +// ---------------------------------------------------------------- 17 + +async fn failed_connect(t: &Ht, mock_hits: &dyn Fn() -> usize) { + let h = t.spawn(t.post("/discord/hold/ok", "{}")); + let id = t.held(1).await; + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::ConnectFailed + ); + let (p, b) = h.await.unwrap().unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (503, "unavailable".into(), "connect_failed".into()) + ); + assert_eq!(t.transitions(), ["held", "approved", "connect_failed"]); + assert_eq!(mock_hits(), 0); +} + +#[tokio::test] +async fn a_refused_connection_is_connect_failed_with_no_forward_started() { + let mock = Mock::start().await; + let dead = { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + l.local_addr().unwrap().port() + }; + let o = Opts { + port: Some(dead), + ..Opts::default() + }; + let t = Ht::with("refused", &mock.up, o).await; + failed_connect(&t, &|| mock.hits()).await; +} + +#[tokio::test] +async fn a_failed_tls_handshake_is_connect_failed_with_no_forward_started() { + // Accepts the TCP connection and closes it, so the handshake fails. + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = l.local_addr().unwrap().port(); + let accepted = Arc::new(AtomicUsize::new(0)); + let a = Arc::clone(&accepted); + tokio::spawn(async move { + while let Ok((s, _)) = l.accept().await { + a.fetch_add(1, Ordering::SeqCst); + drop(s); + } + }); + let mock = Mock::start().await; + let o = Opts { + port: Some(port), + ..Opts::default() + }; + let t = Ht::with("tls-fail", &mock.up, o).await; + failed_connect(&t, &|| 0).await; + assert!(accepted.load(Ordering::SeqCst) >= 1); +} + +#[tokio::test] +async fn a_reset_after_forward_started_closes_the_caller_with_no_completed() { + let mock = Mock::start().await; + let t = Ht::new("reset", &mock.up).await; + for (n, path) in [ + "/discord/hold/reset-after-read", + "/discord/hold/reset-before-read", + ] + .into_iter() + .enumerate() + { + let h = t.spawn(t.post(path, "{}")); + let id = t.held(n + 1).await; + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::Success + ); + assert!( + h.await.unwrap().is_err(), + "{path}: connection must close without an answer" + ); + } + assert_eq!(t.count("forward_started"), 2); + assert_eq!(t.count("completed"), 0); +} + +// ---------------------------------------------------------------- 25 + +#[tokio::test] +async fn approved_requests_are_closed_at_the_idle_and_total_deadlines() { + let mock = Mock::start().await; + let o = Opts { + extra: "request_deadline_secs = 2\nupstream_idle_secs = 1".into(), + ..Opts::default() + }; + let t = Ht::with("deadlines", &mock.up, o).await; + + // No byte for upstream_idle_secs after the head: the body ends in an error. + let start = Instant::now(); + let n = t.held_ids().len() + 1; + let h = t.spawn(t.post("/discord/hold/stall-body", "{}")); + let id = t.held(n).await; + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::Success + ); + let (p, b) = h.await.unwrap().unwrap(); + assert_eq!(p.status, 200); + assert_eq!(&b[..], b"", "body is cut when it errors"); + let took = start.elapsed(); + assert!( + took >= Duration::from_millis(900) && took < Duration::from_millis(1900), + "{took:?}" + ); + + // A trickle never idles, so the total deadline closes it. + let start = Instant::now(); + let n = t.held_ids().len() + 1; + let h = t.spawn(t.post("/discord/hold/trickle", "{}")); + let id = t.held(n).await; + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::Success + ); + h.await.unwrap().unwrap(); + let took = start.elapsed(); + assert!( + took >= Duration::from_millis(1800) && took < Duration::from_millis(3200), + "{took:?}" + ); + + // No answer at all: the total deadline, counted from forward_started, closes the caller. + let start = Instant::now(); + let n = t.held_ids().len() + 1; + let h = t.spawn(t.post("/discord/hold/stall", "{}")); + let id = t.held(n).await; + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::Success + ); + assert!(h.await.unwrap().is_err()); + let took = start.elapsed(); + assert!( + took >= Duration::from_millis(1800) && took < Duration::from_millis(3200), + "{took:?}" + ); + // Reset and timeouts after forward_started write no `completed`. + assert_eq!(t.count("forward_started"), 3); + assert_eq!(t.count("completed"), 0); +} + +// ---------------------------------------------------------------- 29 + +#[tokio::test] +async fn a_failing_sink_before_the_hold_refuses_the_write_and_lets_reads_pass() { + let mock = Mock::start().await; + let sw = Switch::default(); + let o = Opts { + sink: Some(sw.clone()), + ..Opts::default() + }; + let t = Ht::with("sink-before", &mock.up, o).await; + sw.fail_all.store(true, Ordering::SeqCst); + let (p, b) = t.send(t.post("/discord/hold/ok", "{}")).await.unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (503, "unavailable".into(), "audit_unavailable".into()) + ); + assert_eq!(t.app.hold.pending_len(), 0); + assert_eq!(mock.hits(), 0); + // An allowed read still passes with the sink down. + let (p, _) = t + .send( + t.builder(&t.key, "GET", "/discord/api/x") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(p.status, 200); + // And a refusal for the failure did not start a cooldown. + sw.fail_all.store(false, Ordering::SeqCst); + let h = t.spawn(t.post("/discord/hold/ok", "{}")); + t.held(1).await; + t.app.hold.drain_pending(); + h.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn a_failing_sink_between_approve_and_send_sends_nothing() { + let raw = Raw::start().await; + let sw = Switch::default(); + let mut o = Opts { + sink: Some(sw.clone()), + ..Opts::default() + }; + o.limits.cooldown = Duration::from_secs(30); + let t = Ht::with("sink-between", &raw.up, o).await; + let h = t.spawn(t.post("/discord/hold/ok", "{}")); + let id = t.held(1).await; + *sw.fail_on.lock().unwrap() = Some("\"forward_started\"".into()); + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::AuditUnavailable + ); + let (p, b) = h.await.unwrap().unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (503, "unavailable".into(), "audit_unavailable".into()) + ); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!( + raw.bytes.load(Ordering::SeqCst), + 0, + "request bytes reached the upstream" + ); + assert_eq!(t.count("forward_started"), 0); + // A sink failure is not the identity's doing: no cooldown. + *sw.fail_on.lock().unwrap() = None; + let h2 = t.spawn(t.post("/discord/hold/ok", "{}")); + let id2 = t.held(2).await; + assert_eq!(t.app.hold.state(&id2), Some(State::Pending)); + t.app.hold.deny(&id2, "alice"); + h2.await.unwrap().unwrap(); +} + +// ---------------------------------------------------------------- 18, 19 (direct), 24 + +async fn raw_exchange(addr: SocketAddr, head: String, body_len: usize) -> String { + let c = TcpStream::connect(addr).await.unwrap(); + let (mut r, mut w) = c.into_split(); + let writer = tokio::spawn(async move { + w.write_all(head.as_bytes()).await.unwrap(); + let chunk = vec![b'a'; 16 * 1024]; + let mut left = body_len; + while left > 0 { + let n = left.min(chunk.len()); + if w.write_all(&chunk[..n]).await.is_err() { + break; + } + left -= n; + } + w + }); + let mut out = Vec::new(); + let mut buf = [0u8; 4096]; + loop { + match tokio::time::timeout(Duration::from_secs(5), r.read(&mut buf)).await { + Ok(Ok(0)) | Err(_) => break, + Ok(Ok(n)) => { + out.extend_from_slice(&buf[..n]); + if out.windows(4).any(|w| w == b"\r\n\r\n") + && String::from_utf8_lossy(&out).contains("\"code\"") + { + break; + } + } + Ok(Err(_)) => break, + } + } + let _ = writer.await; + String::from_utf8_lossy(&out).into_owned() +} + +#[tokio::test] +async fn a_denied_one_mebibyte_post_gets_a_readable_423() { + let mock = Mock::start().await; + let o = Opts { + held_body_max: 1024 * 1024, + ..Opts::default() + }; + let t = Ht::with("big-denied", &mock.up, o).await; + let addr = t.serve().await; + let len = 1024 * 1024; + // No grant for this path, and a hold route refused on content type. + for (path, ctype, want_status, want_code) in [ + ("/discord/nogrant/x", "application/json", "423", "no_grant"), + ("/discord/hold/ok", "text/plain", "400", "content_type"), + ] { + let head = format!( + "POST {path} HTTP/1.1\r\nHost: {AUTH}\r\nx-ap-caller-key: {}\r\nauthorization: Bot t\r\ncontent-type: {ctype}\r\ncontent-length: {len}\r\n\r\n", + t.key + ); + let out = raw_exchange(addr, head, len).await; + assert!( + out.starts_with(&format!("HTTP/1.1 {want_status}")), + "{path}: {out:?}" + ); + assert!(out.contains(want_code), "{path}: {out:?}"); + } + assert_eq!(mock.hits(), 0); +} + +#[tokio::test] +async fn expect_continue_refusals_skip_the_drain() { + let mock = Mock::start().await; + // The drain would wait `body_read_secs` (1 s in this fixture) for a body that never comes. + let t = Ht::new("expect", &mock.up).await; + let addr = t.serve().await; + let head = format!( + "POST /discord/nogrant/x HTTP/1.1\r\nHost: {AUTH}\r\nx-ap-caller-key: {}\r\nauthorization: Bot t\r\ncontent-type: application/json\r\ncontent-length: 1048576\r\nexpect: 100-continue\r\n\r\n", + t.key + ); + let start = Instant::now(); + // No body follows the head: the client waits for `100 Continue`, which never comes. + let out = raw_exchange(addr, head, 0).await; + assert!(out.starts_with("HTTP/1.1 423"), "{out:?}"); + assert!( + start.elapsed() < Duration::from_millis(800), + "{:?}", + start.elapsed() + ); +} + +#[cfg(not(feature = "stage1-probe"))] +#[tokio::test] +async fn the_probe_route_does_not_exist_without_the_feature() { + let mock = Mock::start().await; + let o = Opts { + tail: "\n[probe]\nenabled = true\n".into(), + ..Opts::default() + }; + let t = Ht::with("no-probe", &mock.up, o).await; + let (p, b) = t + .send( + t.builder(&t.key, "GET", "/__ap_probe/sleep/1") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + (p.status.as_u16(), decision(&p), code(&b)), + (423, "denied".into(), "route_unknown".into()) + ); + assert_eq!(mock.hits(), 0); +} + +#[tokio::test] +async fn webhook_path_tokens_are_redacted_in_every_hold_record() { + let mock = Mock::start().await; + let t = Ht::new("tokens", &mock.up).await; + let path = format!("/discord/webhooks/1/{PATH_TOKEN}"); + let (p, _) = t.approved(t.post(&path, "{}")).await; + assert_eq!(p.status, 200); + assert!( + mock.recorded()[0].uri.contains(PATH_TOKEN), + "the upstream still gets the token" + ); + assert!(t.text().contains("")); + t.assert_clean(); +} diff --git a/crates/ap-proxy/src/passthrough/pause.rs b/crates/ap-proxy/src/passthrough/pause.rs new file mode 100644 index 0000000..a7c9775 --- /dev/null +++ b/crates/ap-proxy/src/passthrough/pause.rs @@ -0,0 +1,125 @@ +//! Test-only pause points in the approved-request path. Compiled for unit tests and for the +//! `matrix-upstream` feature only; a default build has none of it. +//! +//! A [`Gate`] lets a test see that the handler reached a point and then hold it there. The +//! blocking wait is for a point inside a poll of the request body stream, where an `.await` +//! would let the HTTP client flush buffered bytes. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; + +use tokio::sync::Notify; + +/// A rendezvous: the handler calls `arrive` and waits; the test waits for `arrived` and calls +/// `release`. +#[derive(Default)] +#[cfg_attr(not(test), allow(dead_code))] +pub struct Gate { + arrived: Notify, + open: Mutex, + cv: Condvar, + opened: Notify, +} + +#[cfg_attr(not(test), allow(dead_code))] +impl Gate { + pub fn new() -> Arc { + Arc::new(Gate::default()) + } + + /// Wait until the handler has reached the gate. + pub async fn arrived(&self) { + self.arrived.notified().await; + } + + /// Let the handler go. + pub fn release(&self) { + if let Ok(mut open) = self.open.lock() { + *open = true; + } + self.cv.notify_all(); + self.opened.notify_waiters(); + } + + fn is_open(&self) -> bool { + self.open.lock().map(|g| *g).unwrap_or(true) + } + + pub(super) async fn pass_async(&self) { + self.arrived.notify_one(); + loop { + let n = self.opened.notified(); + tokio::pin!(n); + n.as_mut().enable(); + if self.is_open() { + return; + } + n.await; + } + } + + pub(super) fn pass_blocking(&self) { + self.arrived.notify_one(); + let Ok(mut open) = self.open.lock() else { + return; + }; + while !*open { + match self.cv.wait(open) { + Ok(g) => open = g, + Err(_) => return, + } + } + } +} + +#[derive(Default)] +pub struct Pause { + after_approve: Mutex>>, + between_milestones: Mutex>>, + after_approve_ms: AtomicU64, +} + +#[cfg_attr(not(test), allow(dead_code))] +impl Pause { + pub fn new() -> Pause { + let p = Pause::default(); + #[cfg(feature = "matrix-upstream")] + p.after_approve_ms + .store(crate::matrix_hooks::hold_pause_ms(), Ordering::Relaxed); + p + } + + /// Hold the handler between the `Approved` transition and the upstream send. + pub fn set_after_approve(&self, gate: Arc) { + if let Ok(mut g) = self.after_approve.lock() { + *g = Some(gate); + } + } + + /// Hold the handler between the two milestones: after `forward_started` is written and before + /// the first request body chunk is handed over. The wait blocks the polling thread. + pub fn set_between_milestones(&self, gate: Arc) { + if let Ok(mut g) = self.between_milestones.lock() { + *g = Some(gate); + } + } + + pub(super) async fn after_approve(&self) { + let gate = self.after_approve.lock().ok().and_then(|g| g.clone()); + if let Some(g) = gate { + g.pass_async().await; + } + let ms = self.after_approve_ms.load(Ordering::Relaxed); + if ms > 0 { + tokio::time::sleep(Duration::from_millis(ms)).await; + } + } + + pub(super) fn between_milestones(&self) { + let gate = self.between_milestones.lock().ok().and_then(|g| g.clone()); + if let Some(g) = gate { + g.pass_blocking(); + } + } +} From dc6d0d32666f75b97d2b8a997981012957de9287 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:08:38 -0500 Subject: [PATCH 04/16] feat(ap-proxy): approval plane listener, Basic auth, CSRF and page A second loopback listener (approval.listen) serves the approval API and page (design 3.6). It is its own socket, router and credential: the public router mounts no /pending route, the caller key is refused here and the approver credential is refused on the public listener. - listener/approval.rs: hyper http1 accept loop, 16 connections, 10 s header read, 16 KiB header buffer. run_passthrough binds it only when [approval] exists and serves it next to the public listener (either stopping ends the process). - approval/auth.rs: one Basic user, sha256 of the password compared in constant time, one Authorization header only, 250 ms wait before a 401 with the Basic realm. - approval/csrf.rs: random per-view token bound to the entry id, single use, 4 per entry and 256 in total, dies with the entry or hold_secs. - approval/{mod,page}.rs: GET /pending, GET /pending/ (HTML or JSON on Accept), POST /pending//approve|deny with a form or JSON csrf field and a 1 KiB body limit; ApproveResult/DenyResult map to {"result"} with 200 only for success; the approver name goes into the audit transition. Pages escape everything, carry no script or style, show credential headers as present and the body as escaped text with a banner when not UTF-8, and a superseded entry shows a banner, a link to the newest id and disabled buttons. harden() adds the six headers to every response. - hold::Table::list() (admission order), digest::random_hex made pub, base64 is now a normal dependency of ap-proxy. Verified on macmini: cargo fmt --all --check; clippy -D warnings (workspace all-targets, stage1-probe, matrix-upstream+stage1-probe) clean; cargo test --workspace ok (ap-proxy lib 174); cargo test -p ap-proxy approval ok (38 tests: headers on 200/401/404/405/413/400/403, realm, CSRF missing/reused/wrong entry, script body escaped, no credential in page or JSON, concurrent HTTP approves = one success + one upstream request, approve after each state, cross-credential refusals both ways, no /pending route on the public router); ap-proxy --features stage1-probe --lib ok (178); matrix_passthrough (16 stage 1 rows) ok. --- crates/ap-proxy/Cargo.toml | 2 +- crates/ap-proxy/src/approval/auth.rs | 159 ++++ crates/ap-proxy/src/approval/csrf.rs | 170 ++++ crates/ap-proxy/src/approval/mod.rs | 354 +++++++++ crates/ap-proxy/src/approval/page.rs | 328 ++++++++ crates/ap-proxy/src/approval/tests.rs | 939 +++++++++++++++++++++++ crates/ap-proxy/src/hold/digest.rs | 2 +- crates/ap-proxy/src/hold/entry.rs | 2 + crates/ap-proxy/src/hold/mod.rs | 19 + crates/ap-proxy/src/hold/tests.rs | 13 + crates/ap-proxy/src/lib.rs | 33 +- crates/ap-proxy/src/listener.rs | 1 + crates/ap-proxy/src/listener/approval.rs | 71 ++ 13 files changed, 2089 insertions(+), 4 deletions(-) create mode 100644 crates/ap-proxy/src/approval/auth.rs create mode 100644 crates/ap-proxy/src/approval/csrf.rs create mode 100644 crates/ap-proxy/src/approval/mod.rs create mode 100644 crates/ap-proxy/src/approval/page.rs create mode 100644 crates/ap-proxy/src/approval/tests.rs create mode 100644 crates/ap-proxy/src/listener/approval.rs diff --git a/crates/ap-proxy/Cargo.toml b/crates/ap-proxy/Cargo.toml index fce3e46..46484ab 100644 --- a/crates/ap-proxy/Cargo.toml +++ b/crates/ap-proxy/Cargo.toml @@ -16,6 +16,7 @@ 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" @@ -50,7 +51,6 @@ path = "tests/matrix_passthrough.rs" required-features = ["matrix-upstream"] [dev-dependencies] -base64 = "0.22" h2 = "0.4" http-body-util = "0.1" rcgen = "0.13" 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..eff3e86 --- /dev/null +++ b/crates/ap-proxy/src/approval/mod.rs @@ -0,0 +1,354 @@ +//! 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
, + 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() + } +} + +impl ApprovalApp { + pub fn new(table: Arc
, cfg: &Approval) -> Arc { + Self::build(table, cfg, FAIL_DELAY) + } + + fn build(table: Arc
, cfg: &Approval, fail_delay: Duration) -> Arc { + Arc::new(ApprovalApp { + table, + 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())) +} + +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(app.table.approve(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::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..592e03c --- /dev/null +++ b/crates/ap-proxy/src/approval/page.rs @@ -0,0 +1,328 @@ +//! 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("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("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(), + 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("