From 157df6973dfd1f3a11f75246406b8ea9cc031827 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:53:54 +0000 Subject: [PATCH 1/5] fix(proxy): audit the end of a web response before releasing its last frame hyper's HTTP/1 server drops a body with a known length as soon as it is written in full, without polling for its end. The outcome audit only started on Ready(None), so on HTTP/1 every Content-Length response was audited from Drop as "client_disconnected", in a detached task whose failure could not close the connection (ADR-0022: audit fails closed). Hold back the upstream's last frame until the "complete" event is written; an empty body, which may never be polled at all, is audited before the head goes out and answered 503 if that fails. The tests serve a real HTTP/1 upstream and fail without the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYYXVETRewQNUQF7xTn --- crates/limen-proxy/src/web.rs | 174 +++++++++++++++++++++++++++++++++- 1 file changed, 173 insertions(+), 1 deletion(-) diff --git a/crates/limen-proxy/src/web.rs b/crates/limen-proxy/src/web.rs index 5778b4d9..bfa616dd 100644 --- a/crates/limen-proxy/src/web.rs +++ b/crates/limen-proxy/src/web.rs @@ -609,7 +609,7 @@ pub(crate) async fn handle(proxy: &Proxy, mut req: Request) -> ProxyRe let status = upstream_response.status(); let (parts, body) = upstream_response.into_parts(); - let response_body = AuditResponseBody { + let mut response_body = AuditResponseBody { inner: body, audit: proxy.audit.clone(), context: AuditContext { @@ -634,7 +634,22 @@ pub(crate) async fn handle(proxy: &Proxy, mut req: Request) -> ProxyRe audit_started: false, done: false, pending_error: None, + held: None, }; + if response_body.inner.is_end_stream() { + // An empty body (HEAD, 204, 304, `Content-Length: 0`) may never be + // polled: hyper's HTTP/1 server writes the head and drops it. Audit the + // outcome before the head goes out, so a failed emit still refuses. + response_body.start_audit("complete"); + response_body.done = true; + let emitted = match response_body.audit_rx.take() { + Some(rx) => matches!(rx.await, Ok(Ok(()))), + None => false, + }; + if !emitted { + return plain(StatusCode::SERVICE_UNAVAILABLE, "audit is unavailable"); + } + } Response::from_parts(parts, tonic::body::Body::new(response_body)) } @@ -1632,6 +1647,11 @@ struct AuditResponseBody { audit_started: bool, done: bool, pending_error: Option, + /// The upstream's last frame, held back until the outcome is audited. Once + /// a body with a known length has been written in full, hyper's HTTP/1 + /// server drops it without polling for the end, so waiting for + /// `Ready(None)` would leave the audit to `Drop`, which can't fail closed. + held: Option>, } impl AuditResponseBody { @@ -1689,6 +1709,8 @@ impl HttpBody for AuditResponseBody { this.done = true; if let Some(error) = this.pending_error.take() { Poll::Ready(Some(Err(error))) + } else if let Some(frame) = this.held.take() { + Poll::Ready(Some(Ok(frame))) } else { Poll::Ready(None) } @@ -1715,6 +1737,11 @@ impl HttpBody for AuditResponseBody { this.download .fetch_add(data.len() as u64, Ordering::Relaxed); } + if this.inner.is_end_stream() { + this.held = Some(frame); + this.start_audit("complete"); + return Pin::new(this).poll_frame(cx); + } Poll::Ready(Some(Ok(frame))) } Poll::Ready(Some(Err(error))) => { @@ -1794,6 +1821,151 @@ pub mod fuzz { #[cfg(test)] mod tests { + /// The outcome of a proxied response is audited as `complete`, and fails + /// closed, on HTTP/1 too, where hyper drops a body with a known length as + /// soon as it is written, without polling for its end. + mod response_audit { + use super::super::*; + use limen_audit::FailureMode; + use limen_audit::sink::MemorySink; + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + + /// A response body as the upstream client hands it over: hyper's + /// `Incoming`, from an HTTP/1 server that sends `Content-Length`. + async fn upstream(body: &'static [u8], method: Method) -> Incoming { + let (server_io, client_io) = tokio::io::duplex(64 * 1024); + tokio::spawn(async move { + let service = + hyper::service::service_fn(move |_req: Request| async move { + Ok::<_, std::convert::Infallible>(Response::new(http_body_util::Full::new( + Bytes::from_static(body), + ))) + }); + let _ = hyper::server::conn::http1::Builder::new() + .serve_connection(TokioIo::new(server_io), service) + .await; + }); + let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(client_io)) + .await + .expect("handshake"); + tokio::spawn(conn); + let req = Request::builder() + .method(method) + .uri("/") + .body(http_body_util::Empty::::new()) + .expect("request"); + sender + .send_request(req) + .await + .expect("response") + .into_body() + } + + fn body(inner: Incoming, audit: limen_audit::Emitter) -> AuditResponseBody { + AuditResponseBody { + inner, + audit, + context: AuditContext { + user: Some("alice".into()), + session_id: None, + }, + event: json!({}), + status: StatusCode::OK, + session_id: Uuid::nil(), + request_started: Instant::now(), + upload: Arc::new(AtomicU64::new(0)), + download: Arc::new(AtomicU64::new(0)), + audit_rx: None, + audit_started: false, + done: false, + pending_error: None, + held: None, + } + } + + /// Serve `body` to a raw HTTP/1 client and return what the client read + /// before the connection closed (or 2 s passed). + async fn serve(body: AuditResponseBody) -> Vec { + let (server_io, mut client_io) = tokio::io::duplex(64 * 1024); + let body = std::sync::Mutex::new(Some(body)); + let service = hyper::service::service_fn(move |_req: Request| { + let body = body.lock().expect("lock").take().expect("one request"); + async move { + Ok::<_, std::convert::Infallible>(Response::new(tonic::body::Body::new(body))) + } + }); + tokio::spawn( + hyper::server::conn::http1::Builder::new() + .serve_connection(TokioIo::new(server_io), service), + ); + client_io + .write_all(b"GET / HTTP/1.1\r\nhost: app\r\n\r\n") + .await + .expect("write"); + let mut read = Vec::new(); + let mut buf = [0u8; 4096]; + loop { + match tokio::time::timeout( + std::time::Duration::from_secs(2), + client_io.read(&mut buf), + ) + .await + { + Ok(Ok(0) | Err(_)) | Err(_) => break, + Ok(Ok(n)) => read.extend_from_slice(&buf[..n]), + } + if read.ends_with(b"hello world") { + break; + } + } + read + } + + #[tokio::test] + async fn a_complete_http1_response_is_audited_as_complete() { + let sink = Arc::new(MemorySink::default()); + let audit = + limen_audit::Emitter::new("proxy", "p1", sink.clone(), FailureMode::FailClosed); + let read = serve(body(upstream(b"hello world", Method::GET).await, audit)).await; + assert!( + read.ends_with(b"hello world"), + "{}", + String::from_utf8_lossy(&read) + ); + let events = sink.events(); + assert_eq!(events.len(), 1, "{events:?}"); + assert_eq!(events[0].data["reason"], "complete"); + assert_eq!(events[0].data["bytes_out"], 11); + } + + #[tokio::test] + async fn a_failed_outcome_audit_withholds_the_end_of_the_response() { + let sink = Arc::new(MemorySink::default()); + sink.set_failing(true); + let audit = + limen_audit::Emitter::new("proxy", "p1", sink.clone(), FailureMode::FailClosed); + let read = serve(body(upstream(b"hello world", Method::GET).await, audit)).await; + assert!( + !read.ends_with(b"hello world"), + "{}", + String::from_utf8_lossy(&read) + ); + } + + #[tokio::test] + async fn an_empty_upstream_body_reads_as_ended() { + // `proxy_request` audits these before the head goes out. + let audit = limen_audit::Emitter::new( + "proxy", + "p1", + Arc::new(MemorySink::default()), + FailureMode::FailClosed, + ); + let b = body(upstream(b"hello world", Method::HEAD).await, audit); + assert!(b.inner.is_end_stream()); + } + } + #[test] fn preauth_denials_are_limited_per_source_and_counted() { use super::{PreAuth, PreAuthDenials}; From ae583ab8921cb10a08ab81d264ca478d13731797 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:53:54 +0000 Subject: [PATCH 2/5] fix(worker): read MariaDB executable comments as SQL MariaDB runs the content of /*M! ... */ (and /*M!100100 ... */), but sqlparser expands only /*! ... */, so a statement inside one was classified as "empty". USE and KILL inside it got past the one-database and KILL-ownership guards, and normalize_literals audited it as /* ? */. Tokenize the content as code for MySQL targets, in both split and normalize. On MySQL proper it is a comment, so the stricter reading only refuses more. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYYXVETRewQNUQF7xTn --- crates/limen-worker/src/db/sqltext.rs | 75 +++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 9 deletions(-) diff --git a/crates/limen-worker/src/db/sqltext.rs b/crates/limen-worker/src/db/sqltext.rs index 5512c064..7fce434e 100644 --- a/crates/limen-worker/src/db/sqltext.rs +++ b/crates/limen-worker/src/db/sqltext.rs @@ -127,12 +127,41 @@ fn render(tokens: &[Token]) -> String { tokens.iter().map(ToString::to_string).collect() } +/// The code inside a MariaDB executable comment (`/*M! ... */`, +/// `/*M!100100 ... */`), without the marker and version digits. MariaDB runs it +/// and MySQL ignores it; sqlparser expands only the `/*! ... */` form. +fn mariadb_code(body: &str) -> Option<&str> { + body.strip_prefix("M!") + .map(|code| code.trim_start_matches(|c: char| c.is_ascii_digit())) +} + +/// Tokenize `sql`. For MySQL, the content of a MariaDB executable comment is +/// tokenized as code, so a statement inside one is classified (and refused or +/// audited) as what the server will run, not hidden as a comment. +fn tokenize(sql: &str, flavor: Flavor) -> Option> { + let tokens = Tokenizer::new(flavor.dialect(), sql).tokenize().ok()?; + if flavor != Flavor::Mysql { + return Some(tokens); + } + let mut out = Vec::with_capacity(tokens.len()); + for token in tokens { + match &token { + Token::Whitespace(Whitespace::MultiLineComment(body)) => match mariadb_code(body) { + Some(code) => out.extend(tokenize(code, flavor)?), + None => out.push(token), + }, + _ => out.push(token), + } + } + Some(out) +} + /// Split a simple-protocol message into statements. The common single /// statement is returned exactly as written; several are re-rendered from /// their tokens. #[must_use] pub fn split(sql: &str, flavor: Flavor) -> Vec { - let Ok(tokens) = Tokenizer::new(flavor.dialect(), sql).tokenize() else { + let Some(tokens) = tokenize(sql, flavor) else { return vec![Statement { kind: "unknown", text: sql.to_owned(), @@ -186,15 +215,22 @@ pub fn normalize(sql: &str, flavor: Flavor) -> String { let newline = if comment.ends_with('\n') { "\n" } else { "" }; format!("{prefix}?{newline}") } - Token::Whitespace(Whitespace::MultiLineComment(body)) => match body.strip_prefix('!') { - Some(code) if flavor == Flavor::Mysql => { - // Skip the optional version digits, then normalize what runs. - let digits = code.chars().take_while(char::is_ascii_digit).count(); - let (version, code) = code.split_at(digits); - format!("/*!{version}{}*/", normalize(code, flavor)) + Token::Whitespace(Whitespace::MultiLineComment(body)) => { + let (marker, code) = match (body.strip_prefix("M!"), body.strip_prefix('!')) { + (Some(code), _) => ("M!", Some(code)), + (None, Some(code)) => ("!", Some(code)), + (None, None) => ("", None), + }; + match code { + Some(code) if flavor == Flavor::Mysql => { + // Skip the optional version digits, then normalize what runs. + let digits = code.chars().take_while(char::is_ascii_digit).count(); + let (version, code) = code.split_at(digits); + format!("/*{marker}{version}{}*/", normalize(code, flavor)) + } + _ => "/* ? */".to_owned(), } - _ => "/* ? */".to_owned(), - }, + } Token::Number(..) | Token::SingleQuotedString(_) | Token::DoubleQuotedString(_) @@ -306,6 +342,27 @@ mod tests { assert!(my("/*! drop table t */").contains("drop table t")); // An optimizer hint is an ordinary comment. assert_eq!(my("select /*+ tok_9f */ 1"), "select /* ? */ ?"); + // MariaDB runs `/*M! ... */` too: normalized as SQL, not hidden. + let ran = my("/*M!100100 kill 'tok_9f' */"); + assert!(ran.contains("kill ?") && !ran.contains("tok_9f"), "{ran}"); + assert_eq!(pg("select /*M! tok_9f */ 1"), "select /* ? */ ?"); + } + + /// A statement inside a MariaDB executable comment is classified as what + /// the server runs, so the worker's `USE` and `KILL` guards see it. + #[test] + fn mariadb_executable_comments_are_classified_as_code() { + let kinds = |q: &str, f: Flavor| split(q, f).iter().map(|s| s.kind).collect::>(); + assert_eq!(kinds("/*M!USE secret*/", Flavor::Mysql), ["use"]); + assert_eq!(kinds("/*M!100100 KILL 42*/", Flavor::Mysql), ["kill"]); + assert_eq!(kinds("/*M!KILL 42*/", Flavor::Mysql), ["kill"]); + assert_eq!( + kinds("select 1; /*M! use other */", Flavor::Mysql), + ["select", "use"] + ); + // An ordinary comment is still a comment, and PostgreSQL has no such form. + assert_eq!(kinds("/* M! use x */", Flavor::Mysql), ["empty"]); + assert_eq!(kinds("/*M!USE secret*/", Flavor::Postgres), ["empty"]); } /// Whatever is typed, the canary never reaches the normalized text. A From a1de17df3bddae7a0f77d826f31360e6f756a687 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:53:54 +0000 Subject: [PATCH 3/5] fix(console): don't panic on a date filter of 9999-12-31 An upper bound that is a bare date adds one day, which is out of range for the last representable date and panicked the handler (GET /console/sessions?to=9999-12-31, open to any signed-in user). Use checked_add; the value is then reported as ignored like any other bad date. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYYXVETRewQNUQF7xTn --- crates/limen-control-plane/src/console/query.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/limen-control-plane/src/console/query.rs b/crates/limen-control-plane/src/console/query.rs index 88aefdd9..a6fce264 100644 --- a/crates/limen-control-plane/src/console/query.rs +++ b/crates/limen-control-plane/src/console/query.rs @@ -43,11 +43,12 @@ pub fn parse_when(s: &str, end: bool) -> Option { let s = s.trim(); if let Ok(date) = Date::parse(s, format_description!("[year]-[month]-[day]")) { let start = date.midnight().assume_utc(); - return Some(if end { - start + Duration::days(1) + // `checked_add`: the day after 9999-12-31 is out of range and `+` panics. + return if end { + start.checked_add(Duration::days(1)) } else { - start - }); + Some(start) + }; } PrimitiveDateTime::parse( s, @@ -133,6 +134,12 @@ mod tests { assert!(parse_when("yesterday", false).is_none()); } + #[test] + fn the_last_representable_day_does_not_panic() { + assert!(parse_when("9999-12-31", false).is_some()); + assert!(parse_when("9999-12-31", true).is_none()); + } + #[test] fn bad_times_are_reported_not_applied() { let (from, to, ignored) = parse_range(Some("nope"), Some("2026-10-24")); From 927ae2c50dc1fc696d7f509c18892fff25ccfad8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:53:54 +0000 Subject: [PATCH 4/5] fix(console): refuse an unknown access or review decision Anything other than "approve" was read as a deny, and anything other than "certify" as a flag, which withholds the role and ends the subject's sessions. Both are irreversible. Accept only the two values each form sends and refuse the rest, as the policy-change handler already does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYYXVETRewQNUQF7xTn --- .../src/console/workflows.rs | 38 ++++++++++++++++++- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/limen-control-plane/src/console/workflows.rs b/crates/limen-control-plane/src/console/workflows.rs index 011c16cd..57b2072c 100644 --- a/crates/limen-control-plane/src/console/workflows.rs +++ b/crates/limen-control-plane/src/console/workflows.rs @@ -116,6 +116,20 @@ pub struct PageQuery { } /// Where a failed form goes back to, with the reason kept short and escaped by the template. +/// Reads a two-way form decision: `Some(true)` for `yes`, `Some(false)` for +/// `no`, and `None` for anything else, so a missing or mangled value is refused +/// instead of being read as the irreversible choice (a deny, or a flag that +/// ends the subject's sessions). +fn decision(value: &str, yes: &str, no: &str) -> Option { + if value == yes { + Some(true) + } else if value == no { + Some(false) + } else { + None + } +} + fn back_with_error(path: &str, status: &tonic::Status) -> Response { let msg: String = status.message().chars().take(200).collect(); Redirect::to(&format!( @@ -444,8 +458,10 @@ pub async fn access_decide( if let Err(r) = auth.check_post(console, &headers, &f.csrf) { return r; } - let approve = f.decision == "approve"; let back = format!("/console/access/{}", path_segment(&id)); + let Some(approve) = decision(&f.decision, "approve", "deny") else { + return back_with_error(&back, &tonic::Status::invalid_argument("unknown decision")); + }; match access::decide(&state, &access_who(&auth), &id, approve, &f.comment).await { Ok(_) => Redirect::to(&format!( "{back}?done={}", @@ -819,8 +835,10 @@ pub async fn review_decide( if let Err(r) = auth.check_post(console, &headers, &f.csrf) { return r; } - let certify = f.decision == "certify"; let back = format!("/console/reviews/{}", path_segment(&f.review)); + let Some(certify) = decision(&f.decision, "certify", "flag") else { + return back_with_error(&back, &tonic::Status::invalid_argument("unknown decision")); + }; match reviews::decide(&state, &review_who(&auth), &item, certify, &f.comment).await { Ok(_) => Redirect::to(&format!( "{back}?done={}", @@ -1292,3 +1310,19 @@ pub async fn session_extras( .collect(); (ids, watched) } + +#[cfg(test)] +mod tests { + use super::decision; + + #[test] + fn only_the_two_known_decisions_are_read() { + assert_eq!(decision("approve", "approve", "deny"), Some(true)); + assert_eq!(decision("deny", "approve", "deny"), Some(false)); + assert_eq!(decision("certify", "certify", "flag"), Some(true)); + assert_eq!(decision("flag", "certify", "flag"), Some(false)); + for odd in ["", "Approve", "approve ", "DENY", "certify", "yes"] { + assert_eq!(decision(odd, "approve", "deny"), None, "{odd:?}"); + } + } +} From e10fd6a6ee50c68d9f50f390c1cfbd8526dd55cc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:53:55 +0000 Subject: [PATCH 5/5] fix(cli): write known_hosts atomically like the other profile files It was the one profile file written with std::fs::write: an interrupted write left a truncated host-CA trust file, and its mode followed the umask. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SEiXYYXVETRewQNUQF7xTn --- crates/limen-cli/src/commands/ssh.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/limen-cli/src/commands/ssh.rs b/crates/limen-cli/src/commands/ssh.rs index c562465b..4b58dc07 100644 --- a/crates/limen-cli/src/commands/ssh.rs +++ b/crates/limen-cli/src/commands/ssh.rs @@ -28,7 +28,10 @@ pub fn write_known_hosts(proxy: &str, host_ca_public_key: &str) -> anyhow::Resul bail!("the control plane returned an invalid SSH host CA key"); } let path = profile::dir_for(proxy)?.join(KNOWN_HOSTS); - std::fs::write(&path, format!("# Written by `limen login`. Trusts the Limen SSH host CA for hosts reached through {proxy}.\n@cert-authority * {key}\n")) + // Through the profile's atomic write, like every other profile file: an + // interrupted write must not leave a truncated trust file behind, and the + // mode must not depend on the umask. + profile::write_file(&path, &format!("# Written by `limen login`. Trusts the Limen SSH host CA for hosts reached through {proxy}.\n@cert-authority * {key}\n"), false) .with_context(|| format!("writing {}", path.display())) }