From 2e5f015a6cba44164fe9b3bda4e490acf4df08d0 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:59:58 -0500 Subject: [PATCH 1/2] feat(muse): asynchronous polling for the held Muse route Implements docs/design/muse-async-poll.md: [passthrough] hold_mode = async answers 202 with request_id and a 128-bit poll token (sha256 stored, constant-time compare); GET /poll/?wait=N returns pending or a final status (approved_and_sent, denied, expired, dropped, send_failed, send_unknown) for 60 s, then a uniform 404. Reuses the hold table, start claim, audit writer and Telegram notification; blocking stays default. Checks (macmini arm64, umask 022, ~/tmp/auth-proxy-muse-async-poll-impl-20261122105632): - cargo fmt --check: exit 0 - cargo clippy --workspace --all-targets -- -D warnings: exit 0 - cargo test --workspace: exit 0, no failures (known reds: netguard x3 under umask 0002, matrix PT-09/P1-09; not triggered) --- crates/ap-core/src/config.rs | 40 ++ crates/ap-proxy/src/async_poll.rs | 317 ++++++++++ crates/ap-proxy/src/async_poll/tests.rs | 188 ++++++ crates/ap-proxy/src/hold/mod.rs | 71 ++- crates/ap-proxy/src/lib.rs | 1 + crates/ap-proxy/src/passthrough.rs | 22 +- .../ap-proxy/src/passthrough/async_tests.rs | 547 ++++++++++++++++++ crates/ap-proxy/src/passthrough/hold_path.rs | 28 +- .../src/passthrough/hold_path/async_mode.rs | 355 ++++++++++++ crates/ap-proxy/src/passthrough/hold_tests.rs | 9 + 10 files changed, 1575 insertions(+), 3 deletions(-) create mode 100644 crates/ap-proxy/src/async_poll.rs create mode 100644 crates/ap-proxy/src/async_poll/tests.rs create mode 100644 crates/ap-proxy/src/passthrough/async_tests.rs create mode 100644 crates/ap-proxy/src/passthrough/hold_path/async_mode.rs diff --git a/crates/ap-core/src/config.rs b/crates/ap-core/src/config.rs index fc5ce53..dd4ef16 100644 --- a/crates/ap-core/src/config.rs +++ b/crates/ap-core/src/config.rs @@ -138,6 +138,24 @@ pub struct Passthrough { /// Seconds an identity is refused after a human deny, 0..=3600 (0 disables). #[serde(default = "default_cooldown_secs")] pub cooldown_secs: u64, + /// `blocking` (default) keeps the caller's connection open while a request is held. `async` + /// answers 202 with a poll token and the caller polls `GET /poll/` (design + /// `muse-async-poll.md`). + #[serde(default)] + pub hold_mode: HoldMode, + /// In `async` mode, how long an unapproved entry stays pending before it ends as `expired`, + /// 5..=600. Ignored in `blocking` mode, where `hold_secs` applies. + #[serde(default = "default_hold_secs")] + pub async_hold_secs: u64, +} + +/// How a held request is answered to its caller. +#[derive(Debug, Deserialize, Clone, Copy, Default, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum HoldMode { + #[default] + Blocking, + Async, } fn default_hold_secs() -> u64 { @@ -643,6 +661,7 @@ fn validate_passthrough(p: &Passthrough) -> Result<(), ConfigError> { } for (field, v, min, max) in [ ("hold_secs", p.hold_secs, 5, 600), + ("async_hold_secs", p.async_hold_secs, 5, 600), ( "held_body_max_bytes", p.held_body_max_bytes, @@ -2151,6 +2170,8 @@ paths = ["/api/v10/channels/", "/api/v10/users/@me"] for (k, v) in [ ("hold_secs", "4"), ("hold_secs", "601"), + ("async_hold_secs", "4"), + ("async_hold_secs", "601"), ("held_body_max_bytes", "0"), ("held_body_max_bytes", "8388609"), ("max_held_total", "0"), @@ -2172,6 +2193,25 @@ paths = ["/api/v10/channels/", "/api/v10/users/@me"] assert!(load(&ok).is_ok()); } + #[test] + fn hold_mode_defaults_to_blocking_and_accepts_async() { + let p = load(&hold_text()).unwrap().passthrough.unwrap(); + assert_eq!(p.hold_mode, HoldMode::Blocking); + assert_eq!(p.async_hold_secs, 120); + let text = hold_text().replace( + "public_authority = \"gate.example.test\"", + "public_authority = \"gate.example.test\"\nhold_mode = \"async\"\nasync_hold_secs = 30", + ); + let p = load(&text).unwrap().passthrough.unwrap(); + assert_eq!(p.hold_mode, HoldMode::Async); + assert_eq!(p.async_hold_secs, 30); + let bad = hold_text().replace( + "public_authority = \"gate.example.test\"", + "public_authority = \"gate.example.test\"\nhold_mode = \"sync\"", + ); + assert!(load(&bad).is_err()); + } + 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 = \"telegram\"\ntoken_file = \"/etc/ap/telegram-token\"\nchat_id = \"-1001234567890\"\napproval_url_base = \"https://approve.example.test\"\n" diff --git a/crates/ap-proxy/src/async_poll.rs b/crates/ap-proxy/src/async_poll.rs new file mode 100644 index 0000000..132c0d7 --- /dev/null +++ b/crates/ap-proxy/src/async_poll.rs @@ -0,0 +1,317 @@ +//! The poll side of the Muse async hold mode (`docs/design/muse-async-poll.md`). +//! +//! An admitted request gets a random poll token. The store keeps only the sha256 of the token, the +//! request id and the state. `GET /poll/?wait=N` reads the state and never changes it: the +//! token cannot approve, deny or cancel anything. A final status stays readable for +//! [`FINAL_WINDOW_SECS`] from the transition, on the app clock; afterwards, and for any token the +//! store does not know, the answer is one uniform 404. Nothing here is persistent, so a restart +//! forgets every entry. + +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use ap_broker::registry::sha256_hex; +use axum::body::Body; +use http::{header, HeaderValue, Response, StatusCode}; +use serde_json::{json, Value}; +use tokio::sync::Notify; +use tokio::time::Instant; + +use crate::hold::digest::{ct_eq, random_hex}; + +/// How long a final status stays readable, from the final transition. +pub const FINAL_WINDOW_SECS: u64 = 60; +/// Longest `wait` a poll may ask for. +pub const MAX_WAIT_SECS: u64 = 25; +/// Largest Discord response body kept for a poll. +pub const BODY_MAX: usize = 64 * 1024; +/// Polls one token may make in one clock second before it is answered 429. +const POLLS_PER_SEC: u32 = 10; + +/// How a held request ended, as the poll reports it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Final { + Approved { + discord_status: u16, + body: Vec, + truncated: bool, + }, + Denied, + Expired, + Dropped, + SendFailed, + /// Past the first request byte with no confirmed Discord response. `error_class` is `reset`, + /// `timeout` or `write_failed`. + SendUnknown(&'static str), +} + +#[derive(Clone)] +enum State { + Pending, + Final { at: u64, out: Final }, +} + +struct Slot { + /// sha256 hex of the poll token. + key: String, + request_id: String, + state: State, + notify: Arc, + /// Rate-limit window: the clock second and the polls seen in it. + second: u64, + polls: u32, +} + +/// What a read found. +enum Read { + NotFound, + Limited, + Pending { id: String, notify: Arc }, + Final { id: String, out: Final }, +} + +/// The in-memory poll table. +#[derive(Default)] +pub struct PollStore { + slots: Mutex>, +} + +impl PollStore { + fn lock(&self) -> MutexGuard<'_, Vec> { + match self.slots.lock() { + Ok(g) => g, + Err(p) => p.into_inner(), + } + } + + /// A fresh token for a new pending entry. 128 random bits as hex; only its hash is stored. + pub fn insert(&self, request_id: &str, now: u64) -> String { + let token = random_hex(16); + let mut g = self.lock(); + g.retain(|s| !expired(s, now)); + g.push(Slot { + key: sha256_hex(&token), + request_id: request_id.to_string(), + state: State::Pending, + notify: Arc::new(Notify::new()), + second: now, + polls: 0, + }); + token + } + + /// Record the final status of the entry for `request_id`. The first one wins. + pub fn finish(&self, request_id: &str, out: Final, now: u64) { + let mut g = self.lock(); + if let Some(s) = g.iter_mut().find(|s| s.request_id == request_id) { + if matches!(s.state, State::Pending) { + s.state = State::Final { at: now, out }; + s.notify.notify_waiters(); + } + } + } + + /// Whether any entry for `request_id` is still pending. + #[cfg(test)] + pub fn pending_len(&self) -> usize { + self.lock() + .iter() + .filter(|s| matches!(s.state, State::Pending)) + .count() + } + + fn read(&self, token: &str, now: u64, count: bool) -> Read { + let key = sha256_hex(token); + let mut g = self.lock(); + g.retain(|s| !expired(s, now)); + // Every slot is compared, so the time taken does not show which one matched. + let mut hit = None; + for (i, s) in g.iter().enumerate() { + if ct_eq(&s.key, &key) { + hit = Some(i); + } + } + let Some(i) = hit else { + return Read::NotFound; + }; + let s = &mut g[i]; + if count { + if s.second != now { + s.second = now; + s.polls = 0; + } + if s.polls >= POLLS_PER_SEC { + return Read::Limited; + } + s.polls += 1; + } + match &s.state { + State::Pending => Read::Pending { + id: s.request_id.clone(), + notify: Arc::clone(&s.notify), + }, + State::Final { out, .. } => Read::Final { + id: s.request_id.clone(), + out: out.clone(), + }, + } + } +} + +fn expired(s: &Slot, now: u64) -> bool { + matches!(&s.state, State::Final { at, .. } if now >= at.saturating_add(FINAL_WINDOW_SECS)) +} + +/// Ends the entry as `dropped` if the task that should finish it goes away without doing so. +pub struct FinishGuard { + store: Arc, + clock: Arc, + request_id: String, +} + +impl FinishGuard { + pub fn new( + store: Arc, + clock: Arc, + request_id: &str, + ) -> FinishGuard { + FinishGuard { + store, + clock, + request_id: request_id.to_string(), + } + } + + pub fn finish(&self, out: Final) { + self.store.finish(&self.request_id, out, self.clock.now()); + } +} + +impl Drop for FinishGuard { + fn drop(&mut self) { + // A no-op when `finish` already ran: the first final status wins. + self.finish(Final::Dropped); + } +} + +fn json_response(status: StatusCode, v: &Value) -> Response { + let mut r = Response::new(Body::from(v.to_string())); + *r.status_mut() = status; + r.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + r.headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + r +} + +/// The one answer for an unknown token, an ended window and any method but GET. +pub fn not_found() -> Response { + json_response(StatusCode::NOT_FOUND, &json!({"error": "not_found"})) +} + +/// The 202 a POST gets in async mode. No body or `Authorization` of the request is in it. +pub fn accepted(request_id: &str, token: &str) -> Response { + json_response( + StatusCode::ACCEPTED, + &json!({"status": "pending", "request_id": request_id, "poll_token": token}), + ) +} + +/// `wait` from the query: missing is 0, an integer above the cap is the cap, anything else (not +/// all digits, empty, repeated) is `None`. +fn parse_wait(query: Option<&str>) -> Option { + let mut found = None; + for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) { + let (k, v) = pair.split_once('=').unwrap_or((pair, "")); + if k != "wait" { + continue; + } + if found.is_some() || v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + // More than nine digits is certainly above the cap. + found = Some(if v.len() > 9 { + MAX_WAIT_SECS + } else { + v.parse::().ok()?.min(MAX_WAIT_SECS) + }); + } + Some(found.unwrap_or(0)) +} + +fn final_json(id: &str, out: &Final) -> Value { + match out { + Final::Approved { + discord_status, + body, + truncated, + } => json!({ + "status": "approved_and_sent", + "request_id": id, + "discord_status": discord_status, + "body": String::from_utf8_lossy(body), + "truncated": truncated, + }), + Final::Denied => json!({"status": "denied", "request_id": id}), + Final::Expired => json!({"status": "expired", "request_id": id}), + Final::Dropped => json!({"status": "dropped", "request_id": id}), + Final::SendFailed => json!({"status": "send_failed", "request_id": id}), + Final::SendUnknown(class) => { + json!({"status": "send_unknown", "request_id": id, "error_class": class}) + } + } +} + +/// Answer `GET /poll/?wait=N`. The caller has already checked the method and the prefix. +pub async fn poll( + store: &PollStore, + clock: &(dyn ap_broker::clock::Clock + Send + Sync), + token: &str, + query: Option<&str>, +) -> Response { + // The wait is checked first, so a bad one says nothing about the token. + let Some(wait) = parse_wait(query) else { + return json_response(StatusCode::BAD_REQUEST, &json!({"error": "bad_wait"})); + }; + let deadline = Instant::now() + Duration::from_secs(wait); + let mut count = true; + loop { + let (id, notify) = match store.read(token, clock.now(), count) { + Read::NotFound => return not_found(), + Read::Limited => { + let mut r = json_response( + StatusCode::TOO_MANY_REQUESTS, + &json!({"error": "rate_limited"}), + ); + r.headers_mut() + .insert(header::RETRY_AFTER, HeaderValue::from_static("1")); + return r; + } + Read::Final { id, out } => { + return json_response(StatusCode::OK, &final_json(&id, &out)) + } + Read::Pending { id, notify } => (id, notify), + }; + count = false; + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return json_response( + StatusCode::OK, + &json!({"status": "pending", "request_id": id}), + ); + } + // Register for the wake-up, then look again, so a final status set in between is seen. + let notified = notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if !matches!(store.read(token, clock.now(), false), Read::Pending { .. }) { + continue; + } + let _ = tokio::time::timeout(left, notified).await; + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ap-proxy/src/async_poll/tests.rs b/crates/ap-proxy/src/async_poll/tests.rs new file mode 100644 index 0000000..e892325 --- /dev/null +++ b/crates/ap-proxy/src/async_poll/tests.rs @@ -0,0 +1,188 @@ +//! The poll store and the poll answer, without a hold table. + +use super::*; +use ap_broker::clock::{Clock, ManualClock}; + +fn clock() -> Arc { + Arc::new(ManualClock::new(1_000)) +} + +async fn get( + store: &PollStore, + clock: &Arc, + token: &str, + query: Option<&str>, +) -> (StatusCode, Value) { + let c: &(dyn Clock + Send + Sync) = clock.as_ref(); + let r = poll(store, c, token, query).await; + let status = r.status(); + let bytes = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + (status, serde_json::from_slice(&bytes).unwrap()) +} + +#[tokio::test] +async fn every_final_status_reads_back_with_its_fields() { + let store = PollStore::default(); + let c = clock(); + let cases = [ + ( + Final::Approved { + discord_status: 200, + body: b"{\"id\":\"1\"}".to_vec(), + truncated: false, + }, + "approved_and_sent", + ), + (Final::Denied, "denied"), + (Final::Expired, "expired"), + (Final::Dropped, "dropped"), + (Final::SendFailed, "send_failed"), + (Final::SendUnknown("reset"), "send_unknown"), + ]; + for (i, (out, name)) in cases.into_iter().enumerate() { + let id = format!("req-{i}"); + let token = store.insert(&id, c.now()); + assert_eq!(get(&store, &c, &token, None).await.1["status"], "pending"); + store.finish(&id, out, c.now()); + let (st, v) = get(&store, &c, &token, None).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(v["status"], name); + assert_eq!(v["request_id"], id); + match name { + "approved_and_sent" => { + assert_eq!(v["discord_status"], 200); + assert_eq!(v["body"], "{\"id\":\"1\"}"); + assert_eq!(v["truncated"], false); + } + "send_unknown" => assert_eq!(v["error_class"], "reset"), + _ => assert_eq!(v.as_object().unwrap().len(), 2, "{v}"), + } + } +} + +#[tokio::test] +async fn first_final_status_wins() { + let store = PollStore::default(); + let c = clock(); + let token = store.insert("r", c.now()); + store.finish("r", Final::Expired, c.now()); + store.finish("r", Final::Denied, c.now()); + assert_eq!(get(&store, &c, &token, None).await.1["status"], "expired"); +} + +#[tokio::test] +async fn final_is_readable_for_sixty_seconds_then_uniform_404() { + let store = PollStore::default(); + let c = clock(); + let token = store.insert("r", c.now()); + store.finish("r", Final::Denied, c.now()); + c.advance(FINAL_WINDOW_SECS - 1); + assert_eq!(get(&store, &c, &token, None).await.0, StatusCode::OK); + c.advance(1); + let gone = get(&store, &c, &token, None).await; + let unknown = get(&store, &c, "0123456789abcdef0123456789abcdef", None).await; + assert_eq!(gone.0, StatusCode::NOT_FOUND); + assert_eq!(gone, unknown, "an ended window looks like an unknown token"); + assert_eq!(store.pending_len(), 0); +} + +#[tokio::test] +async fn pending_does_not_expire_by_the_window() { + let store = PollStore::default(); + let c = clock(); + let token = store.insert("r", c.now()); + c.advance(10_000); + assert_eq!(get(&store, &c, &token, None).await.1["status"], "pending"); +} + +#[tokio::test] +async fn wait_parameter_handling() { + let store = PollStore::default(); + let c = clock(); + let token = store.insert("r", c.now()); + for q in [ + "wait=abc", + "wait=-1", + "wait=", + "wait=1.5", + "wait=+2", + "wait=1&wait=2", + ] { + let (st, v) = get(&store, &c, &token, Some(q)).await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{q}"); + assert_eq!(v["error"], "bad_wait"); + // The same answer for a token that does not exist. + assert_eq!(get(&store, &c, "nope", Some(q)).await, (st, v), "{q}"); + } + assert_eq!(parse_wait(None), Some(0)); + assert_eq!(parse_wait(Some("x=1")), Some(0)); + assert_eq!(parse_wait(Some("wait=7")), Some(7)); + assert_eq!(parse_wait(Some("wait=26")), Some(25)); + assert_eq!(parse_wait(Some("wait=99999999999999999999999")), Some(25)); + assert_eq!(parse_wait(Some("a=1&wait=3")), Some(3)); +} + +#[tokio::test(start_paused = true)] +async fn wait_returns_pending_after_the_wait_and_the_final_status_when_it_arrives() { + let store = Arc::new(PollStore::default()); + let c = clock(); + let token = store.insert("r", c.now()); + let t0 = tokio::time::Instant::now(); + let (_, v) = get(&store, &c, &token, Some("wait=3")).await; + assert_eq!(v["status"], "pending"); + assert_eq!(t0.elapsed(), Duration::from_secs(3)); + // A wait above the cap is cut at 25 s. + let t0 = tokio::time::Instant::now(); + let (_, v) = get(&store, &c, &token, Some("wait=60")).await; + assert_eq!(v["status"], "pending"); + assert_eq!(t0.elapsed(), Duration::from_secs(MAX_WAIT_SECS)); + // A final status wakes the waiter early. + let s2 = Arc::clone(&store); + let c2 = Arc::clone(&c); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(2)).await; + s2.finish("r", Final::Denied, c2.now()); + }); + let t0 = tokio::time::Instant::now(); + let (_, v) = get(&store, &c, &token, Some("wait=20")).await; + assert_eq!(v["status"], "denied"); + assert_eq!(t0.elapsed(), Duration::from_secs(2)); +} + +#[tokio::test] +async fn a_token_is_rate_limited_per_clock_second() { + let store = PollStore::default(); + let c = clock(); + let token = store.insert("r", c.now()); + for _ in 0..POLLS_PER_SEC { + assert_eq!(get(&store, &c, &token, None).await.0, StatusCode::OK); + } + assert_eq!( + get(&store, &c, &token, None).await.0, + StatusCode::TOO_MANY_REQUESTS + ); + c.advance(1); + assert_eq!(get(&store, &c, &token, None).await.0, StatusCode::OK); +} + +#[tokio::test] +async fn the_guard_ends_an_unfinished_entry_as_dropped() { + let store = Arc::new(PollStore::default()); + let c = clock(); + let token = store.insert("r", c.now()); + drop(FinishGuard::new(Arc::clone(&store), c.clone(), "r")); + assert_eq!(get(&store, &c, &token, None).await.1["status"], "dropped"); +} + +#[test] +fn the_token_is_128_bits_and_only_its_hash_is_stored() { + let store = PollStore::default(); + let a = store.insert("a", 0); + let b = store.insert("b", 0); + assert_eq!(a.len(), 32); + assert_ne!(a, b); + let g = store.lock(); + assert!(g + .iter() + .all(|s| s.key != a && s.key == sha256_hex(&a) || s.key == sha256_hex(&b))); +} diff --git a/crates/ap-proxy/src/hold/mod.rs b/crates/ap-proxy/src/hold/mod.rs index 97ba5b9..59bd198 100644 --- a/crates/ap-proxy/src/hold/mod.rs +++ b/crates/ap-proxy/src/hold/mod.rs @@ -53,7 +53,10 @@ pub struct Limits { impl Limits { pub fn from_config(pt: &Passthrough) -> Limits { Limits { - hold: Duration::from_secs(pt.hold_secs), + hold: Duration::from_secs(match pt.hold_mode { + ap_core::config::HoldMode::Blocking => pt.hold_secs, + ap_core::config::HoldMode::Async => pt.async_hold_secs, + }), max_total: pt.max_held_total, max_per_identity: pt.max_held_per_identity, cooldown: Duration::from_secs(pt.cooldown_secs), @@ -279,6 +282,72 @@ impl Table { }) } + /// Admit a new hold in async mode (`muse-async-poll.md`): the `held` record comes first, + /// then the admission checks. There is no fingerprint dedupe and no supersede, so every + /// request is an independent entry. + /// + /// `persist` runs under the table lock, before the cooldown and cap checks. A failed write + /// refuses with `audit_unavailable` and leaves no entry. A refusal after the write leaves the + /// `held` record in the log; the caller writes the terminal record with the refusal's code. + pub fn admit_async(&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); + } + let id = digest::random_hex(16); + if persist(&id, &digest).is_err() { + return Admission::Refused(Code::AuditUnavailable); + } + g.cooldown.retain(|_, until| *until > now); + if g.cooldown.contains_key(identity) { + return Admission::Refused(Code::Cooldown); + } + 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 nonce = digest::random_hex(12); + let view_token = digest::random_hex(16); + let (tx, rx) = oneshot::channel(); + let seq = g.next_seq; + g.next_seq += 1; + g.pending.insert( + id.clone(), + Entry { + seq, + held_at: now, + identity: identity.to_string(), + fingerprint, + digest: digest.clone(), + req, + tx: Some(tx), + nonce: nonce.clone(), + view_token: view_token.clone(), + }, + ); + Admission::Held(Held { + id, + digest, + decision: rx, + superseded: None, + nonce, + view_token, + }) + } + /// Approve `id` for `approver` and wait for the handler's confirmation, with no policy /// re-check. The approval listener uses [`Table::approve_if`]. /// diff --git a/crates/ap-proxy/src/lib.rs b/crates/ap-proxy/src/lib.rs index 9c1d726..176d0ec 100644 --- a/crates/ap-proxy/src/lib.rs +++ b/crates/ap-proxy/src/lib.rs @@ -5,6 +5,7 @@ pub mod admin_http; pub mod approval; +pub mod async_poll; pub mod audit_sink; pub mod evidence; pub mod forward; diff --git a/crates/ap-proxy/src/passthrough.rs b/crates/ap-proxy/src/passthrough.rs index 5d6b93f..0726280 100644 --- a/crates/ap-proxy/src/passthrough.rs +++ b/crates/ap-proxy/src/passthrough.rs @@ -19,7 +19,7 @@ use ap_broker::clock::{Clock, SystemClock}; use ap_broker::registry::sha256_hex; use ap_core::audit::{path_only, AuditRec}; use ap_core::canon; -use ap_core::config::{Config, Identity}; +use ap_core::config::{Config, HoldMode, Identity}; use ap_core::error::Code; use ap_core::outcome::{render_passthrough, DECISION_HEADER}; use ap_core::policy::{Snapshot, Verdict}; @@ -65,6 +65,8 @@ pub struct PtApp { held_client: reqwest::Client, /// Held requests waiting for a decision. pub hold: Arc, + /// Poll tokens and final statuses of the async hold mode. Empty in blocking mode. + pub(crate) polls: Arc, /// Told about each new distinct hold entry. `None` until a notifier is configured. pub notifier: Option>, /// `[approval].public_base_url` without a trailing slash: the notification link is @@ -188,6 +190,7 @@ impl PtApp { client, held_client, hold: Arc::new(hold::Table::new(limits)), + polls: Arc::default(), notifier: None, approval_base: None, view_base: None, @@ -561,6 +564,23 @@ pub async fn handle(app: Arc, req: Request) -> Result` is answered before any authentication, because the + // token is its only credential and the answer must not depend on the headers sent. + if pt.hold_mode == HoldMode::Async { + if let Some(token) = parts.uri.path().strip_prefix("/poll/") { + if parts.method != Method::GET || token.is_empty() || token.contains('/') { + return Ok(crate::async_poll::not_found()); + } + return Ok(crate::async_poll::poll( + &app.polls, + app.clock.as_ref(), + token, + parts.uri.query(), + ) + .await); + } + } + // 3. Canonical request target, host and path. if let Err(code) = canon::check_origin_form( &parts.uri, diff --git a/crates/ap-proxy/src/passthrough/async_tests.rs b/crates/ap-proxy/src/passthrough/async_tests.rs new file mode 100644 index 0000000..d12347f --- /dev/null +++ b/crates/ap-proxy/src/passthrough/async_tests.rs @@ -0,0 +1,547 @@ +//! The Muse async poll mode end to end (`docs/design/muse-async-poll.md`), on the hold-path +//! fixture. Every secret here is a synthetic sentinel. + +use super::*; +use serde_json::Value; + +const ASYNC: &str = "hold_mode = \"async\""; + +fn async_opts(extra: &str) -> Opts { + Opts { + extra: format!("{ASYNC}\n{extra}"), + ..Opts::default() + } +} + +async fn async_ht(tag: &str, up: &Upstream) -> Ht { + Ht::with(tag, up, async_opts("")).await +} + +/// What a 202 carried. +struct Admitted { + id: String, + token: String, +} + +impl Ht { + async fn submit(&self, path: &str, body: &str) -> Admitted { + let (p, b) = self.send(self.post(path, body)).await.unwrap(); + assert_eq!(p.status, 202, "{}", String::from_utf8_lossy(&b)); + assert!(p.headers.get("x-ap-decision").is_none()); + let v: Value = serde_json::from_slice(&b).unwrap(); + assert_eq!(v["status"], "pending"); + let text = String::from_utf8_lossy(&b).into_owned(); + for secret in [SENTINEL, self.key.as_str(), body] { + assert!(!text.contains(secret), "the 202 echoed {secret}"); + } + let id = v["request_id"].as_str().unwrap().to_string(); + assert_eq!(self.held(1).await, id); + Admitted { + id, + token: v["poll_token"].as_str().unwrap().to_string(), + } + } + + async fn poll(&self, token: &str, query: &str) -> (u16, Value) { + let uri = if query.is_empty() { + format!("/poll/{token}") + } else { + format!("/poll/{token}?{query}") + }; + // No Authorization and no caller key: the token is the only credential. + let req = Request::builder() + .method("GET") + .uri(uri) + .header("host", AUTH) + .body(Body::empty()) + .unwrap(); + let (p, b) = self.send(req).await.unwrap(); + (p.status.as_u16(), serde_json::from_slice(&b).unwrap()) + } + + async fn poll_until(&self, token: &str, status: &str) -> Value { + for _ in 0..250 { + let (code, v) = self.poll(token, "").await; + assert_eq!(code, 200); + if v["status"] == status { + return v; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("poll never reached {status}"); + } + + /// Nothing the audit stream holds may name a poll token or its hash. + fn assert_token_not_audited(&self, token: &str) { + let t = self.text(); + assert!( + !t.contains(token), + "the poll token reached the audit stream" + ); + assert!( + !t.contains(&sha256_hex(token)), + "the token hash reached the audit stream" + ); + self.assert_clean(); + } +} + +#[tokio::test] +async fn approved_request_is_sent_and_the_poll_reports_discord_status_and_body() { + let mock = Mock::start().await; + let t = async_ht("async-ok", &mock.up).await; + let a = t.submit("/discord/hold/ok", r#"{"content":"hi"}"#).await; + assert_eq!(a.token.len(), 32); + // Pending, and nothing has gone upstream. + let (code, v) = t.poll(&a.token, "").await; + assert_eq!((code, v["status"].as_str()), (200, Some("pending"))); + assert_eq!(v["request_id"], a.id); + assert_eq!(mock.hits(), 0); + assert_eq!( + t.app.hold.approve(&a.id, "alice").await, + ApproveResult::Success + ); + let v = t.poll_until(&a.token, "approved_and_sent").await; + assert_eq!(v["discord_status"], 200); + assert_eq!(v["body"], "ok"); + assert_eq!(v["truncated"], false); + assert_eq!(v["request_id"], a.id); + assert_eq!(mock.recorded().len(), 1); + assert_eq!( + t.transitions(), + ["held", "approved", "forward_started", "completed"] + ); + t.assert_token_not_audited(&a.token); +} + +#[tokio::test] +async fn a_long_wait_returns_as_soon_as_the_request_is_sent() { + let mock = Mock::start().await; + let t = async_ht("async-wait", &mock.up).await; + let a = t.submit("/discord/hold/ok", "{}").await; + let id = a.id.clone(); + let table = Arc::clone(&t.app.hold); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(300)).await; + table.approve(&id, "alice").await; + }); + let t0 = Instant::now(); + let (code, v) = t.poll(&a.token, "wait=20").await; + assert_eq!( + (code, v["status"].as_str()), + (200, Some("approved_and_sent")) + ); + assert!(t0.elapsed() < Duration::from_secs(10)); +} + +#[tokio::test] +async fn a_large_discord_body_is_cut_at_64_kib() { + let mock = Mock::start().await; + let t = async_ht("async-big", &mock.up).await; + let a = t.submit("/discord/hold/big", "{}").await; + t.app.hold.approve(&a.id, "alice").await; + let v = t.poll_until(&a.token, "approved_and_sent").await; + assert_eq!(v["truncated"], true); + assert_eq!(v["body"].as_str().unwrap().len(), 64 * 1024); +} + +#[tokio::test] +async fn a_non_200_discord_status_is_still_approved_and_sent() { + let mock = Mock::start().await; + let t = async_ht("async-418", &mock.up).await; + let a = t.submit("/discord/hold/teapot", "{}").await; + t.app.hold.approve(&a.id, "alice").await; + let v = t.poll_until(&a.token, "approved_and_sent").await; + assert_eq!(v["discord_status"], 418); + assert_eq!(v["body"], "short and stout"); +} + +#[tokio::test] +async fn denied_request_polls_as_denied_and_sends_nothing() { + let mock = Mock::start().await; + let t = async_ht("async-deny", &mock.up).await; + let a = t.submit("/discord/hold/ok", "{}").await; + t.app.hold.deny(&a.id, "alice"); + let v = t.poll_until(&a.token, "denied").await; + assert_eq!(v.as_object().unwrap().len(), 2); + assert_eq!(mock.hits(), 0); + assert_eq!(t.transitions(), ["held", "denied"]); + t.assert_token_not_audited(&a.token); +} + +#[tokio::test] +async fn unapproved_entry_expires_after_async_hold_secs() { + let mock = Mock::start().await; + let t = Ht::with("async-expire", &mock.up, async_opts("async_hold_secs = 5")).await; + let a = t.submit("/discord/hold/ok", "{}").await; + let (_, v) = t.poll(&a.token, "").await; + assert_eq!(v["status"], "pending"); + let (code, v) = t.poll(&a.token, "wait=10").await; + assert_eq!((code, v["status"].as_str()), (200, Some("expired"))); + assert_eq!(t.transitions(), ["held", "expired"]); + assert_eq!(mock.hits(), 0); + // A late approve finds nothing to approve. + assert_eq!( + t.app.hold.approve(&a.id, "alice").await, + ApproveResult::Expired + ); +} + +#[tokio::test] +async fn policy_reload_drops_a_pending_entry() { + let mock = Mock::start().await; + let t = async_ht("async-drop", &mock.up).await; + let a = t.submit("/discord/hold/ok", "{}").await; + assert_eq!(t.app.hold.drop_all(), 1); + let v = t.poll_until(&a.token, "dropped").await; + assert_eq!(v.as_object().unwrap().len(), 2); + assert_eq!(t.count("dropped_on_reload"), 1); +} + +#[tokio::test] +async fn start_claim_failure_before_any_byte_is_dropped_with_the_existing_audit_code() { + let mock = Mock::start().await; + let o = Opts { + tail: pilot_tail("2026-12-20"), + ..async_opts("") + }; + let mut t = Ht::with("async-claim", &mock.up, o).await; + let clock = ManualClock::new(PILOT_LAST_DAY); + PtApp::set_clock(&mut t.app, Arc::new(clock.clone())); + let (p, b) = t + .send(keyless("POST", PILOT_WRITE, Some(PILOT_AUTH))) + .await + .unwrap(); + assert_eq!(p.status, 202); + let token = serde_json::from_slice::(&b).unwrap()["poll_token"] + .as_str() + .unwrap() + .to_string(); + let id = t.held(1).await; + // The pilot window closes between admission and the approve: the claim refuses. + clock.set(PILOT_REFUSED); + assert_eq!( + t.app.hold.approve(&id, "alice").await, + ApproveResult::PolicyChanged + ); + let (code, v) = t.poll(&token, "").await; + assert_eq!((code, v["status"].as_str()), (200, Some("dropped"))); + assert_eq!(t.count("dropped_on_reload"), 1); + assert_eq!(t.count("forward_started"), 0); + assert!(mock.recorded().is_empty()); + t.assert_token_not_audited(&token); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn approved_just_before_shutdown_is_refused_at_the_claim_and_polls_as_dropped() { + let mock = Mock::start().await; + let t = async_ht("async-shutdown", &mock.up).await; + let a = t.submit("/discord/hold/ok", "{}").await; + let gate = Gate::new(); + t.app.pause.set_after_approve(Arc::clone(&gate)); + let table = Arc::clone(&t.app.hold); + let id = a.id.clone(); + let approve = tokio::spawn(async move { table.approve(&id, "alice").await }); + tokio::time::timeout(Duration::from_secs(5), gate.arrived()) + .await + .unwrap(); + t.app.hold.drain_pending(); + gate.release(); + assert_eq!(approve.await.unwrap(), ApproveResult::ApprovedButAbandoned); + t.poll_until(&a.token, "dropped").await; + assert_eq!(t.count("forward_started"), 0); + assert!(mock.recorded().is_empty()); +} + +#[tokio::test] +async fn connect_failure_is_send_failed_and_writes_no_forward_started() { + let mock = Mock::start().await; + // Nothing listens on this port. + let free = { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + l.local_addr().unwrap().port() + }; + let o = Opts { + port: Some(free), + ..async_opts("") + }; + let t = Ht::with("async-connect", &mock.up, o).await; + let a = t.submit("/discord/hold/ok", "{}").await; + t.app.hold.approve(&a.id, "alice").await; + let v = t.poll_until(&a.token, "send_failed").await; + assert_eq!(v.as_object().unwrap().len(), 2); + assert_eq!(t.count("connect_failed"), 1); + assert_eq!(t.count("forward_started"), 0); +} + +#[tokio::test] +async fn a_failed_forward_started_write_is_send_failed() { + let raw = Raw::start().await; + let sw = Switch::default(); + let o = Opts { + sink: Some(sw.clone()), + ..async_opts("") + }; + let t = Ht::with("async-fs-audit", &raw.up, o).await; + let a = t.submit("/discord/hold/ok", "{}").await; + *sw.fail_on.lock().unwrap() = Some("\"forward_started\"".into()); + t.app.hold.approve(&a.id, "alice").await; + t.poll_until(&a.token, "send_failed").await; + assert_eq!(t.count("audit_unavailable"), 1); + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(raw.bytes.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn reset_after_the_request_was_sent_is_send_unknown_never_dropped() { + let mock = Mock::start().await; + let t = async_ht("async-reset", &mock.up).await; + let a = t.submit("/discord/hold/reset-after-read", "{}").await; + t.app.hold.approve(&a.id, "alice").await; + let v = t.poll_until(&a.token, "send_unknown").await; + assert_eq!(v["error_class"], "reset"); + assert_eq!(mock.recorded().len(), 1); + assert_eq!(t.count("forward_started"), 1); + assert_eq!(t.count("completed"), 0); + t.assert_token_not_audited(&a.token); +} + +#[tokio::test] +async fn no_answer_within_the_request_deadline_is_send_unknown_timeout() { + let mock = Mock::start().await; + let t = Ht::with( + "async-timeout", + &mock.up, + async_opts("request_deadline_secs = 1"), + ) + .await; + let a = t.submit("/discord/hold/stall", "{}").await; + t.app.hold.approve(&a.id, "alice").await; + let (code, v) = t.poll(&a.token, "wait=10").await; + assert_eq!(code, 200); + assert_eq!(v["status"], "send_unknown"); + assert_eq!(v["error_class"], "timeout"); +} + +#[tokio::test] +async fn a_stalled_response_body_is_send_unknown_timeout() { + let mock = Mock::start().await; + let t = Ht::with( + "async-stall-body", + &mock.up, + async_opts("upstream_idle_secs = 1"), + ) + .await; + let a = t.submit("/discord/hold/stall-body", "{}").await; + t.app.hold.approve(&a.id, "alice").await; + let (_, v) = t.poll(&a.token, "wait=10").await; + assert_eq!(v["status"], "send_unknown"); + assert_eq!(v["error_class"], "timeout"); +} + +#[tokio::test] +async fn unknown_token_and_ended_window_give_the_same_404_and_headers_do_not_matter() { + let mock = Mock::start().await; + let mut t = async_ht("async-404", &mock.up).await; + let clock = ManualClock::new(5_000); + PtApp::set_clock(&mut t.app, Arc::new(clock.clone())); + let a = t.submit("/discord/hold/ok", "{}").await; + t.app.hold.deny(&a.id, "alice"); + t.poll_until(&a.token, "denied").await; + clock.advance(59); + assert_eq!(t.poll(&a.token, "").await.0, 200); + clock.advance(1); + let ended = t.poll(&a.token, "").await; + let unknown = t.poll("00000000000000000000000000000000", "").await; + assert_eq!(ended.0, 404); + assert_eq!(ended, unknown); + // Whatever headers a caller sends, the unknown token gets the same answer. + let req = Request::builder() + .method("GET") + .uri("/poll/00000000000000000000000000000000") + .header("host", AUTH) + .header("x-ap-caller-key", t.key.as_str()) + .header("authorization", format!("Bot {SENTINEL}")) + .body(Body::empty()) + .unwrap(); + let (p, b) = t.send(req).await.unwrap(); + assert_eq!(p.status, 404); + assert_eq!(serde_json::from_slice::(&b).unwrap(), unknown.1); + // A method other than GET is the same 404. + let req = Request::builder() + .method("POST") + .uri(format!("/poll/{}", a.token)) + .header("host", AUTH) + .body(Body::empty()) + .unwrap(); + assert_eq!(t.send(req).await.unwrap().0.status, 404); +} + +#[tokio::test] +async fn wait_parameter_is_validated_through_the_listener_path() { + let mock = Mock::start().await; + let t = async_ht("async-wait-param", &mock.up).await; + let a = t.submit("/discord/hold/ok", "{}").await; + for q in ["wait=abc", "wait=-1", "wait=1.5"] { + let known = t.poll(&a.token, q).await; + let unknown = t.poll("ffffffffffffffffffffffffffffffff", q).await; + assert_eq!(known.0, 400, "{q}"); + assert_eq!(known, unknown, "{q} must not reveal the token"); + } + // Missing and over-cap are accepted. A missing wait does not wait. + let t0 = Instant::now(); + assert_eq!(t.poll(&a.token, "").await.1["status"], "pending"); + assert!(t0.elapsed() < Duration::from_secs(2)); +} + +#[tokio::test] +async fn restart_loses_pending_entries_and_their_polls_are_404() { + let mock = Mock::start().await; + let t = async_ht("async-restart-a", &mock.up).await; + let a = t.submit("/discord/hold/ok", "{}").await; + assert_eq!(t.poll(&a.token, "").await.0, 200); + // A new process: a new app over the same policy has an empty table and store. + let t2 = async_ht("async-restart-b", &mock.up).await; + assert_eq!(t2.poll(&a.token, "").await.0, 404); + assert_eq!(t2.app.hold.pending_len(), 0); +} + +#[tokio::test] +async fn the_poll_token_cannot_approve_deny_or_change_state() { + let mock = Mock::start().await; + let t = async_ht("async-readonly", &mock.up).await; + let a = t.submit("/discord/hold/ok", "{}").await; + // The token and the request id in every shape a caller might try. + for uri in [ + format!("/poll/{}/approve", a.token), + format!("/poll/{}?approve=1&decision=approved", a.token), + format!("/approve/{}", a.token), + format!("/pending/{}/approve", a.token), + ] { + for method in ["GET", "POST", "PUT", "DELETE"] { + let req = Request::builder() + .method(method) + .uri(&uri) + .header("host", AUTH) + .body(Body::empty()) + .unwrap(); + let _ = t.send(req).await; + } + } + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(t.app.hold.state(&a.id), Some(State::Pending)); + assert_eq!(mock.hits(), 0); + assert_eq!(t.transitions(), ["held"]); +} + +#[tokio::test] +async fn a_failed_held_write_refuses_before_any_entry_or_notification() { + let mock = Mock::start().await; + let sw = Switch::default(); + let n = MockNotifier::new(false); + let o = Opts { + sink: Some(sw.clone()), + notifier: Some(Arc::clone(&n)), + ..async_opts("") + }; + let t = Ht::with("async-held-fail", &mock.up, o).await; + *sw.fail_on.lock().unwrap() = Some("\"held\"".into()); + let (p, b) = t.send(t.post("/discord/hold/ok", "{}")).await.unwrap(); + assert_eq!(p.status, 503); + assert_eq!(code(&b), "audit_unavailable"); + assert_eq!(t.app.hold.pending_len(), 0); + assert_eq!(t.app.polls.pending_len(), 0); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!( + n.calls().is_empty(), + "a notification went out without an entry" + ); + assert_eq!(mock.hits(), 0); + // No token was issued. + assert!(!String::from_utf8_lossy(&b).contains("poll_token")); +} + +#[tokio::test] +async fn admission_refusals_keep_their_codes_after_the_held_record_and_issue_no_token() { + let mock = Mock::start().await; + let mut o = async_opts(""); + o.limits.max_per_identity = 1; + let t = Ht::with("async-caps", &mock.up, o).await; + let a = t.submit("/discord/hold/ok", "{}").await; + // Async mode does not dedupe: an identical second request is refused by the cap, not merged. + let (p, b) = t.send(t.post("/discord/hold/ok", "{}")).await.unwrap(); + assert_eq!( + (p.status.as_u16(), code(&b).as_str()), + (503, "identity_cap") + ); + assert!(!String::from_utf8_lossy(&b).contains("poll_token")); + assert_eq!( + t.count("held"), + 2, + "the held record comes before the checks" + ); + assert_eq!(t.app.hold.state(&a.id), Some(State::Pending)); + assert_eq!(t.app.hold.pending_len(), 1); +} + +#[tokio::test] +async fn identical_requests_are_independent_entries_with_their_own_tokens() { + let mock = Mock::start().await; + let n = MockNotifier::new(false); + let o = Opts { + notifier: Some(Arc::clone(&n)), + ..async_opts("") + }; + let t = Ht::with("async-indep", &mock.up, o).await; + let a = t.submit("/discord/hold/ok", "{}").await; + let (p, b) = t.send(t.post("/discord/hold/ok", "{}")).await.unwrap(); + assert_eq!(p.status, 202); + let v: Value = serde_json::from_slice(&b).unwrap(); + assert_ne!(v["poll_token"], a.token); + assert_ne!(v["request_id"], a.id); + assert_eq!(t.app.hold.pending_len(), 2); + assert_eq!(t.count("superseded"), 0); + calls_reach(&n, 2).await; + assert_eq!(t.poll(&a.token, "").await.1["status"], "pending"); +} + +#[tokio::test] +async fn the_blocking_mode_is_the_default_and_has_no_poll_route() { + let mock = Mock::start().await; + let t = Ht::new("async-default-off", &mock.up).await; + // Same request as before: held on the caller's connection, answered when decided. + 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::Success + ); + let (p, b) = h.await.unwrap().unwrap(); + assert_eq!((p.status.as_u16(), &b[..]), (200, &b"ok"[..])); + // `/poll/...` is just an unauthenticated request in blocking mode. + let req = Request::builder() + .method("GET") + .uri("/poll/abcdef") + .header("host", AUTH) + .body(Body::empty()) + .unwrap(); + let (p, _) = t.send(req).await.unwrap(); + assert_eq!(p.status, 401); +} + +#[tokio::test] +async fn a_poll_that_is_rate_limited_changes_nothing() { + let mock = Mock::start().await; + let t = async_ht("async-rate", &mock.up).await; + let a = t.submit("/discord/hold/ok", "{}").await; + let mut limited = false; + for _ in 0..40 { + if t.poll(&a.token, "").await.0 == 429 { + limited = true; + break; + } + } + // The loop may straddle a clock second; at 40 polls at least one second holds more than 10. + assert!(limited); + assert_eq!(t.app.hold.state(&a.id), Some(State::Pending)); +} diff --git a/crates/ap-proxy/src/passthrough/hold_path.rs b/crates/ap-proxy/src/passthrough/hold_path.rs index 34d5c82..21d4523 100644 --- a/crates/ap-proxy/src/passthrough/hold_path.rs +++ b/crates/ap-proxy/src/passthrough/hold_path.rs @@ -23,7 +23,7 @@ use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use ap_core::audit::HoldRec; -use ap_core::config::{Passthrough, Route}; +use ap_core::config::{HoldMode, Passthrough, Route}; use bytes::Bytes; use futures_util::Stream; use http::{header, HeaderMap, HeaderValue}; @@ -33,6 +33,8 @@ use super::{ audited, refusal_response, refuse, refuse_unread, ConnAbort, Drain, End, PtApp, Trail, }; use super::{Code, Duration, Instant, Response, StreamAudit}; + +mod async_mode; use crate::forward::{self, BufferError}; use crate::hold::{Admission, CallbackAction, Confirm, ConfirmTx, Decision, HeldRequest, Upstream}; use crate::notify::poll::callback_data; @@ -512,6 +514,30 @@ pub(super) async fn run(r: Request<'_>) -> Result, ConnAbort> { started: trail.started, }; + if pt.hold_mode == HoldMode::Async { + return Ok(async_mode::run(async_mode::Request { + app, + trail, + ctx, + req, + headers, + bytes, + method: parts.method, + url: forward::upstream_url( + route, + &match &query { + Some(q) => format!("{rel}?{q}"), + None => rel.to_string(), + }, + ), + hold: Duration::from_secs(pt.async_hold_secs), + deadline: Duration::from_secs(pt.request_deadline_secs), + idle: Duration::from_secs(pt.upstream_idle_secs), + identity, + }) + .await); + } + // 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| { let mut rec = ctx.rec(id, digest, "held", None, None, None); diff --git a/crates/ap-proxy/src/passthrough/hold_path/async_mode.rs b/crates/ap-proxy/src/passthrough/hold_path/async_mode.rs new file mode 100644 index 0000000..c38aefc --- /dev/null +++ b/crates/ap-proxy/src/passthrough/hold_path/async_mode.rs @@ -0,0 +1,355 @@ +//! The async hold mode (`docs/design/muse-async-poll.md`): the same hold, approval and forward as +//! the blocking path, but the caller gets `202` with a poll token at once and a detached task +//! carries the entry to its end. The task's outcome is stored for `GET /poll/`. +//! +//! What is reused unchanged: the hold table, the start claim in [`HeldBody`], the audit records +//! and the Telegram notification. What is new: the admission order (the `held` record first), the +//! absence of dedupe and supersede, and the mapping from each ending to a poll status. + +use super::*; +use crate::async_poll::{self, Final, FinishGuard, BODY_MAX}; +use futures_util::StreamExt; + +pub(super) struct Request<'a> { + pub app: Arc, + pub trail: Trail, + pub ctx: Ctx, + pub req: Arc, + pub headers: HeaderMap, + pub bytes: Bytes, + pub method: http::Method, + pub url: String, + pub hold: Duration, + pub deadline: Duration, + pub idle: Duration, + pub identity: &'a str, +} + +struct Drive { + app: Arc, + trail: Trail, + req: Arc, + guard: Guard, + fin: FinishGuard, + headers: HeaderMap, + bytes: Bytes, + method: http::Method, + url: String, + hold: Duration, + deadline: Duration, + idle: Duration, +} + +/// Admit the request and answer `202`, or refuse as the blocking path does. +pub(super) async fn run(r: Request<'_>) -> Response { + let Request { + app, + trail, + ctx, + req, + headers, + bytes, + method, + url, + hold, + deadline, + idle, + identity, + } = r; + + // The `held` record is written first, under the table lock. A failed write refuses before any + // entry exists; a refusal by the checks that follow leaves the record and gets its own. + let admission = app + .hold + .admit_async(identity, Arc::clone(&req), |id, digest| { + let mut rec = ctx.rec(id, digest, "held", None, None, None); + rec.upstream = Some(req.upstream.authority()); + rec.policy_generation = Some(req.generation); + app.audit.try_write_hold(&rec) + }); + let held = match admission { + Admission::Refused(code) => return refuse(&app, &trail, code), + Admission::Held(h) => h, + }; + let token = app.polls.insert(&held.id, app.clock.now()); + announce(&app, &ctx, &held); + let fin = FinishGuard::new(Arc::clone(&app.polls), Arc::clone(&app.clock), &held.id); + let guard = Guard { + app: Arc::clone(&app), + ctx, + id: held.id, + digest: held.digest, + phase: Phase::Pending, + rx: Some(held.decision), + started: Arc::new(Started::new()), + }; + trail.write_evidence(&app.audit, 202); + let response = async_poll::accepted(&guard.id, &token); + tokio::spawn(drive(Drive { + app, + trail, + req, + guard, + fin, + headers, + bytes, + method, + url, + hold, + deadline, + idle, + })); + response +} + +/// Wait for a decision or the timer, then forward if approved, and store the ending. +async fn drive(d: Drive) { + let Drive { + app, + trail, + req, + mut guard, + fin, + headers, + bytes, + method, + url, + hold, + deadline, + idle, + } = d; + enum Event { + Decision(Result), + Timer, + } + let event = { + let Some(rx) = guard.rx.as_mut() else { + return; + }; + tokio::select! { + d = rx => Event::Decision(d), + () = tokio::time::sleep(hold) => Event::Timer, + } + }; + // Approve versus expiry is decided inside the table, on its one mutex: the first wins. + 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)); + fin.finish(Final::Expired); + return; + } + match guard.rx.as_mut() { + Some(rx) => rx.await, + None => return, + } + } + }; + guard.rx = None; + let shutdown = |guard: &mut Guard| { + guard.phase = Phase::Done; + let code = Code::Shutdown; + let (status, _, _) = render_passthrough(code); + app.audit + .write_rec(&trail.rec("deny", Some(code.code_str()), status)); + }; + let decision = match decision { + Ok(d) => d, + Err(_) => { + shutdown(&mut guard); + fin.finish(Final::Dropped); + return; + } + }; + guard.record(&decision); + match decision { + Decision::Approved { confirm, .. } => { + guard.phase = Phase::Approved; + let out = forward( + &app, + req, + &mut guard, + confirm, + headers, + bytes, + method, + url, + (deadline, idle), + ) + .await; + fin.finish(out); + } + Decision::Denied { .. } => { + guard.phase = Phase::Done; + fin.finish(Final::Denied); + } + // No dedupe in async mode, so a supersede cannot happen; treat it as dropped anyway. + Decision::Superseded { .. } | Decision::Dropped => { + guard.phase = Phase::Done; + fin.finish(Final::Dropped); + } + Decision::Shutdown => { + shutdown(&mut guard); + fin.finish(Final::Dropped); + } + } +} + +/// The approved forward. Same milestones and audit records as `forward_approved`; the ending is a +/// poll status instead of a response. Anything past the first request byte that is not a fully +/// read Discord response is `send_unknown`, never `dropped`. +#[allow(clippy::too_many_arguments)] +async fn forward( + app: &Arc, + req: Arc, + guard: &mut Guard, + confirm: ConfirmTx, + headers: HeaderMap, + bytes: Bytes, + method: http::Method, + url: String, + (deadline, idle): (Duration, Duration), +) -> Final { + 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 shutdown = Arc::new(AtomicBool::new(false)); + let policy_changed = Arc::new(AtomicBool::new(false)); + let stream = HeldBody { + app: Arc::clone(app), + req, + 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), + shutdown: Arc::clone(&shutdown), + policy_changed: Arc::clone(&policy_changed), + 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 sent = tokio::select! { + r = &mut send => Sent::Done(r), + () = started.deadline(deadline) => Sent::Timeout, + }; + let upstream = match sent { + Sent::Done(Ok(r)) => r, + Sent::Done(Err(e)) => { + guard.phase = Phase::Done; + if audit_failed.load(Ordering::SeqCst) { + guard.write( + "audit_unavailable", + None, + Some("audit_unavailable"), + Some(503), + ); + return Final::SendFailed; + } + if policy_changed.load(Ordering::SeqCst) { + guard.write( + "dropped_on_reload", + None, + Some("dropped_on_reload"), + Some(503), + ); + return Final::Dropped; + } + if shutdown.load(Ordering::SeqCst) { + guard.write("abandoned_after_approve", None, Some("shutdown"), Some(503)); + return Final::Dropped; + } + if started.get().is_none() { + if let Some(c) = take_confirm(&confirm) { + c.send(Confirm::ConnectFailed); + } + guard.write("connect_failed", None, Some("connect_failed"), Some(503)); + return Final::SendFailed; + } + return Final::SendUnknown(if e.is_timeout() { + "timeout" + } else { + error_class(&e) + }); + } + Sent::Timeout => { + guard.phase = Phase::Done; + return Final::SendUnknown("timeout"); + } + }; + + // The request is on its way; the guard has nothing left to record. + guard.phase = Phase::Done; + let status = upstream.status().as_u16(); + let limit = started.get().unwrap_or_else(Instant::now) + deadline; + let mut stream = upstream.bytes_stream(); + let mut body: Vec = Vec::new(); + let mut truncated = false; + loop { + let wait = limit.saturating_duration_since(Instant::now()).min(idle); + match tokio::time::timeout(wait, stream.next()).await { + Ok(Some(Ok(chunk))) => { + body.extend_from_slice(&chunk); + if body.len() > BODY_MAX { + body.truncate(BODY_MAX); + truncated = true; + break; + } + } + Ok(Some(Err(_))) => return Final::SendUnknown("reset"), + Ok(None) => break, + Err(_) => return Final::SendUnknown("timeout"), + } + } + guard.write("completed", None, None, Some(status)); + Final::Approved { + discord_status: status, + body, + truncated, + } +} + +/// `write_failed` when a write on the connection failed, otherwise `reset`. +fn error_class(e: &(dyn std::error::Error + 'static)) -> &'static str { + let mut cur = Some(e); + while let Some(err) = cur { + if let Some(io) = err.downcast_ref::() { + match io.kind() { + io::ErrorKind::TimedOut => return "timeout", + io::ErrorKind::BrokenPipe | io::ErrorKind::WriteZero => return "write_failed", + _ => {} + } + } + cur = err.source(); + } + "reset" +} + +#[cfg(test)] +mod class_tests { + use super::*; + + #[test] + fn error_class_reads_the_io_kind_in_the_chain() { + let pipe = io::Error::new(io::ErrorKind::BrokenPipe, "x"); + assert_eq!(error_class(&pipe), "write_failed"); + let timed = io::Error::new(io::ErrorKind::TimedOut, "x"); + assert_eq!(error_class(&timed), "timeout"); + let other = io::Error::other("x"); + assert_eq!(error_class(&other), "reset"); + } +} diff --git a/crates/ap-proxy/src/passthrough/hold_tests.rs b/crates/ap-proxy/src/passthrough/hold_tests.rs index 71b35bb..6da7781 100644 --- a/crates/ap-proxy/src/passthrough/hold_tests.rs +++ b/crates/ap-proxy/src/passthrough/hold_tests.rs @@ -43,6 +43,10 @@ const PATH_TOKEN: &str = "SENTINEL-PATH-TOKEN-0002"; #[path = "../leak_tests.rs"] mod leak_tests; +// The Muse async poll mode. +#[path = "async_tests.rs"] +mod async_tests; + // ---------------------------------------------------------------- mock upstreams #[derive(Clone, Debug)] @@ -148,6 +152,11 @@ async fn serve( .body(full("short and stout")) .expect("teapot")), "reset-after-read" => Err(io::Error::other("reset")), + "big" => Ok(hyper::Response::new( + Full::new(Bytes::from(vec![b'x'; 70_000])) + .map_err(|never: Infallible| match never {}) + .boxed_unsync(), + )), "stall" => std::future::pending().await, "stall-body" => { let s = futures_util::stream::once(async { From 120f4391e07817d77528df932e7442ad85e995fe Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:11:24 -0500 Subject: [PATCH 2/2] fix(muse): scope async to its route, track forwards at shutdown, audit refusals, drop poll rate limit - hold_mode and async_hold_secs move from [passthrough] to the route; load requires a passthrough route with a hold grant. Other held routes keep blocking, dedupe and supersede. - Detached async forwards are tracked (AsyncTasks) and included in the shutdown wait (request_deadline_secs + 2). A cut after forward_started ends as send_unknown (completed, code upstream_reset); before it, dropped. - Admission refused after the held record (cooldown, identity_cap, table_full) writes a terminal hold record for that request_id with the refusal code and status 503. - Remove the per-token poll rate limit and the 429 rate_limited response. Checks on macmini (arm64, umask 022): see PR comment / follow-up commit trailer. --- crates/ap-core/src/config.rs | 78 ++++++++---- crates/ap-proxy/src/async_poll.rs | 120 ++++++++++++------ crates/ap-proxy/src/async_poll/tests.rs | 23 ++-- crates/ap-proxy/src/hold/mod.rs | 37 ++++-- crates/ap-proxy/src/lib.rs | 11 +- crates/ap-proxy/src/passthrough.rs | 12 +- .../ap-proxy/src/passthrough/async_tests.rs | 109 ++++++++++++++-- crates/ap-proxy/src/passthrough/hold_path.rs | 4 +- .../src/passthrough/hold_path/async_mode.rs | 56 +++++++- crates/ap-proxy/src/passthrough/hold_tests.rs | 5 + 10 files changed, 347 insertions(+), 108 deletions(-) diff --git a/crates/ap-core/src/config.rs b/crates/ap-core/src/config.rs index dd4ef16..698076f 100644 --- a/crates/ap-core/src/config.rs +++ b/crates/ap-core/src/config.rs @@ -138,15 +138,6 @@ pub struct Passthrough { /// Seconds an identity is refused after a human deny, 0..=3600 (0 disables). #[serde(default = "default_cooldown_secs")] pub cooldown_secs: u64, - /// `blocking` (default) keeps the caller's connection open while a request is held. `async` - /// answers 202 with a poll token and the caller polls `GET /poll/` (design - /// `muse-async-poll.md`). - #[serde(default)] - pub hold_mode: HoldMode, - /// In `async` mode, how long an unapproved entry stays pending before it ends as `expired`, - /// 5..=600. Ignored in `blocking` mode, where `hold_secs` applies. - #[serde(default = "default_hold_secs")] - pub async_hold_secs: u64, } /// How a held request is answered to its caller. @@ -423,6 +414,15 @@ pub struct Route { /// forwarded. Default empty. #[serde(default)] pub keep_auth_headers: Vec, + /// Passthrough routes with a hold grant only. `blocking` (default) keeps the caller's + /// connection open while a request is held. `async` answers 202 with a poll token and the + /// caller polls `GET /poll/` (design `muse-async-poll.md`). Applies to this route only. + #[serde(default)] + pub hold_mode: HoldMode, + /// With `hold_mode = "async"`: seconds an unapproved entry stays pending before it ends as + /// `expired`, 5..=600. Ignored in `blocking` mode, where `[passthrough].hold_secs` applies. + #[serde(default = "default_hold_secs")] + pub async_hold_secs: u64, } #[derive(Debug, Deserialize, Clone)] @@ -661,7 +661,6 @@ fn validate_passthrough(p: &Passthrough) -> Result<(), ConfigError> { } for (field, v, min, max) in [ ("hold_secs", p.hold_secs, 5, 600), - ("async_hold_secs", p.async_hold_secs, 5, 600), ( "held_body_max_bytes", p.held_body_max_bytes, @@ -932,6 +931,27 @@ impl Config { route_hosts.insert(r.name.as_str(), r.host.as_str()); } + for r in &self.routes { + if !(5..=600).contains(&r.async_hold_secs) { + return Err(invalid(format!( + "route {:?}: async_hold_secs must be in 5..=600", + r.name + ))); + } + if r.hold_mode == HoldMode::Async + && !(r.mode == RouteMode::Passthrough + && self + .grants + .iter() + .any(|g| g.route == r.name && g.decision == Decision::Hold)) + { + return Err(invalid(format!( + "route {:?}: hold_mode \"async\" needs a passthrough route with a hold grant", + r.name + ))); + } + } + let passthrough_routes: HashSet<&str> = self .routes .iter() @@ -2170,8 +2190,6 @@ paths = ["/api/v10/channels/", "/api/v10/users/@me"] for (k, v) in [ ("hold_secs", "4"), ("hold_secs", "601"), - ("async_hold_secs", "4"), - ("async_hold_secs", "601"), ("held_body_max_bytes", "0"), ("held_body_max_bytes", "8388609"), ("max_held_total", "0"), @@ -2194,22 +2212,34 @@ paths = ["/api/v10/channels/", "/api/v10/users/@me"] } #[test] - fn hold_mode_defaults_to_blocking_and_accepts_async() { - let p = load(&hold_text()).unwrap().passthrough.unwrap(); - assert_eq!(p.hold_mode, HoldMode::Blocking); - assert_eq!(p.async_hold_secs, 120); - let text = hold_text().replace( - "public_authority = \"gate.example.test\"", - "public_authority = \"gate.example.test\"\nhold_mode = \"async\"\nasync_hold_secs = 30", + fn hold_mode_is_per_route_and_needs_a_hold_grant() { + let route = "mode = \"passthrough\"\n"; + let c = load(&hold_text()).unwrap(); + assert_eq!(c.routes[0].hold_mode, HoldMode::Blocking); + assert_eq!(c.routes[0].async_hold_secs, 120); + let on = hold_text().replacen( + route, + &format!("{route}hold_mode = \"async\"\nasync_hold_secs = 30\n"), + 1, ); - let p = load(&text).unwrap().passthrough.unwrap(); - assert_eq!(p.hold_mode, HoldMode::Async); - assert_eq!(p.async_hold_secs, 30); - let bad = hold_text().replace( + let c = load(&on).unwrap(); + assert_eq!(c.routes[0].hold_mode, HoldMode::Async); + assert_eq!(c.routes[0].async_hold_secs, 30); + // The old global spelling is gone. + let global = hold_text().replace( "public_authority = \"gate.example.test\"", - "public_authority = \"gate.example.test\"\nhold_mode = \"sync\"", + "public_authority = \"gate.example.test\"\nhold_mode = \"async\"", ); + assert!(load(&global).is_err()); + let bad = hold_text().replacen(route, &format!("{route}hold_mode = \"sync\"\n"), 1); assert!(load(&bad).is_err()); + for secs in ["4", "601"] { + let t = on.replace("async_hold_secs = 30", &format!("async_hold_secs = {secs}")); + expect_invalid(&t, "async_hold_secs"); + } + // No hold grant on the route: refused. + let allow = on.replace("decision = \"hold\"", "decision = \"allow\""); + expect_invalid(&allow, "hold_mode"); } fn approval_block() -> String { diff --git a/crates/ap-proxy/src/async_poll.rs b/crates/ap-proxy/src/async_poll.rs index 132c0d7..413b786 100644 --- a/crates/ap-proxy/src/async_poll.rs +++ b/crates/ap-proxy/src/async_poll.rs @@ -7,6 +7,7 @@ //! store does not know, the answer is one uniform 404. Nothing here is persistent, so a restart //! forgets every entry. +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; @@ -14,7 +15,7 @@ use ap_broker::registry::sha256_hex; use axum::body::Body; use http::{header, HeaderValue, Response, StatusCode}; use serde_json::{json, Value}; -use tokio::sync::Notify; +use tokio::sync::{watch, Notify}; use tokio::time::Instant; use crate::hold::digest::{ct_eq, random_hex}; @@ -25,8 +26,6 @@ pub const FINAL_WINDOW_SECS: u64 = 60; pub const MAX_WAIT_SECS: u64 = 25; /// Largest Discord response body kept for a poll. pub const BODY_MAX: usize = 64 * 1024; -/// Polls one token may make in one clock second before it is answered 429. -const POLLS_PER_SEC: u32 = 10; /// How a held request ended, as the poll reports it. #[derive(Debug, Clone, PartialEq, Eq)] @@ -57,15 +56,11 @@ struct Slot { request_id: String, state: State, notify: Arc, - /// Rate-limit window: the clock second and the polls seen in it. - second: u64, - polls: u32, } /// What a read found. enum Read { NotFound, - Limited, Pending { id: String, notify: Arc }, Final { id: String, out: Final }, } @@ -94,8 +89,6 @@ impl PollStore { request_id: request_id.to_string(), state: State::Pending, notify: Arc::new(Notify::new()), - second: now, - polls: 0, }); token } @@ -120,7 +113,7 @@ impl PollStore { .count() } - fn read(&self, token: &str, now: u64, count: bool) -> Read { + fn read(&self, token: &str, now: u64) -> Read { let key = sha256_hex(token); let mut g = self.lock(); g.retain(|s| !expired(s, now)); @@ -134,17 +127,7 @@ impl PollStore { let Some(i) = hit else { return Read::NotFound; }; - let s = &mut g[i]; - if count { - if s.second != now { - s.second = now; - s.polls = 0; - } - if s.polls >= POLLS_PER_SEC { - return Read::Limited; - } - s.polls += 1; - } + let s = &g[i]; match &s.state { State::Pending => Read::Pending { id: s.request_id.clone(), @@ -162,11 +145,14 @@ fn expired(s: &Slot, now: u64) -> bool { matches!(&s.state, State::Final { at, .. } if now >= at.saturating_add(FINAL_WINDOW_SECS)) } -/// Ends the entry as `dropped` if the task that should finish it goes away without doing so. +/// Ends the entry if the task that should finish it goes away without doing so. `on_cut` decides +/// how: `dropped` before the first request byte, `send_unknown` after it. pub struct FinishGuard { store: Arc, clock: Arc, request_id: String, + done: AtomicBool, + on_cut: Box Final + Send + Sync>, } impl FinishGuard { @@ -174,23 +160,94 @@ impl FinishGuard { store: Arc, clock: Arc, request_id: &str, + on_cut: Box Final + Send + Sync>, ) -> FinishGuard { FinishGuard { store, clock, request_id: request_id.to_string(), + done: AtomicBool::new(false), + on_cut, } } pub fn finish(&self, out: Final) { + self.done.store(true, Ordering::SeqCst); self.store.finish(&self.request_id, out, self.clock.now()); } } impl Drop for FinishGuard { fn drop(&mut self) { - // A no-op when `finish` already ran: the first final status wins. - self.finish(Final::Dropped); + if !self.done.load(Ordering::SeqCst) { + let out = (self.on_cut)(); + self.finish(out); + } + } +} + +/// The detached async forwards. Shutdown waits for them like it waits for blocking requests, and +/// cuts the ones still running when the wait ends. +pub struct AsyncTasks { + live: AtomicUsize, + idle: Notify, + cut: watch::Sender, +} + +impl Default for AsyncTasks { + fn default() -> AsyncTasks { + AsyncTasks { + live: AtomicUsize::new(0), + idle: Notify::new(), + cut: watch::channel(false).0, + } + } +} + +struct Live(Arc); + +impl Drop for Live { + fn drop(&mut self) { + if self.0.live.fetch_sub(1, Ordering::SeqCst) == 1 { + self.0.idle.notify_waiters(); + } + } +} + +impl AsyncTasks { + /// Run `f` detached. It is dropped, and so runs its guards, when [`AsyncTasks::cut`] fires. + pub fn spawn(self: &Arc, f: F) + where + F: std::future::Future + Send + 'static, + { + self.live.fetch_add(1, Ordering::SeqCst); + let live = Live(Arc::clone(self)); + let mut cut = self.cut.subscribe(); + tokio::spawn(async move { + let _live = live; + tokio::select! { + () = f => {} + _ = cut.wait_for(|c| *c) => {} + } + }); + } + + /// Resolves once no task is running. + pub async fn idle(&self) { + loop { + let n = self.idle.notified(); + tokio::pin!(n); + n.as_mut().enable(); + if self.live.load(Ordering::SeqCst) == 0 { + return; + } + n.await; + } + } + + /// Cancel every running task. + pub fn cut(&self) { + self.cut.send_replace(true); } } @@ -276,25 +333,14 @@ pub async fn poll( return json_response(StatusCode::BAD_REQUEST, &json!({"error": "bad_wait"})); }; let deadline = Instant::now() + Duration::from_secs(wait); - let mut count = true; loop { - let (id, notify) = match store.read(token, clock.now(), count) { + let (id, notify) = match store.read(token, clock.now()) { Read::NotFound => return not_found(), - Read::Limited => { - let mut r = json_response( - StatusCode::TOO_MANY_REQUESTS, - &json!({"error": "rate_limited"}), - ); - r.headers_mut() - .insert(header::RETRY_AFTER, HeaderValue::from_static("1")); - return r; - } Read::Final { id, out } => { return json_response(StatusCode::OK, &final_json(&id, &out)) } Read::Pending { id, notify } => (id, notify), }; - count = false; let left = deadline.saturating_duration_since(Instant::now()); if left.is_zero() { return json_response( @@ -306,7 +352,7 @@ pub async fn poll( let notified = notify.notified(); tokio::pin!(notified); notified.as_mut().enable(); - if !matches!(store.read(token, clock.now(), false), Read::Pending { .. }) { + if !matches!(store.read(token, clock.now()), Read::Pending { .. }) { continue; } let _ = tokio::time::timeout(left, notified).await; diff --git a/crates/ap-proxy/src/async_poll/tests.rs b/crates/ap-proxy/src/async_poll/tests.rs index e892325..132cbf9 100644 --- a/crates/ap-proxy/src/async_poll/tests.rs +++ b/crates/ap-proxy/src/async_poll/tests.rs @@ -150,19 +150,17 @@ async fn wait_returns_pending_after_the_wait_and_the_final_status_when_it_arrive } #[tokio::test] -async fn a_token_is_rate_limited_per_clock_second() { +async fn rapid_polls_just_return_the_current_status() { let store = PollStore::default(); let c = clock(); let token = store.insert("r", c.now()); - for _ in 0..POLLS_PER_SEC { - assert_eq!(get(&store, &c, &token, None).await.0, StatusCode::OK); + for _ in 0..50 { + let (code, v) = get(&store, &c, &token, None).await; + assert_eq!( + (code, v["status"].as_str()), + (StatusCode::OK, Some("pending")) + ); } - assert_eq!( - get(&store, &c, &token, None).await.0, - StatusCode::TOO_MANY_REQUESTS - ); - c.advance(1); - assert_eq!(get(&store, &c, &token, None).await.0, StatusCode::OK); } #[tokio::test] @@ -170,7 +168,12 @@ async fn the_guard_ends_an_unfinished_entry_as_dropped() { let store = Arc::new(PollStore::default()); let c = clock(); let token = store.insert("r", c.now()); - drop(FinishGuard::new(Arc::clone(&store), c.clone(), "r")); + drop(FinishGuard::new( + Arc::clone(&store), + c.clone(), + "r", + Box::new(|| Final::Dropped), + )); assert_eq!(get(&store, &c, &token, None).await.1["status"], "dropped"); } diff --git a/crates/ap-proxy/src/hold/mod.rs b/crates/ap-proxy/src/hold/mod.rs index 59bd198..45e9286 100644 --- a/crates/ap-proxy/src/hold/mod.rs +++ b/crates/ap-proxy/src/hold/mod.rs @@ -53,10 +53,7 @@ pub struct Limits { impl Limits { pub fn from_config(pt: &Passthrough) -> Limits { Limits { - hold: Duration::from_secs(match pt.hold_mode { - ap_core::config::HoldMode::Blocking => pt.hold_secs, - ap_core::config::HoldMode::Async => pt.async_hold_secs, - }), + 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), @@ -288,10 +285,18 @@ impl Table { /// /// `persist` runs under the table lock, before the cooldown and cap checks. A failed write /// refuses with `audit_unavailable` and leaves no entry. A refusal after the write leaves the - /// `held` record in the log; the caller writes the terminal record with the refusal's code. - pub fn admit_async(&self, identity: &str, req: Arc, persist: F) -> Admission + /// `held` record in the log, so `refused` then writes the terminal record for the same id and + /// digest with the refusal's code, under the same lock, before the refusal is returned. + pub fn admit_async( + &self, + identity: &str, + req: Arc, + persist: F, + refused: R, + ) -> Admission where F: FnOnce(&str, &str) -> io::Result<()>, + R: FnOnce(&str, &str, Code), { let fingerprint = self.fingerprinter.fingerprint(&req); let digest = digest::audit_digest(&req); @@ -305,19 +310,23 @@ impl Table { return Admission::Refused(Code::AuditUnavailable); } g.cooldown.retain(|_, until| *until > now); - if g.cooldown.contains_key(identity) { - return Admission::Refused(Code::Cooldown); - } 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 refusal = if g.cooldown.contains_key(identity) { + Some(Code::Cooldown) + } else if own >= self.limits.max_per_identity { + Some(Code::IdentityCap) + } else if g.pending.len() >= self.limits.max_total { + Some(Code::TableFull) + } else { + None + }; + if let Some(code) = refusal { + refused(&id, &digest, code); + return Admission::Refused(code); } let nonce = digest::random_hex(12); let view_token = digest::random_hex(16); diff --git a/crates/ap-proxy/src/lib.rs b/crates/ap-proxy/src/lib.rs index 176d0ec..f3112b0 100644 --- a/crates/ap-proxy/src/lib.rs +++ b/crates/ap-proxy/src/lib.rs @@ -476,14 +476,21 @@ a passthrough-only config has no per-UID rules" app.hold.drain_pending(); let wait = std::time::Duration::from_secs(pt.request_deadline_secs) .saturating_add(std::time::Duration::from_secs(2)); - let ended = permits.acquire_many(pt.max_connections as u32); + // Detached async forwards count too: the 202 released their connection permit already. + let ended = async { + let _ = permits.acquire_many(pt.max_connections as u32).await; + app.async_tasks.idle().await; + }; tokio::select! { - _ = ended => {} + () = ended => {} () = tokio::time::sleep(wait) => { eprintln!("auth-proxy: shutdown wait reached the request deadline"); } _ = sigterm.recv() => {} _ = sigint.recv() => {} } + // Whatever still runs is cut; a forward past `forward_started` ends as `send_unknown`. + app.async_tasks.cut(); + let _ = tokio::time::timeout(std::time::Duration::from_secs(1), app.async_tasks.idle()).await; 0 } diff --git a/crates/ap-proxy/src/passthrough.rs b/crates/ap-proxy/src/passthrough.rs index 0726280..d986d83 100644 --- a/crates/ap-proxy/src/passthrough.rs +++ b/crates/ap-proxy/src/passthrough.rs @@ -67,6 +67,8 @@ pub struct PtApp { pub hold: Arc, /// Poll tokens and final statuses of the async hold mode. Empty in blocking mode. pub(crate) polls: Arc, + /// The detached async forwards, which shutdown waits for. + pub(crate) async_tasks: Arc, /// Told about each new distinct hold entry. `None` until a notifier is configured. pub notifier: Option>, /// `[approval].public_base_url` without a trailing slash: the notification link is @@ -191,6 +193,7 @@ impl PtApp { held_client, hold: Arc::new(hold::Table::new(limits)), polls: Arc::default(), + async_tasks: Arc::default(), notifier: None, approval_base: None, view_base: None, @@ -564,9 +567,14 @@ pub async fn handle(app: Arc, req: Request) -> Result` is answered before any authentication, because the + // Async hold mode (any route with `hold_mode = "async"`): `GET /poll/` is answered before any authentication, because the // token is its only credential and the answer must not depend on the headers sent. - if pt.hold_mode == HoldMode::Async { + if policy + .cfg + .routes + .iter() + .any(|r| r.hold_mode == HoldMode::Async) + { if let Some(token) = parts.uri.path().strip_prefix("/poll/") { if parts.method != Method::GET || token.is_empty() || token.contains('/') { return Ok(crate::async_poll::not_found()); diff --git a/crates/ap-proxy/src/passthrough/async_tests.rs b/crates/ap-proxy/src/passthrough/async_tests.rs index d12347f..73b70f8 100644 --- a/crates/ap-proxy/src/passthrough/async_tests.rs +++ b/crates/ap-proxy/src/passthrough/async_tests.rs @@ -8,7 +8,8 @@ const ASYNC: &str = "hold_mode = \"async\""; fn async_opts(extra: &str) -> Opts { Opts { - extra: format!("{ASYNC}\n{extra}"), + route_extra: ASYNC.to_string(), + extra: extra.to_string(), ..Opts::default() } } @@ -172,7 +173,9 @@ async fn denied_request_polls_as_denied_and_sends_nothing() { #[tokio::test] async fn unapproved_entry_expires_after_async_hold_secs() { let mock = Mock::start().await; - let t = Ht::with("async-expire", &mock.up, async_opts("async_hold_secs = 5")).await; + let mut o = async_opts(""); + o.route_extra.push_str("\nasync_hold_secs = 5"); + let t = Ht::with("async-expire", &mock.up, o).await; let a = t.submit("/discord/hold/ok", "{}").await; let (_, v) = t.poll(&a.token, "").await; assert_eq!(v["status"], "pending"); @@ -480,6 +483,17 @@ async fn admission_refusals_keep_their_codes_after_the_held_record_and_issue_no_ 2, "the held record comes before the checks" ); + // The refused request's id has a terminal record with the refusal's code and 503. + let refused_id = t.held(2).await; + assert_ne!(refused_id, a.id); + let term: Vec<_> = t + .lines() + .into_iter() + .filter(|v| v["request_id"] == refused_id.as_str() && v["transition"] != "held") + .collect(); + assert_eq!(term.len(), 1, "{term:?}"); + assert_eq!(term[0]["code"], "identity_cap"); + assert_eq!(term[0]["status"], 503); assert_eq!(t.app.hold.state(&a.id), Some(State::Pending)); assert_eq!(t.app.hold.pending_len(), 1); } @@ -530,18 +544,93 @@ async fn the_blocking_mode_is_the_default_and_has_no_poll_route() { } #[tokio::test] -async fn a_poll_that_is_rate_limited_changes_nothing() { +async fn rapid_polls_just_return_the_current_status() { let mock = Mock::start().await; - let t = async_ht("async-rate", &mock.up).await; + let t = async_ht("async-rapid", &mock.up).await; let a = t.submit("/discord/hold/ok", "{}").await; - let mut limited = false; for _ in 0..40 { - if t.poll(&a.token, "").await.0 == 429 { - limited = true; + let (code, v) = t.poll(&a.token, "").await; + assert_eq!((code, v["status"].as_str()), (200, Some("pending"))); + } + assert_eq!(t.app.hold.state(&a.id), Some(State::Pending)); +} + +/// A second held route on the same policy: another port, so its own `[[route]]`. +fn second_route(port: u16) -> String { + format!( + "\n[[route]]\nname = \"other\"\nhost = \"{HOST}\"\nport = {port}\nmode = \"passthrough\"\n\n[[grant]]\nidentity = \"muse-pilot\"\nroute = \"other\"\nmethods = [\"POST\"]\ndecision = \"hold\"\npath_patterns = [\"/hold/*\"]\n" + ) +} + +#[tokio::test] +async fn a_second_held_route_stays_blocking_while_the_muse_route_is_async() { + let mock = Mock::start().await; + let mut o = async_opts(""); + o.tail = second_route(mock.up.addr.port().wrapping_add(1).max(1024)); + let t = Ht::with("async-two-routes", &mock.up, o).await; + // The async route answers 202 at once. + let a = t.submit("/discord/hold/ok", "{}").await; + // The other route holds the caller's connection until it is decided, with an X-AP-Decision answer. + let first = t.spawn(t.post("/other/hold/ok", "{}")); + let id1 = t.held(2).await; + assert_ne!(id1, a.id); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(!first.is_finished()); + t.app.hold.deny(&id1, "alice"); + let (p1, _) = first.await.unwrap().unwrap(); + assert_eq!(p1.status.as_u16(), 423); + // And the async entry is untouched. + assert_eq!(t.poll(&a.token, "").await.1["status"], "pending"); +} + +#[tokio::test] +async fn shutdown_waits_for_a_started_forward_and_a_cut_after_start_is_send_unknown() { + let mock = Mock::start().await; + let t = async_ht("async-shutdown", &mock.up).await; + let a = t.submit("/discord/hold/stall", "{}").await; + t.app.hold.approve(&a.id, "alice").await; + for _ in 0..250 { + if t.count("forward_started") == 1 { break; } + tokio::time::sleep(Duration::from_millis(20)).await; } - // The loop may straddle a clock second; at 40 polls at least one second holds more than 10. - assert!(limited); - assert_eq!(t.app.hold.state(&a.id), Some(State::Pending)); + assert_eq!(t.count("forward_started"), 1); + // Shutdown closes the table; the started forward is not told to stop and the wait covers it. + t.app.hold.drain_pending(); + let waited = tokio::time::timeout(Duration::from_millis(400), t.app.async_tasks.idle()).await; + assert!( + waited.is_err(), + "the wait did not cover the started forward" + ); + assert_eq!(t.poll(&a.token, "").await.1["status"], "pending"); + // The wait ran out: the cut ends it as send_unknown, with the existing code, not dropped. + t.app.async_tasks.cut(); + tokio::time::timeout(Duration::from_secs(2), t.app.async_tasks.idle()) + .await + .expect("tasks ended"); + let v = t.poll(&a.token, "").await.1; + assert_eq!(v["status"], "send_unknown"); + assert_eq!(v["error_class"], "reset"); + let end: Vec<_> = t + .lines() + .into_iter() + .filter(|v| v["request_id"] == a.id.as_str() && v["transition"] == "completed") + .collect(); + assert_eq!(end.len(), 1); + assert_eq!(end[0]["code"], "upstream_reset"); + assert_eq!(t.count("abandoned_after_approve"), 0); +} + +#[tokio::test] +async fn a_cut_before_forward_started_is_dropped() { + let mock = Mock::start().await; + let t = async_ht("async-cut-early", &mock.up).await; + let a = t.submit("/discord/hold/ok", "{}").await; + t.app.async_tasks.cut(); + tokio::time::timeout(Duration::from_secs(2), t.app.async_tasks.idle()) + .await + .expect("tasks ended"); + assert_eq!(t.poll(&a.token, "").await.1["status"], "dropped"); + assert_eq!(mock.hits(), 0); } diff --git a/crates/ap-proxy/src/passthrough/hold_path.rs b/crates/ap-proxy/src/passthrough/hold_path.rs index 21d4523..2a257d5 100644 --- a/crates/ap-proxy/src/passthrough/hold_path.rs +++ b/crates/ap-proxy/src/passthrough/hold_path.rs @@ -514,7 +514,7 @@ pub(super) async fn run(r: Request<'_>) -> Result, ConnAbort> { started: trail.started, }; - if pt.hold_mode == HoldMode::Async { + if route.hold_mode == HoldMode::Async { return Ok(async_mode::run(async_mode::Request { app, trail, @@ -530,7 +530,7 @@ pub(super) async fn run(r: Request<'_>) -> Result, ConnAbort> { None => rel.to_string(), }, ), - hold: Duration::from_secs(pt.async_hold_secs), + hold: Duration::from_secs(route.async_hold_secs), deadline: Duration::from_secs(pt.request_deadline_secs), idle: Duration::from_secs(pt.upstream_idle_secs), identity, diff --git a/crates/ap-proxy/src/passthrough/hold_path/async_mode.rs b/crates/ap-proxy/src/passthrough/hold_path/async_mode.rs index c38aefc..16e0a3b 100644 --- a/crates/ap-proxy/src/passthrough/hold_path/async_mode.rs +++ b/crates/ap-proxy/src/passthrough/hold_path/async_mode.rs @@ -59,21 +59,62 @@ pub(super) async fn run(r: Request<'_>) -> Response { // The `held` record is written first, under the table lock. A failed write refuses before any // entry exists; a refusal by the checks that follow leaves the record and gets its own. - let admission = app - .hold - .admit_async(identity, Arc::clone(&req), |id, digest| { + let admission = app.hold.admit_async( + identity, + Arc::clone(&req), + |id, digest| { let mut rec = ctx.rec(id, digest, "held", None, None, None); rec.upstream = Some(req.upstream.authority()); rec.policy_generation = Some(req.generation); app.audit.try_write_hold(&rec) - }); + }, + // A refusal after the `held` record gets its own terminal record for the same id. + |id, digest, code| { + let rec = ctx.rec( + id, + digest, + "abandoned", + None, + Some(code.code_str()), + Some(503), + ); + app.audit.write_hold(&rec); + }, + ); let held = match admission { Admission::Refused(code) => return refuse(&app, &trail, code), Admission::Held(h) => h, }; let token = app.polls.insert(&held.id, app.clock.now()); announce(&app, &ctx, &held); - let fin = FinishGuard::new(Arc::clone(&app.polls), Arc::clone(&app.clock), &held.id); + let started = Arc::new(Started::new()); + // If the task is cut (shutdown past the wait), a forward that already passed + // `forward_started` is `send_unknown`, never `dropped`; before it, `dropped`. + let on_cut = { + let (app, ctx, started) = (Arc::clone(&app), ctx.clone(), Arc::clone(&started)); + let (id, digest) = (held.id.clone(), held.digest.clone()); + Box::new(move || { + if started.get().is_some() { + app.audit.write_hold(&ctx.rec( + &id, + &digest, + "completed", + None, + Some("upstream_reset"), + None, + )); + Final::SendUnknown("reset") + } else { + Final::Dropped + } + }) + }; + let fin = FinishGuard::new( + Arc::clone(&app.polls), + Arc::clone(&app.clock), + &held.id, + on_cut, + ); let guard = Guard { app: Arc::clone(&app), ctx, @@ -81,11 +122,12 @@ pub(super) async fn run(r: Request<'_>) -> Response { digest: held.digest, phase: Phase::Pending, rx: Some(held.decision), - started: Arc::new(Started::new()), + started, }; trail.write_evidence(&app.audit, 202); let response = async_poll::accepted(&guard.id, &token); - tokio::spawn(drive(Drive { + let tasks = Arc::clone(&app.async_tasks); + tasks.spawn(drive(Drive { app, trail, req, diff --git a/crates/ap-proxy/src/passthrough/hold_tests.rs b/crates/ap-proxy/src/passthrough/hold_tests.rs index 6da7781..e5a376f 100644 --- a/crates/ap-proxy/src/passthrough/hold_tests.rs +++ b/crates/ap-proxy/src/passthrough/hold_tests.rs @@ -256,6 +256,8 @@ struct Opts { limits: Limits, /// Extra keys inside `[passthrough]`. extra: String, + /// Extra keys inside the `discord` `[[route]]`. + route_extra: String, held_body_max: u64, /// Text appended after the grants. tail: String, @@ -276,6 +278,7 @@ impl Default for Opts { cooldown: Duration::ZERO, }, extra: String::new(), + route_extra: String::new(), held_body_max: 2048, tail: String::new(), port: None, @@ -333,6 +336,7 @@ name = "discord" host = "{HOST}" port = {port} mode = "passthrough" +{route_extra} [[grant]] identity = "muse-pilot" @@ -357,6 +361,7 @@ path_patterns = ["/hold/*"] "#, max = o.held_body_max, extra = o.extra, + route_extra = o.route_extra, tail = o.tail, sha = sha256_hex(&key), sha2 = sha256_hex(&other_key),