From d5fbc62131b0d5f04d9814b981b2b9a298c34ac6 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 16:57:17 +0000 Subject: [PATCH 01/10] server: refuse ambiguous request framing - Resolve the body framing from the head before anything is written or read. An unparseable Content-Length used to mean "no body", so its bytes were parsed as the next request line and could carry a second request past the gate. - Refuse a shape a proxy in front of the server could have framed differently: a Content-Length that is not all digits, unequal duplicates, a Content-Length alongside Transfer-Encoding, and any transfer-coding list other than exactly one chunked. - Accept equal duplicate lengths, since header rewriting produces them and they frame the same message. The socket tests send a complete second request behind the bad head: a proceed-and-panic gate proves the 400 comes from the framing decision, and the read to end-of-file proves the second request never got served. --- src/server/http.rs | 239 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 212 insertions(+), 27 deletions(-) diff --git a/src/server/http.rs b/src/server/http.rs index 5aa5bda..3d0067f 100644 --- a/src/server/http.rs +++ b/src/server/http.rs @@ -614,8 +614,86 @@ fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option { .position(|window| window == needle) } +/// How a request body is framed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Framing { + /// The head announced no body. + None, + /// A body of exactly this many bytes. + Length(usize), + /// A chunked body. + Chunked, +} + +/// Every value of a header, in the order the client sent them. +fn all_values<'a>(headers: &'a [(String, String)], name: &str) -> Vec<&'a str> { + headers + .iter() + .filter(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) + .collect() +} + +/// Decide how the body is framed, or refuse a head this server cannot agree on. +/// +/// Guessing here is what let an unread body prefix the next request: an +/// unparseable `Content-Length` used to mean "no body", so its bytes were read +/// as the next request line. A shape a proxy in front of this server could +/// have framed differently is refused instead of resolved. +fn framing(headers: &[(String, String)]) -> Result { + let lengths = all_values(headers, "content-length"); + let encodings = all_values(headers, "transfer-encoding"); + + // A proxy may have honoured either header. The server cannot tell which, + // so it must not pick one. + if !encodings.is_empty() && !lengths.is_empty() { + return Err(BodyError::Malformed); + } + + if !encodings.is_empty() { + // RFC 9112 §6.1: combine the field lines, in order, into one list. + let combined = encodings.join(","); + let mut codings = combined.split(',').map(str::trim); + let only = codings.next().unwrap_or_default(); + // The only framing implemented here is a single `chunked`. This also + // rejects `xchunked`, `gzip, chunked`, and an empty list. + if codings.next().is_some() || !only.eq_ignore_ascii_case("chunked") { + return Err(BodyError::Malformed); + } + return Ok(Framing::Chunked); + } + + let mut length = None; + for value in &lengths { + // `str::parse` would accept a leading `+`, which is not + // `Content-Length` syntax and may be framed differently by a proxy. + let value = value.trim(); + if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(BodyError::Malformed); + } + let Ok(parsed) = value.parse::() else { + return Err(BodyError::Malformed); + }; + match length { + // Equal duplicates come from header rewriting and frame the same + // message; a difference means the sender and this server disagree. + Some(previous) if previous != parsed => return Err(BodyError::Malformed), + _ => length = Some(parsed), + } + } + + Ok(match length { + Some(length) => Framing::Length(length), + None => Framing::None, + }) +} + /// Read the request body, collecting it when `keep` is true. /// +/// The framing is decided before anything is written or read: a malformed +/// announcement must not be answered with `100 Continue`, and its bytes must +/// not be left in the socket for the next request to parse. +/// /// With `keep` false the bytes are read and thrown away in a fixed-size /// buffer, so a refusal can consume what the client is still sending without /// allocating the body. @@ -626,41 +704,31 @@ fn read_body( keep: bool, max_body_bytes: usize, ) -> Result, BodyError> { - let lookup = |name: &str| { - headers - .iter() - .find(|(key, _)| key.eq_ignore_ascii_case(name)) - .map(|(_, value)| value.as_str()) - }; + let framing = framing(headers)?; - if keep && lookup("expect").is_some_and(|value| value.eq_ignore_ascii_case("100-continue")) { + if keep && !matches!(framing, Framing::None) && expects_continue(headers) { writer.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?; writer.flush()?; } - if let Some(encoding) = lookup("transfer-encoding") - && encoding.to_ascii_lowercase().contains("chunked") - { - return read_chunked_body(reader, keep, max_body_bytes); - } - - let Some(length) = lookup("content-length").and_then(|value| value.parse::().ok()) - else { - return Ok(Vec::new()); - }; + match framing { + Framing::None => Ok(Vec::new()), + Framing::Chunked => read_chunked_body(reader, keep, max_body_bytes), + Framing::Length(length) => { + if length > max_body_bytes { + return Err(BodyError::TooLarge); + } - if length > max_body_bytes { - return Err(BodyError::TooLarge); - } + if !keep { + discard(reader, length)?; + return Ok(Vec::new()); + } - if !keep { - discard(reader, length)?; - return Ok(Vec::new()); + let mut body = vec![0u8; length]; + reader.read_exact(&mut body)?; + Ok(body) + } } - - let mut body = vec![0u8; length]; - reader.read_exact(&mut body)?; - Ok(body) } /// Read and throw away exactly `length` bytes. @@ -902,6 +970,71 @@ mod tests { assert!(matches!(error, BodyError::TooLarge)); } + /// The framing decision for a head written as name/value pairs. + fn framing_of(headers: &[(&str, &str)]) -> Result { + let headers: Vec<(String, String)> = headers + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect(); + framing(&headers) + } + + #[test] + fn framing_decisions_are_table_driven() { + use Framing::{Chunked, Length, None as NoBody}; + + assert_eq!(framing_of(&[]).ok(), Some(NoBody)); + assert_eq!(framing_of(&[("Content-Length", "5")]).ok(), Some(Length(5))); + assert_eq!( + framing_of(&[("Content-Length", "0")]).ok(), + Some(Length(0)), + "an explicit empty body is still a length" + ); + assert_eq!( + framing_of(&[("content-length", "5"), ("Content-Length", "5")]).ok(), + Some(Length(5)), + "equal duplicates are accepted" + ); + assert_eq!( + framing_of(&[("Content-Length", "5"), ("Content-Length", "05")]).ok(), + Some(Length(5)), + "equal values written differently still agree" + ); + assert_eq!( + framing_of(&[("Transfer-Encoding", "chunked")]).ok(), + Some(Chunked) + ); + assert_eq!( + framing_of(&[("Transfer-Encoding", "Chunked")]).ok(), + Some(Chunked), + "the coding name is case-insensitive" + ); + + for headers in [ + vec![("Content-Length", "5"), ("Content-Length", "6")], + vec![("Content-Length", "abc")], + vec![("Content-Length", "")], + vec![("Content-Length", "-1")], + vec![("Content-Length", "+5")], + vec![("Content-Length", "5 5")], + vec![("Content-Length", "99999999999999999999999999")], + vec![("Content-Length", "5"), ("Transfer-Encoding", "chunked")], + vec![("Transfer-Encoding", "gzip, chunked")], + vec![("Transfer-Encoding", "chunked, gzip")], + vec![("Transfer-Encoding", "xchunked")], + vec![("Transfer-Encoding", "")], + vec![ + ("Transfer-Encoding", "chunked"), + ("Transfer-Encoding", "chunked"), + ], + ] { + assert!( + matches!(framing_of(&headers), Err(BodyError::Malformed)), + "{headers:?} must be refused" + ); + } + } + #[test] fn chunked_checks_use_the_configured_limit() { let (mut client, server) = tcp_pair(); @@ -1012,6 +1145,58 @@ mod integration_tests { assert!(response.starts_with("HTTP/1.1 401"), "{response}"); } + /// A head whose framing is refused answers one `400` and closes. + /// + /// The gate proceeds and the handler panics, so a `400` here can only come + /// from the framing decision. The request is followed by a complete second + /// request in the same write: the failure this guards against is the first + /// body's bytes being parsed as the next request line. + fn assert_framing_refused(head: &str) { + let gate = Arc::new(|_: &Request| GateDecision::Proceed { keep_body: true }); + let handler = Arc::new(|_: Request| -> Response { + panic!("a request with malformed framing must not reach the handler") + }); + let port = start_with_gate(gate, handler); + + let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let request = format!( + "POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\n{head}\r\nGET /health HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n" + ); + stream.write_all(request.as_bytes()).unwrap(); + + // Reading to `Ok(0)` is the close: a read that timed out instead would + // return an error here, and a second response would break the count. + let mut response = String::new(); + stream + .read_to_string(&mut response) + .expect("the connection closes after the refusal"); + assert!(response.starts_with("HTTP/1.1 400"), "{response}"); + assert!(response.contains("malformed_body"), "{response}"); + assert_eq!( + response.matches("HTTP/1.1 ").count(), + 1, + "one refusal and then a close: {response}" + ); + } + + #[test] + fn a_malformed_content_length_cannot_prefix_the_next_request() { + assert_framing_refused("Content-Length: abc"); + } + + #[test] + fn a_conflicting_content_length_is_refused() { + assert_framing_refused("Content-Length: 5\r\nContent-Length: 6"); + } + + #[test] + fn content_length_alongside_chunked_is_refused() { + assert_framing_refused("Content-Length: 5\r\nTransfer-Encoding: chunked"); + } + #[test] fn an_oversized_chunk_is_refused_and_the_server_survives() { let port = start(Arc::new(|_: Request| Response::json(200, "{}"))); From d051c215d9b2cb110d851512996c88cda77eb846 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 16:58:58 +0000 Subject: [PATCH 02/10] server: bound request reads and allocate from received bytes - Give the request head one absolute budget measured from its first byte. The idle timeout resets on every read, so a peer that dribbled one byte at a time never tripped it; that reset now bounds only the wait for the first byte. - Give a body a no-progress budget instead of a total, so an upload on a slow link still finishes as long as it keeps moving. - Arm the read timeout immediately before each read, from the reader that is about to read. SO_RCVTIMEO belongs to the socket and the writer is a dup of it, so the value set once per request loop was overwritten by the next body read. - Grow the body buffer with the bytes that arrive rather than reserving the announced size before any of it has been sent, for both a declared length and a chunk. A short end-of-file is now an error instead of a silently truncated body. - Expose head_timeout_seconds (60) and body_stall_timeout_seconds (120) under [server], each floored at one second. --- docs/configuration.md | 6 +- docs/plans/cli-spec.md | 3 + src/config.rs | 55 ++++++++ src/server/http.rs | 313 +++++++++++++++++++++++++++++++++++------ src/server/mod.rs | 4 + 5 files changed, 340 insertions(+), 41 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 4eb40ea..b3abe22 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -31,6 +31,8 @@ max_connections = 256 max_body_bytes = 33554432 idle_timeout_seconds = 120 write_timeout_seconds = 600 +head_timeout_seconds = 60 +body_stall_timeout_seconds = 120 [update] repository = "eggstack/eggpass" @@ -60,8 +62,10 @@ default_provider = "xai" | `log_level` | `info` | `error`, `warn`, `info`, or `debug`. | | `allow_privileged_port` | `false` | Must be `true` to use a port below 1024. | | `timeouts.*` | See example | Upstream connection, whole-request, and response-body time limits in seconds. | -| `server.*` | See example | Local connection limit and idle/write timeouts. | +| `server.*` | See example | Local connection limit, idle/write timeouts, and request read deadlines. | | `server.max_body_bytes` | `33554432` | Largest request body in bytes, including inline base64 media. Clamped to 1–256 MiB; a larger body answers `413 body_too_large`. | +| `server.head_timeout_seconds` | `60` | Budget for the whole request head, counted from its first byte. A head that misses it is closed without a response. Clamped to at least 1. | +| `server.body_stall_timeout_seconds` | `120` | How long a body read may make no progress before the connection is closed. Resets with every read that arrives, so a slow upload that keeps sending still finishes. Clamped to at least 1. | | `providers.*.enabled` | `true` | Disable a provider without deleting its stored credentials. Routing to a disabled provider will not serve requests. | | `providers.xai.upstream` | `api` | `api` uses `https://api.x.ai/v1`; `build` uses `https://cli-chat-proxy.grok.com/v1`. | | `routing.default_provider` | `xai` | Provider used when no model prefix matches. | diff --git a/docs/plans/cli-spec.md b/docs/plans/cli-spec.md index abc49a9..b54c73d 100644 --- a/docs/plans/cli-spec.md +++ b/docs/plans/cli-spec.md @@ -865,6 +865,9 @@ body_seconds = 1800 # the ceiling on reading the response body max_connections = 256 # simultaneous connections; beyond it the server answers 503 idle_timeout_seconds = 120 # how long a kept-alive connection may sit idle write_timeout_seconds = 600 # how long a single write may stall +# The head budget is absolute; the body budget resets with every read. +head_timeout_seconds = 60 +body_stall_timeout_seconds = 120 [update] repository = "eggstack/eggpass" diff --git a/src/config.rs b/src/config.rs index cfede7c..900c6f4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -285,6 +285,10 @@ pub struct ServerLimits { pub idle_timeout_seconds: u64, /// How long a single write may stall, in seconds. pub write_timeout_seconds: u64, + /// How long the whole request head may take, from its first byte. + pub head_timeout_seconds: u64, + /// How long a body read may make no progress, in seconds. + pub body_stall_timeout_seconds: u64, } impl Default for ServerLimits { @@ -294,6 +298,8 @@ impl Default for ServerLimits { max_body_bytes: crate::server::http::DEFAULT_MAX_BODY_BYTES, idle_timeout_seconds: crate::server::http::DEFAULT_IDLE_TIMEOUT.as_secs(), write_timeout_seconds: crate::server::http::DEFAULT_WRITE_TIMEOUT.as_secs(), + head_timeout_seconds: crate::server::http::DEFAULT_HEAD_TIMEOUT.as_secs(), + body_stall_timeout_seconds: crate::server::http::DEFAULT_BODY_STALL_TIMEOUT.as_secs(), } } } @@ -428,6 +434,11 @@ max_connections = 256 max_body_bytes = 33554432 idle_timeout_seconds = 120 write_timeout_seconds = 600 +# The head budget is absolute, counted from the head's first byte. The body +# budget resets with every read that arrives, so a slow upload that keeps +# sending still finishes. +head_timeout_seconds = 60 +body_stall_timeout_seconds = 120 # Optional EggPool integration. `ca` is a file path, never PEM contents. # Do not store tokens, API keys, private keys, or certificate PEM in this file. @@ -578,6 +589,8 @@ struct RawServer { max_body_bytes: Option, idle_timeout_seconds: Option, write_timeout_seconds: Option, + head_timeout_seconds: Option, + body_stall_timeout_seconds: Option, } /// The raw shape of the `[providers]` tables. @@ -756,6 +769,14 @@ impl Config { if let Some(seconds) = server.write_timeout_seconds { config.server.write_timeout_seconds = seconds; } + // A zero budget would close a request the moment it arrived, so + // both are floored the way `max_connections` is. + if let Some(seconds) = server.head_timeout_seconds { + config.server.head_timeout_seconds = seconds.max(1); + } + if let Some(seconds) = server.body_stall_timeout_seconds { + config.server.body_stall_timeout_seconds = seconds.max(1); + } } if let Some(update) = raw.update { @@ -1524,6 +1545,40 @@ mod tests { ); } + #[test] + fn request_deadlines_parse_and_never_reach_zero() { + let config = Config::parse( + "[server]\nhead_timeout_seconds = 5\nbody_stall_timeout_seconds = 7\n", + Path::new("config.toml"), + ) + .unwrap(); + assert_eq!(config.server.head_timeout_seconds, 5); + assert_eq!(config.server.body_stall_timeout_seconds, 7); + + // A zero budget would close a request the moment its first byte + // arrived, so parsing floors it like `max_connections`. + let zeroed = Config::parse( + "[server]\nhead_timeout_seconds = 0\nbody_stall_timeout_seconds = 0\n", + Path::new("config.toml"), + ) + .unwrap(); + assert_eq!(zeroed.server.head_timeout_seconds, 1); + assert_eq!(zeroed.server.body_stall_timeout_seconds, 1); + } + + #[test] + fn the_default_template_sets_the_request_deadlines() { + let config = Config::parse(DEFAULT_CONFIG_TOML, Path::new("config.toml")).unwrap(); + assert_eq!( + config.server.head_timeout_seconds, + crate::server::http::DEFAULT_HEAD_TIMEOUT.as_secs() + ); + assert_eq!( + config.server.body_stall_timeout_seconds, + crate::server::http::DEFAULT_BODY_STALL_TIMEOUT.as_secs() + ); + } + #[test] fn eggpool_defaults_disabled() { let config = Config::parse("", Path::new("config.toml")).unwrap(); diff --git a/src/server/http.rs b/src/server/http.rs index 3d0067f..98b2e4c 100644 --- a/src/server/http.rs +++ b/src/server/http.rs @@ -43,6 +43,21 @@ pub const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(120); /// How long a single write may stall before the connection is dropped. pub const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(600); +/// How long the whole request head may take, measured from its first byte. +/// +/// The idle timeout cannot bound this: it resets on every read, so a peer +/// that keeps sending one byte at a time never trips it. +pub const DEFAULT_HEAD_TIMEOUT: Duration = Duration::from_secs(60); + +/// How long a body read may make no progress before the connection is dropped. +/// +/// This is a no-progress budget, not a total: a multi-megabyte upload on a slow +/// link legitimately takes longer than any fixed total while still progressing. +pub const DEFAULT_BODY_STALL_TIMEOUT: Duration = Duration::from_secs(120); + +/// The floor for a request deadline: zero would close every request on arrival. +const MIN_TIMEOUT: Duration = Duration::from_millis(1); + /// How many connections may be handled at once. pub const DEFAULT_MAX_CONNECTIONS: usize = 256; @@ -169,6 +184,10 @@ pub struct HttpServer { idle_timeout: Duration, /// How long a single write may stall. write_timeout: Duration, + /// How long the whole request head may take, from its first byte. + head_timeout: Duration, + /// How long a body read may make no progress. + body_stall_timeout: Duration, } impl HttpServer { @@ -182,6 +201,8 @@ impl HttpServer { max_body_bytes: DEFAULT_MAX_BODY_BYTES, idle_timeout: DEFAULT_IDLE_TIMEOUT, write_timeout: DEFAULT_WRITE_TIMEOUT, + head_timeout: DEFAULT_HEAD_TIMEOUT, + body_stall_timeout: DEFAULT_BODY_STALL_TIMEOUT, }) } @@ -204,6 +225,17 @@ impl HttpServer { self } + /// Set how long a request head and a stalled body may take. + /// + /// The head budget is absolute, measured from the head's first byte; the + /// body budget is a no-progress budget that resets on every read, so a + /// slow but steady upload still finishes. + pub fn with_request_timeouts(mut self, head: Duration, body_stall: Duration) -> HttpServer { + self.head_timeout = head.max(MIN_TIMEOUT); + self.body_stall_timeout = body_stall.max(MIN_TIMEOUT); + self + } + /// The address the server listens on. pub fn local_addr(&self) -> std::io::Result { self.listener.local_addr() @@ -249,18 +281,15 @@ impl HttpServer { let gate = Arc::clone(&gate); let handler = Arc::clone(&handler); let active = Arc::clone(&self.active); - let idle_timeout = self.idle_timeout; - let write_timeout = self.write_timeout; - let max_body_bytes = self.max_body_bytes; + let limits = ConnectionLimits { + max_body_bytes: self.max_body_bytes, + idle_timeout: self.idle_timeout, + write_timeout: self.write_timeout, + head_timeout: self.head_timeout, + body_stall_timeout: self.body_stall_timeout, + }; std::thread::spawn(move || { - let _ = handle_connection( - stream, - gate, - handler, - idle_timeout, - write_timeout, - max_body_bytes, - ); + let _ = handle_connection(stream, gate, handler, limits); // The count drops only now: the response body has been // written, so a stream that was cut short by a shutdown was // still counted as in flight. @@ -294,28 +323,40 @@ fn refuse(mut stream: TcpStream) -> std::io::Result<()> { Ok(()) } +/// The limits one connection is served within. +#[derive(Debug, Clone, Copy)] +struct ConnectionLimits { + /// The largest body accepted. + max_body_bytes: usize, + /// How long a kept-alive connection may sit idle before its first byte. + idle_timeout: Duration, + /// How long a single write may stall. + write_timeout: Duration, + /// How long the whole head may take, measured from its first byte. + head_timeout: Duration, + /// How long a body read may make no progress. + body_stall_timeout: Duration, +} + /// Handle one connection, serving requests until it is closed. fn handle_connection( stream: TcpStream, gate: Gate, handler: Handler, - idle_timeout: Duration, - write_timeout: Duration, - max_body_bytes: usize, + limits: ConnectionLimits, ) -> std::io::Result<()> { // Small responses should go out immediately. let _ = stream.set_nodelay(true); - let _ = stream.set_write_timeout(Some(write_timeout)); + let _ = stream.set_write_timeout(Some(limits.write_timeout)); - let mut reader = SocketReader::new(stream.try_clone()?); + let mut reader = SocketReader::new(stream.try_clone()?, limits.idle_timeout); let mut writer = stream; loop { - // A kept-alive connection may sit idle for a while; when it does, it - // is closed rather than holding a thread forever. - let _ = writer.set_read_timeout(Some(idle_timeout)); - - let request = match read_request(&mut reader, &mut writer, gate.as_ref(), max_body_bytes) { + // The reader arms its own budget before every read: `SO_RCVTIMEO` + // belongs to the socket, and the writer is a dup of it, so a value set + // here would be overwritten by the next body read anyway. + let request = match read_request(&mut reader, &mut writer, gate.as_ref(), &limits) { Ok(Some(request)) => request, Ok(None) => return Ok(()), Err(err) if is_idle_timeout(&err) => return Ok(()), @@ -348,19 +389,33 @@ struct SocketReader { stream: TcpStream, buffer: Vec, position: usize, + /// The read timeout applied before each read from the socket. + /// + /// `SO_RCVTIMEO` belongs to the socket rather than to this handle, and the + /// writer is a dup of the same socket. Arming it immediately before every + /// read is what keeps a head budget, a body stall budget, and the idle + /// timeout from overwriting each other. + read_timeout: Duration, } impl SocketReader { - fn new(stream: TcpStream) -> SocketReader { + fn new(stream: TcpStream, read_timeout: Duration) -> SocketReader { SocketReader { stream, buffer: Vec::new(), position: 0, + read_timeout, } } + /// Use this budget for the next read. + fn arm(&mut self, read_timeout: Duration) { + self.read_timeout = read_timeout; + } + /// Read more bytes into the buffer. Returns the number of new bytes. fn fill(&mut self) -> std::io::Result { + self.stream.set_read_timeout(Some(self.read_timeout))?; let mut chunk = [0u8; 8192]; let count = self.stream.read(&mut chunk)?; if count > 0 { @@ -483,9 +538,9 @@ fn read_request( reader: &mut SocketReader, writer: &mut TcpStream, gate: &dyn Fn(&Request) -> GateDecision, - max_body_bytes: usize, + limits: &ConnectionLimits, ) -> std::io::Result> { - let Some(head) = read_head(reader)? else { + let Some(head) = read_head(reader, limits)? else { return Ok(None); }; @@ -495,17 +550,17 @@ fn read_request( GateDecision::Refuse(refusal) => { write_response(writer, refusal, false)?; if !expects_continue(&request.headers) { - let _ = read_body(reader, writer, &request.headers, false, max_body_bytes); + let _ = read_body(reader, writer, &request.headers, false, limits); } return Ok(None); } GateDecision::Proceed { keep_body } => keep_body, }; - match read_body(reader, writer, &request.headers, keep_body, max_body_bytes) { + match read_body(reader, writer, &request.headers, keep_body, limits) { Ok(body) => Ok(Some(Request { body, ..request })), Err(BodyError::TooLarge) => { - write_response(writer, payload_too_large(max_body_bytes), false)?; + write_response(writer, payload_too_large(limits.max_body_bytes), false)?; Ok(None) } Err(BodyError::Malformed) => { @@ -573,7 +628,15 @@ fn payload_too_large(limit: usize) -> Response { } /// Read the request head, up to the blank line. -fn read_head(reader: &mut SocketReader) -> std::io::Result>> { +/// +/// The idle timeout bounds the wait for the first byte. Once a byte has +/// arrived, the head gets one absolute budget: the idle timeout alone resets on +/// every read, so a peer that keeps dribbling never trips it. +fn read_head( + reader: &mut SocketReader, + limits: &ConnectionLimits, +) -> std::io::Result>> { + let mut deadline: Option = None; loop { if let Some(index) = find_subslice(reader.pending(), b"\r\n\r\n") { let head = reader.pending()[..index + 4].to_vec(); @@ -592,6 +655,27 @@ fn read_head(reader: &mut SocketReader) -> std::io::Result>> { )); } + // The budget starts at the head's first byte. An idle keep-alive + // connection is still governed by the idle timeout, so a long-lived + // connection is not closed merely for sitting still. + if deadline.is_none() && !reader.pending().is_empty() { + deadline = Some(Instant::now() + limits.head_timeout); + } + let wait = match deadline { + Some(deadline) => { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(std::io::Error::new( + ErrorKind::TimedOut, + "the request head did not finish within its budget", + )); + } + remaining + } + None => limits.idle_timeout, + }; + reader.arm(wait); + if reader.fill()? == 0 { if reader.pending().is_empty() { return Ok(None); @@ -702,7 +786,7 @@ fn read_body( writer: &mut TcpStream, headers: &[(String, String)], keep: bool, - max_body_bytes: usize, + limits: &ConnectionLimits, ) -> Result, BodyError> { let framing = framing(headers)?; @@ -713,24 +797,47 @@ fn read_body( match framing { Framing::None => Ok(Vec::new()), - Framing::Chunked => read_chunked_body(reader, keep, max_body_bytes), + Framing::Chunked => { + reader.arm(limits.body_stall_timeout); + read_chunked_body(reader, keep, limits.max_body_bytes) + } Framing::Length(length) => { - if length > max_body_bytes { + if length > limits.max_body_bytes { return Err(BodyError::TooLarge); } + reader.arm(limits.body_stall_timeout); if !keep { discard(reader, length)?; return Ok(Vec::new()); } - let mut body = vec![0u8; length]; - reader.read_exact(&mut body)?; - Ok(body) + read_exact_incremental(reader, length) } } } +/// Read exactly `length` bytes, growing with the bytes that arrive. +/// +/// A declared length is not a reason to reserve that much before any of it has +/// been sent, so the buffer follows the received bytes rather than the +/// announcement. `read_to_end` reports success at a short end-of-file, so the +/// length is checked rather than assumed. +fn read_exact_incremental(reader: &mut SocketReader, length: usize) -> Result, BodyError> { + let mut bytes = Vec::with_capacity(length.min(64 * 1024)); + reader + .by_ref() + .take(length as u64) + .read_to_end(&mut bytes)?; + if bytes.len() != length { + return Err(BodyError::from(std::io::Error::new( + ErrorKind::UnexpectedEof, + "the request body ended before its declared length", + ))); + } + Ok(bytes) +} + /// Read and throw away exactly `length` bytes. fn discard(reader: &mut SocketReader, length: usize) -> std::io::Result<()> { let mut buffer = [0u8; 8192]; @@ -779,9 +886,17 @@ fn read_chunked_body( } if keep { - let mut chunk = vec![0u8; size]; - reader.read_exact(&mut chunk)?; - body.extend_from_slice(&chunk); + // Append from the socket rather than reserving the declared size: + // a chunk header is a claim, and the bytes may never arrive. + let before = body.len(); + reader.by_ref().take(size as u64).read_to_end(&mut body)?; + if body.len() - before != size { + return Err(std::io::Error::new( + ErrorKind::UnexpectedEof, + "a chunk ended before its declared size", + ) + .into()); + } } else { discard(reader, size)?; } @@ -955,16 +1070,28 @@ mod tests { assert!(body.contains("body_too_large"), "{body}"); } + /// Limits for a unit test that only cares about one of them. + fn test_limits(max_body_bytes: usize) -> ConnectionLimits { + ConnectionLimits { + max_body_bytes, + idle_timeout: Duration::from_secs(5), + write_timeout: Duration::from_secs(5), + head_timeout: Duration::from_secs(5), + body_stall_timeout: Duration::from_secs(5), + } + } + #[test] fn content_length_checks_use_the_configured_limit() { let (mut writer, server) = tcp_pair(); - let mut reader = SocketReader::new(server); + let limits = test_limits(8); + let mut reader = SocketReader::new(server, Duration::from_secs(5)); let error = read_body( &mut reader, &mut writer, &[("content-length".to_string(), "9".to_string())], true, - 8, + &limits, ) .unwrap_err(); assert!(matches!(error, BodyError::TooLarge)); @@ -1039,7 +1166,7 @@ mod tests { fn chunked_checks_use_the_configured_limit() { let (mut client, server) = tcp_pair(); client.write_all(b"9\r\n").unwrap(); - let mut reader = SocketReader::new(server); + let mut reader = SocketReader::new(server, Duration::from_secs(5)); let error = read_chunked_body(&mut reader, true, 8).unwrap_err(); assert!(matches!(error, BodyError::TooLarge)); } @@ -1348,6 +1475,112 @@ mod integration_tests { assert_eq!(probe_health(port), 200); } + /// Start a server with explicit request deadlines. + fn start_with_timeouts(handler: Handler, head: Duration, body_stall: Duration) -> u16 { + let gate: Gate = Arc::new(|_: &Request| GateDecision::Proceed { keep_body: true }); + let server = Arc::new( + HttpServer::bind("127.0.0.1:0") + .unwrap() + .with_request_timeouts(head, body_stall), + ); + let port = server.local_addr().unwrap().port(); + let shutdown = Arc::new(AtomicBool::new(false)); + let running = Arc::clone(&server); + std::thread::spawn(move || running.serve(shutdown, gate, handler)); + std::thread::sleep(Duration::from_millis(50)); + port + } + + #[test] + fn a_stalled_head_is_closed_at_the_head_deadline() { + let port = start_with_timeouts( + Arc::new(|_: Request| Response::json(200, "{}")), + Duration::from_millis(150), + Duration::from_secs(5), + ); + + let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + // A request line and one header, then silence: the head never reaches + // its blank line, and no single read blocks long enough for the idle + // timeout to be what closes it. + write!(stream, "GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\n").unwrap(); + + let mut response = String::new(); + stream + .read_to_string(&mut response) + .expect("the server closes a stalled head"); + assert!( + response.is_empty(), + "a stalled head must not be answered: {response}" + ); + } + + #[test] + fn a_stalled_body_is_closed_at_the_stall_deadline() { + let port = start_with_timeouts( + Arc::new(|_: Request| Response::json(200, "{}")), + Duration::from_secs(5), + Duration::from_millis(150), + ); + + let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + write!( + stream, + "POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 10\r\n\r\nX" + ) + .unwrap(); + + let mut response = String::new(); + stream + .read_to_string(&mut response) + .expect("the server closes a stalled body"); + assert!( + response.is_empty(), + "a stalled body must not be answered: {response}" + ); + } + + #[test] + fn a_slow_but_progressing_body_is_accepted() { + // The head budget is far shorter than the body takes in total: only a + // no-progress budget lets this through. A total body deadline would + // fail here, which is why there is not one. + let port = start_with_timeouts( + Arc::new(|request: Request| { + Response::json(200, format!("{{\"len\":{}}}", request.body.len())) + }), + Duration::from_millis(100), + Duration::from_millis(400), + ); + + let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + write!( + stream, + "POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Length: 12\r\n\r\n" + ) + .unwrap(); + // Six writes 150 ms apart: 900 ms in total, nine times the head + // budget, with no gap longer than the 400 ms body budget. + for _ in 0..6 { + std::thread::sleep(Duration::from_millis(150)); + stream.write_all(b"ab").unwrap(); + stream.flush().unwrap(); + } + + let response = read_response(&mut stream); + assert!(response.starts_with("HTTP/1.1 200"), "{response}"); + assert!(response.contains("\"len\":12"), "{response}"); + } + #[test] fn a_short_chunked_body_still_arrives() { let port = start(Arc::new(|request: Request| { diff --git a/src/server/mod.rs b/src/server/mod.rs index d87eea2..dd9d256 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -194,6 +194,10 @@ impl Server { Duration::from_secs(limits.idle_timeout_seconds), Duration::from_secs(limits.write_timeout_seconds), ) + .with_request_timeouts( + Duration::from_secs(limits.head_timeout_seconds), + Duration::from_secs(limits.body_stall_timeout_seconds), + ) .with_max_body_bytes(limits.max_body_bytes); Ok(Arc::new(Server { From d6c38417e474d4e498d79d68573cec2207e618ce Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 16:59:48 +0000 Subject: [PATCH 03/10] docs: state the key requirement the code enforces - Describe the config's api_key field and the endpoint's authentication as the code implements them. With neither an issued key nor a config key the server refuses every request with `401 no_api_key` and `eggpass run` will not start, and revoking the last key closes the endpoint instead of reopening it. - Leave the shipped plans that describe the old open state as they were written: they are a record of what was decided then, not a claim about this build. --- docs/plans/cli-spec.md | 10 +++++----- src/config.rs | 5 ++++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/plans/cli-spec.md b/docs/plans/cli-spec.md index b54c73d..bd2bcda 100644 --- a/docs/plans/cli-spec.md +++ b/docs/plans/cli-spec.md @@ -614,11 +614,11 @@ eggpass key revoke --all # revoke every key whenever the file changes underneath it, so `add` and `revoke` need no restart. The store has exactly one writer — this command — so the file is never contended. -7. **Authentication is required when there is a key.** While the store is empty - and the config's `api_key` is empty, the endpoint accepts anything, which is - the safe default for a loopback socket. The moment a key exists, a key is - required. Revoking the last one puts the endpoint back to open, and the - command says so. +7. **Authentication is required, and there is no open state.** A server with + neither an issued key nor a config `api_key` refuses every request with + `401 no_api_key`, and `eggpass run` will not start in that state. The moment + a key exists, a key is required. Revoking the last one closes the endpoint + again rather than opening it, and the command says so. 8. **The config's `api_key` still works.** It is the older, hand-written way to set one key, and it is accepted alongside the issued ones. It is not removed, because a configuration file that suddenly stops parsing is worse diff --git a/src/config.rs b/src/config.rs index 900c6f4..cc9d047 100644 --- a/src/config.rs +++ b/src/config.rs @@ -350,7 +350,10 @@ pub struct Config { /// Which upstream serves requests. Kept for the single-provider layout; /// `providers.xai.upstream` is the authority when it is set. pub upstream: Upstream, - /// Key clients must present. Empty means "accept anything". + /// Key clients must present. It is accepted alongside issued keys. + /// + /// When this is empty and the key store is empty, the server refuses every + /// request rather than accepting anything, and `eggpass run` will not start. pub api_key: String, /// Log verbosity. pub log_level: LogLevel, From 882abeb4e7a2cd7764620a4a9b731b5660408d27 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 17:00:02 +0000 Subject: [PATCH 04/10] ci: pin publish actions to commit SHAs - Resolve every third-party action in the three publish workflows to the commit its tag pointed at on 2026-11-30 and pin that SHA. A tag can be moved or retargeted, so a release could otherwise run different code than the one that was reviewed. - The pins cover actions/checkout, actions/setup-python, actions/upload-artifact, actions/download-artifact, Swatinem/rust-cache, PyO3/maturin-action and pypa/gh-action-pypi-publish: 18 references across the crates, auth and auth-pypi workflows. The CI and release workflows are unchanged. --- .github/workflows/publish-crates.yml | 4 +-- .../workflows/publish-eggpass-auth-pypi.yml | 28 +++++++++---------- .github/workflows/publish-eggpass-auth.yml | 4 +-- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.github/workflows/publish-crates.yml b/.github/workflows/publish-crates.yml index 166aa78..9c1b4b1 100644 --- a/.github/workflows/publish-crates.yml +++ b/.github/workflows/publish-crates.yml @@ -30,7 +30,7 @@ jobs: name: publish runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: # The crate that ships is the crate the release was cut from. ref: ${{ github.event.release.tag_name || github.ref }} @@ -40,7 +40,7 @@ jobs: rustup toolchain install stable --profile minimal --no-self-update rustup default stable - - uses: Swatinem/rust-cache@v2 + - uses: "Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0" - name: Check the version matches the release if: ${{ github.event_name == 'release' }} diff --git a/.github/workflows/publish-eggpass-auth-pypi.yml b/.github/workflows/publish-eggpass-auth-pypi.yml index 2910e06..3d22008 100644 --- a/.github/workflows/publish-eggpass-auth-pypi.yml +++ b/.github/workflows/publish-eggpass-auth-pypi.yml @@ -26,11 +26,11 @@ jobs: outputs: version: ${{ steps.version.outputs.value }} steps: - - uses: actions/checkout@v4 + - uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: ref: ${{ github.event.release.tag_name || github.ref }} - - uses: actions/setup-python@v6 + - uses: "actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1" with: python-version: "3.11" @@ -104,11 +104,11 @@ jobs: manylinux: "off" interpreter: python steps: - - uses: actions/checkout@v4 + - uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: ref: ${{ github.event.release.tag_name || github.ref }} - - uses: actions/setup-python@v6 + - uses: "actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1" with: python-version: "3.11" @@ -117,7 +117,7 @@ jobs: working-directory: python/eggpass-auth - name: Build stable-ABI wheel - uses: PyO3/maturin-action@v1 + uses: "PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b" with: maturin-version: v1.16.0 manylinux: ${{ matrix.platform.manylinux }} @@ -126,7 +126,7 @@ jobs: --out dist working-directory: python/eggpass-auth - - uses: actions/upload-artifact@v4 + - uses: "actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02" with: name: python-dist-${{ matrix.platform.name }} path: python/eggpass-auth/dist/*.whl @@ -138,11 +138,11 @@ jobs: needs: verify-source runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v4 + - uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: ref: ${{ github.event.release.tag_name || github.ref }} - - uses: actions/setup-python@v6 + - uses: "actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1" with: python-version: "3.11" @@ -162,7 +162,7 @@ jobs: run: maturin sdist --out dist working-directory: python/eggpass-auth - - uses: actions/upload-artifact@v4 + - uses: "actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02" with: name: python-dist-sdist path: python/eggpass-auth/dist/*.tar.gz @@ -174,11 +174,11 @@ jobs: needs: [verify-source, build-wheels, build-sdist] runs-on: ubuntu-24.04 steps: - - uses: actions/setup-python@v6 + - uses: "actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1" with: python-version: "3.11" - - uses: actions/download-artifact@v4 + - uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: pattern: python-dist-* path: dist @@ -295,7 +295,7 @@ jobs: print(f"Validated {len(wheels)} wheels and {sdist.name}") PY - - uses: actions/upload-artifact@v4 + - uses: "actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02" with: name: verified-distributions path: dist/* @@ -315,12 +315,12 @@ jobs: permissions: id-token: write steps: - - uses: actions/download-artifact@v4 + - uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: name: verified-distributions path: dist - name: Publish with PyPI Trusted Publishing - uses: pypa/gh-action-pypi-publish@release/v1 + uses: "pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086" with: packages-dir: dist diff --git a/.github/workflows/publish-eggpass-auth.yml b/.github/workflows/publish-eggpass-auth.yml index c027fdd..e6b9f56 100644 --- a/.github/workflows/publish-eggpass-auth.yml +++ b/.github/workflows/publish-eggpass-auth.yml @@ -27,7 +27,7 @@ jobs: name: publish runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: # Build the exact source associated with a published auth release. ref: ${{ github.event.release.tag_name || github.ref }} @@ -37,7 +37,7 @@ jobs: rustup toolchain install stable --profile minimal --no-self-update rustup default stable - - uses: Swatinem/rust-cache@v2 + - uses: "Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0" - name: Check the version matches the release tag env: From 3c56070b77ac622f2d346cf1df74330c6feb601f Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 17:00:43 +0000 Subject: [PATCH 05/10] cli: accept editor arguments in EDITOR and VISUAL - Split the EDITOR/VISUAL value into a program and its own arguments instead of passing the whole string as one executable path, which made the common `code --wait` and `vim -f` forms fail to launch. - Keep a backslash that escapes nothing as written, so a Windows path survives, and treat an unbalanced quote as an error naming the variable and its value rather than silently falling back to another editor. --- docs/commands.md | 2 +- src/cli/commands/edit.rs | 187 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 174 insertions(+), 15 deletions(-) diff --git a/docs/commands.md b/docs/commands.md index 04f2393..6d68901 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -172,7 +172,7 @@ The config file's `api_key`, if set, remains accepted alongside issued keys. Rev eggpass edit ``` -Opens the config in `$EDITOR`, then `$VISUAL`, then `helix`, `vim`, or `nano`, falling back to `vi`. The config is validated after the editor exits. +Opens the config in `$EDITOR`, then `$VISUAL`, then `helix`, `vim`, or `nano`, falling back to `vi`. A value may carry arguments — `EDITOR="code -w"` — which are split from the program and never run through a shell; an unbalanced quote is reported instead of being skipped. The config is validated after the editor exits. **Exit code:** `0` if the edited config is valid, `1` if the editor fails or validation fails. diff --git a/src/cli/commands/edit.rs b/src/cli/commands/edit.rs index 5cac4d3..212ef26 100644 --- a/src/cli/commands/edit.rs +++ b/src/cli/commands/edit.rs @@ -8,22 +8,26 @@ use crate::config; /// Open the configuration file in the user's editor. /// /// The editor is `$EDITOR`, then `$VISUAL`, then the first of `helix`, -/// `vim` and `nano` that is installed. When the editor exits the file is -/// validated; a syntax error is reported without touching the file. +/// `vim` and `nano` that is installed. A value may carry arguments +/// (`EDITOR="code -w"`); it is split into a program and its arguments and is +/// never handed to a shell. When the editor exits the file is validated; a +/// syntax error is reported without touching the file. pub fn edit(context: &Context) -> Result<(), CommandError> { let path = context.paths.config_file().to_path_buf(); config::ensure_config_file(&path).map_err(|err| CommandError::new(err.to_string()))?; - let editor = pick_editor(); + let editor = pick_editor()?; - let status = Command::new(&editor) + let status = Command::new(&editor.program) + .args(&editor.arguments) .arg(&path) .status() - .map_err(|err| CommandError::new(format!("could not run `{editor}`: {err}")))?; + .map_err(|err| CommandError::new(format!("could not run `{}`: {err}", editor.label)))?; if !status.success() { return Err(CommandError::new(format!( - "`{editor}` exited with {status}; the configuration was left unchanged" + "`{}` exited with {status}; the configuration was left unchanged", + editor.label ))); } @@ -38,24 +42,134 @@ pub fn edit(context: &Context) -> Result<(), CommandError> { } } +/// The editor to run: a program, its arguments, and the value it came from. +struct Editor { + /// The value as written, so a message can quote what the user set. + label: String, + /// The program to run. + program: String, + /// The arguments to pass before the configuration path. + arguments: Vec, +} + /// Choose the editor to use. -fn pick_editor() -> String { +/// +/// `$EDITOR` and `$VISUAL` may carry arguments — `code -w`, `vim -u NONE` — so +/// a value is split into a program and its arguments. An unbalanced quote is +/// reported rather than silently skipped: falling through to `vi` would launch +/// the wrong editor and hide the typo. +fn pick_editor() -> Result { for variable in ["EDITOR", "VISUAL"] { - if let Ok(value) = std::env::var(variable) { - let value = value.trim(); - if !value.is_empty() { - return value.to_string(); - } + let Ok(value) = std::env::var(variable) else { + continue; + }; + let value = value.trim().to_string(); + if value.is_empty() { + continue; } + let parts = split_editor_command(&value).map_err(|reason| { + CommandError::new(format!("{variable} is not usable: {reason}: `{value}`")) + })?; + let Some((program, arguments)) = parts.split_first() else { + continue; + }; + return Ok(Editor { + label: value, + program: program.clone(), + arguments: arguments.to_vec(), + }); } for candidate in ["helix", "vim", "nano"] { if is_installed(candidate) { - return candidate.to_string(); + return Ok(Editor { + label: candidate.to_string(), + program: candidate.to_string(), + arguments: Vec::new(), + }); + } + } + + Ok(Editor { + label: "vi".to_string(), + program: "vi".to_string(), + arguments: Vec::new(), + }) +} + +/// Split an `$EDITOR` value into a program and its arguments. +/// +/// Whitespace separates words; single and double quotes group and are removed. +/// A backslash escapes only a quote, a backslash, or whitespace, and is +/// otherwise an ordinary character, so `C:\tools\ed.exe` survives intact. No +/// shell is involved, so variables, globs, and pipes do not expand. +fn split_editor_command(value: &str) -> Result, &'static str> { + let mut parts = Vec::new(); + let mut word = String::new(); + let mut started = false; + let mut quote: Option = None; + let mut characters = value.chars(); + + while let Some(character) = characters.next() { + match quote { + Some(delimiter) => { + if character == delimiter { + quote = None; + } else if character == '\\' { + push_escaped(&mut word, characters.next()); + } else { + word.push(character); + } + } + None => match character { + '"' | '\'' => { + quote = Some(character); + started = true; + } + '\\' => { + started = true; + push_escaped(&mut word, characters.next()); + } + character if character.is_whitespace() => { + if started { + parts.push(std::mem::take(&mut word)); + started = false; + } + } + character => { + started = true; + word.push(character); + } + }, } } - "vi".to_string() + if quote.is_some() { + return Err("an unbalanced quote"); + } + if started { + parts.push(word); + } + Ok(parts) +} + +/// Append an escaped character, keeping the backslash when it escapes nothing. +fn push_escaped(word: &mut String, next: Option) { + match next { + Some(character) + if character == '"' + || character == '\'' + || character == '\\' + || character.is_whitespace() => + { + word.push(character); + } + Some(character) => { + word.push('\\'); + word.push(character); + } + None => word.push('\\'), + } } /// Whether a program is on the `PATH`. @@ -70,3 +184,48 @@ fn is_installed(program: &str) -> bool { candidate.is_file() }) } + +#[cfg(test)] +mod tests { + use super::split_editor_command; + + fn split(value: &str) -> Vec { + split_editor_command(value).expect("the value splits") + } + + #[test] + fn an_editor_value_splits_into_a_program_and_arguments() { + assert_eq!(split("vim -u NONE"), ["vim", "-u", "NONE"]); + assert_eq!(split("code -w"), ["code", "-w"]); + assert_eq!( + split(r#""path with spaces/ed" -f"#), + ["path with spaces/ed", "-f"] + ); + } + + #[test] + fn backslashes_that_escape_nothing_are_kept() { + // `\t` and `\e` are not escapes here; treating them as escapes + // would mangle a Windows path into something that cannot launch. + assert_eq!(split(r#"C:\tools\ed.exe"#), [r#"C:\tools\ed.exe"#]); + assert_eq!( + split(r#""C:\Program Files\ed\ed.exe""#), + [r#"C:\Program Files\ed\ed.exe"#] + ); + // The escapes that are defined still work. + assert_eq!(split(r#""a\"b""#), ["a\"b"]); + assert_eq!(split(r"one\ two"), ["one two"]); + } + + #[test] + fn an_unbalanced_quote_is_an_error_rather_than_a_fallback() { + let error = split_editor_command(r#""unbalanced"#).unwrap_err(); + assert!(error.contains("quote"), "{error}"); + } + + #[test] + fn a_blank_value_splits_to_nothing() { + assert!(split(" ").is_empty()); + assert!(split("").is_empty()); + } +} From acf7ab90f8d4c5632c1f18096424dbc689ae7dfb Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 17:09:25 +0000 Subject: [PATCH 06/10] chore: add security-review-2026-11-30-implementation.md - Record the review's accepted findings and the corrective plan for each, so the reasoning behind the five stage commits sits in the history next to them. - Include what was reviewed and deliberately left alone, the measured test counts per commit, and the tag-to-commit pins resolved for the three publish workflows. --- ...curity-review-2026-11-30-implementation.md | 419 ++++++++++++++++++ 1 file changed, 419 insertions(+) create mode 100644 plans/security-review-2026-11-30-implementation.md diff --git a/plans/security-review-2026-11-30-implementation.md b/plans/security-review-2026-11-30-implementation.md new file mode 100644 index 0000000..6c6b9c9 --- /dev/null +++ b/plans/security-review-2026-11-30-implementation.md @@ -0,0 +1,419 @@ +# Security and Code-Quality Review — Corrective Implementation Plan + +**Status:** Implemented and committed on `fix/pypi-classifiers-0.1.1` as five +commits in the order below, each one verified to build and pass on its own: +`d5fbc62` (F1), `d051c21` (F4), `d6c3841` (F3), `882abeb` (F2), `3c56070` (F5). +Nothing is pushed, published or released. Reviewed revision: `2c87b85` on +`fix/pypi-classifiers-0.1.1`, an ancestor of `origin/main` at `7d015db`. + +**Basis:** Read-only review of the security-relevant surfaces — credential and +token storage, HTTP parsing, upstream forwarding, the key store, configuration, +self-update, the installer, and CI — plus a sweep of every production +`unwrap`/`expect`/`panic!` site. Five findings were accepted: one medium, +one low-medium, two low, and one minor. No critical defect was found; the +credential store, key store, request gate, header stripping, PKCE flow, EggPool +contract, and self-update path all passed inspection. Line numbers refer to +`2c87b85` and may move. + +**Why one plan:** all five findings come from one review and share a reference +set. The stages are independent except that F1 and F4 both touch +`read_body`/`handle_connection` and must be done in that order. + +## Goal + +Close the five findings with the smallest change that removes each defect, +without altering behavior that passed the review, adding a dependency, or +touching a provider integration. F1 and F4 are server behavior; F2 is CI +hardening; F3 is documentation that contradicts the code; F5 is a CLI launch +bug. Every measure is local and testable offline: no live probe, no provider +login, no release, no publish, no commit. + +## Findings addressed + +| # | Severity | Finding | Evidence | Effect | +| --- | --- | --- | --- | --- | +| F1 | Medium | HTTP message framing is never validated: an unparseable `Content-Length` yields an empty body without consuming bytes, duplicate `Content-Length` headers take the first, and `Content-Length` beside `Transfer-Encoding: chunked` is accepted | `src/server/http.rs:629-634` (`lookup` is `.find()`), `:641-645` (TE wins, CL not rejected), `:647-650` (parse failure returns `Ok(Vec::new())`), `:313-330` (keep-alive loop) | Unread body bytes are parsed as the next request head on the same connection. Not an auth bypass — the next request is authorized from its own headers — but eggpass and a front end can disagree about message boundaries. Highest exposure behind a reverse proxy on a non-loopback bind. | +| F2 | Low–Medium | Publish workflows hold credentials while referencing actions by mutable tag | `.github/workflows/publish-crates.yml:33,43,65`; `publish-eggpass-auth.yml:30,40,66`; `publish-eggpass-auth-pypi.yml:120,324` with job-level `id-token: write` at `:315-316`; contrast `release.yml:31` and `ci.yml:65`, which pin full SHAs | Whoever controls a tag runs code with `CARGO_REGISTRY_TOKEN` or the PyPI OIDC identity. Mutable-tag exposure, not evidence of compromise. | +| F3 | Low (doc) | The `api_key` field doc says an empty value accepts anything; the code refuses everything when no key source is configured | `src/config.rs:347` against `src/server/mod.rs:509-527` and `:405-413`; the same stale model survives in `docs/plans/cli-spec.md:618-621` | An operator reasoning from the contract builds the wrong model of exposure: the code is stricter than documented, and `cli-spec` says revoking the last key reopens the endpoint, which is the opposite of `src/cli/commands/key.rs:108-118`. | +| F4 | Low | No whole-request deadline and a single global connection cap; the body buffer is allocated from the declared length | `src/server/http.rs:40-41` (120 s per read), `:47` (256 connections), `:316` (`set_read_timeout`), `:661` (`vec![0u8; length]`) after the gate at `:494-509` | A peer dribbling a head holds a thread indefinitely; 256 such connections stall the listener. The default loopback bind and the post-head key check limit exposure, and only authenticated clients reach the allocation. | +| F5 | Minor | `$EDITOR`/`$VISUAL` values containing arguments fail to launch | `src/cli/commands/edit.rs:19-21` (`Command::new`), `:42-48` (verbatim value); contract at `docs/commands.md:175` | `EDITOR="vim -u NONE"` or `EDITOR="code -w"` fails with ENOENT. Not an injection risk: no shell is involved. | + +## Stages + +### Stage F1 — Reject ambiguous framing instead of guessing + +Replace the ad-hoc header lookups in `read_body` (`src/server/http.rs:622-664`) +with one framing decision taken before any body byte is read or allocated. + +Decisions taken (do not re-litigate during implementation): + +- Duplicate `Content-Length` values that are **equal** are accepted; any + difference is refused. RFC 9112 §6.3 permits either rejecting all duplicates + or accepting an equal set; equal duplicates occur in the wild from header + rewriting, and refusing them would break clients that are otherwise correct. +- `Content-Length` must be all ASCII digits. `str::parse::` also accepts + a leading `+`, which is not valid `Content-Length` syntax and may be framed + differently by a proxy, so it is refused with the other unparseable values. +- `Transfer-Encoding` and `Content-Length` together are refused rather than + resolved. The server cannot know which framing a proxy in front of it used. +- `Transfer-Encoding` header lines are combined in order (RFC 9112 §6.1), then + the coding list is parsed; the only accepted list is exactly `chunked`. The + current `contains("chunked")` also matches `xchunked` and `gzip, chunked`. +- A framing refusal reuses the existing `400` body and code + (`malformed_body()`, `http.rs:557-562`) and closes the connection through the + existing `BodyError::Malformed` arm (`http.rs:511-514`). No new error code is + introduced in this stage. + +Framing table to implement as a private `fn framing(headers: &[(String, String)])` +returning a small enum (`None`, `Length(usize)`, `Chunked`) or +`BodyError::Malformed`: + +| Headers present | Result | +| --- | --- | +| neither | empty body, as today | +| one or more equal `Content-Length`, all digits, within `max_body_bytes` | `Length(n)` | +| duplicate `Content-Length` with any difference | `400`, close | +| `Content-Length` that is not all ASCII digits (empty, `abc`, `-1`, `+5`, `5 5`, overflow) | `400`, close | +| `Transfer-Encoding` whose combined coding list is exactly `chunked` | `Chunked` | +| any other coding list, including `gzip, chunked`, `chunked, gzip`, `xchunked`, an empty list | `400`, close | +| `Transfer-Encoding` with any `Content-Length` | `400`, close | + +Steps: + +- Add `fn all_values<'a>(headers: &'a [(String, String)], name: &str) -> Vec<&'a str>` + beside the current `lookup` closure and use it for both `Content-Length` and + `Transfer-Encoding`; keep `lookup` for `Expect`. +- Check the length against `max_body_bytes` before reading, as today, so the + `413` path is unchanged. +- Leave `read_chunked_body` (`http.rs:679-724`) as it is; it already consumes the + trailer section and bounds each chunk. + +Tests: + +- `framing_decisions_are_table_driven` — one case per row above plus the two + duplicate-equal and duplicate-conflicting cases. Direct unit test of + `framing`, in the `mod tests` at `http.rs:855`. +- `a_malformed_content_length_cannot_prefix_the_next_request` — socket-level: + open the server with a configured key, write a `POST` with + `Content-Length: abc` immediately followed by a complete second request in the + same write, and assert exactly one response (`400`, `malformed_body`) followed + by EOF. **The request must pass the gate**, so this test needs a key; through + an unauthenticated endpoint the connection would close regardless and the test + would pass for the wrong reason. +- `a_conflicting_content_length_is_refused` and + `content_length_alongside_chunked_is_refused` — the same shape, one header + variance each. +- Keep `keep_alive_connections_serve_more_than_one_request` + (`src/server/tests.rs:1298`), the chunked tests, and the `413` test green. + +**Exit:** every ambiguous shape above answers `400` and closes without +consuming a body; a well-formed `Content-Length` or `chunked` request is +unaffected; the two-requests-on-one-connection case still works when both are +well formed. Do not touch the gate, the body cap, or `read_chunked_body`. + +### Stage F2 — Pin the actions that can reach a publish credential + +Resolve each tag to its current commit and replace the tag reference with the +full 40-character SHA, matching `release.yml`'s style. Record the resolution +date and the tag-to-SHA mapping in this section when the work is done, so a +reviewer can audit the pins without leaving the repository. + +| Workflow | Reference | Why it matters | +| --- | --- | --- | +| `publish-crates.yml:33` | `actions/checkout@v4` | runs before `cargo publish` | +| `publish-crates.yml:43` | `Swatinem/rust-cache@v2` | runs in the same job as the token | +| `publish-eggpass-auth.yml:30` | `actions/checkout@v4` | crate publish job | +| `publish-eggpass-auth.yml:40` | `Swatinem/rust-cache@v2` | same job as `CARGO_REGISTRY_TOKEN` (`:66`) | +| `publish-eggpass-auth-pypi.yml:29,107,141` | `actions/checkout@v4` | build matrix | +| `publish-eggpass-auth-pypi.yml:33,111,145,177` | `actions/setup-python@v6` | build matrix | +| `publish-eggpass-auth-pypi.yml:120` | `PyO3/maturin-action@v1` | builds the wheels | +| `publish-eggpass-auth-pypi.yml:129,165,298` | `actions/upload-artifact@v4` | artifact handoff into the publish job | +| `publish-eggpass-auth-pypi.yml:181,318` | `actions/download-artifact@v4` | artifact handoff into the publish job | +| `publish-eggpass-auth-pypi.yml:324` | `pypa/gh-action-pypi-publish@release/v1` | receives the OIDC token from `:315-316` | + +Resolution (run at implementation time, record the output): + +```sh +gh api repos/actions/checkout/commits/v4 --jq .sha +gh api repos/actions/setup-python/commits/v6 --jq .sha +gh api repos/actions/upload-artifact/commits/v4 --jq .sha +gh api repos/actions/download-artifact/commits/v4 --jq .sha +gh api repos/Swatinem/rust-cache/commits/v2 --jq .sha +gh api repos/PyO3/maturin-action/commits/v1 --jq .sha +gh api repos/pypa/gh-action-pypi-publish/commits/release/v1 --jq .sha +``` + +Resolved 2026-11-30 against the GitHub API; every reference below is pinned in +the working tree. + +| Reference | Commit | +| --- | --- | +| `actions/checkout@v4` | `11d5960a326750d5838078e36cf38b85af677262` | +| `actions/setup-python@v6` | `ece7cb06caefa5fff74198d8649806c4678c61a1` | +| `actions/upload-artifact@v4` | `ea165f8d65b6e75b540449e92b4886f43607fa02` | +| `actions/download-artifact@v4` | `d3f86a106a0bac45b974a628896c90dbdf5c8093` | +| `Swatinem/rust-cache@v2` | `d1527c8f67ef9af357290475d4af4b0fab8f12e0` | +| `PyO3/maturin-action@v1` | `e83996d129638aa358a18fbd1dfb82f0b0fb5d3b` | +| `pypa/gh-action-pypi-publish@release/v1` | `7245906fb61fa33a13554f9d5fb856fe61758086` | + +Three of these already appear in `release.yml` — `actions/checkout`, +`actions/upload-artifact`, and `actions/download-artifact` — which is the +consistency check that the pins are the same commits that workflow already +trusts. 18 references were pinned in total: 2 in `publish-crates.yml`, 2 in +`publish-eggpass-auth.yml`, and 14 in `publish-eggpass-auth-pypi.yml`. +`actionlint` passes on all three. + +Notes: + +- Pin every occurrence, not just the first in each file; a partially pinned file + is the failure mode this stage exists to prevent. +- `ci.yml` and `python-auth.yml` also float tags but hold no publish credential. + Pinning them is optional consistency work, not part of this stage's exit. +- Do not add a dependency bot in this stage; if pin maintenance is wanted, that + is a separate decision. + +**Exit:** `grep -n 'uses:' .github/workflows/*.yml` shows a full SHA for every +reference in the three files above, no `@v\d` remains in them, and each workflow +still parses as YAML. If `actionlint` is installed, it passes; otherwise parse +with `python3 -c 'import sys,yaml; [yaml.safe_load(open(p)) for p in sys.argv[1:]]' .github/workflows/*.yml`. +Optional end-to-end check: dispatch `publish-crates.yml` with `dry_run=true`, +which runs `cargo package` without the token being used to publish. + +### Stage F3 — Make the key documentation match the enforced rule + +Two locations carry the stale model; a third carries it only as history. + +- `src/config.rs:347` — replace + `/// Key clients must present. Empty means "accept anything".` with a + statement of the enforced rule: the static key is accepted alongside issued + keys; when both are absent the server refuses every request and `eggpass run` + will not start. Name the three presentment forms (`Authorization: Bearer`, + `X-Api-Key`, and the `key` query parameter) only if the surrounding comment + can stay short; the field is documented in `docs/configuration.md:59,83`. +- `docs/plans/cli-spec.md:617-621` — point 7 currently claims the endpoint + "accepts anything" while the store and config key are empty, calls that "the + safe default for a loopback socket", and says revoking the last key "puts the + endpoint back to open". All three clauses are wrong: `keys_configured` is + `!api_key.is_empty() || !keys.is_empty()`; `is_authorized` returns `false` + when nothing is configured, the gate answers `401 no_api_key`, and the CLI prints + "Every request is now refused" (`src/cli/commands/key.rs:108-118`). Rewrite the + point to state that a server with no key source refuses everything, that + revoking the last issued key closes it, and that the command says so. +- Leave `docs/plans/research.md:526` and + `docs/plans/shipped-2026-11-13.md:282,550` alone: `docs/plans/README.md` + already marks them as historical, and rewriting a record of what was believed + or shipped on a past date would make the record less trustworthy. If a reader + could still mistake them for current behavior, that is a `docs/plans/README.md` + line, not a change to the history. + +**Exit:** `grep -rn 'accept anything\|accepts anything' src docs` matches only the +two historical records; the `api_key` field comment and `cli-spec.md` agree with +`server/mod.rs:509-527` and `cli/commands/key.rs:108-118`; no user-facing +document says an empty key opens the server. + +### Stage F4 — Bound a request and stop allocating from a declaration + +Two changes in the same connection path as F1. Do this stage after F1 so the +framing decision is already in place. + +Deadlines: + +- Add `head_timeout_seconds` (default 60) and `body_stall_timeout_seconds` + (default 120) to `ServerLimits` (`src/config.rs:279-288`), the raw config + struct (`:577-580`), the application block (`:743-758`), the template + (`:424-430`), the `HttpServer` builder (`src/server/http.rs:190-198`), and the + wiring at `src/server/mod.rs:192-197`. +- Semantics: the head gets one absolute budget measured from the first byte; + the body gets a **no-progress** budget that resets on every successful read. + A total body deadline is deliberately not used: a legitimate multi-megabyte + media upload on a slow link can take longer than any fixed total while still + making steady progress. +- Head expiry closes the connection silently, matching the existing idle path + (`http.rs:320-322`) rather than writing a response to a peer that may not be + reading; the write path is bounded by `write_timeout_seconds` but a response + adds nothing a proxy cannot infer from the close. Record this choice in the + comment above the loop. +- Implementation: thread the two durations into `handle_connection` and + `read_request` alongside `max_body_bytes`, and have `SocketReader::fill` + callers set `set_read_timeout` to the smaller of the idle and remaining budget + before each read. `SocketReader` already owns the socket, so no new type is + needed. + +Allocation: + +- Replace `let mut body = vec![0u8; length]` (`http.rs:661`) with an + incremental read: `Vec::with_capacity(length.min(64 * 1024))`, then + `reader.by_ref().take(length as u64).read_to_end(&mut body)`, then require + `body.len() == length` and map a short read to the same + `UnexpectedEof` the current `read_exact` produces. +- Keep the `length > max_body_bytes` check where it is, so `413` behavior and its + message do not change. + +Explicitly not in this stage: a per-peer connection cap. `peer_addr` cannot +distinguish EggPool-forwarded clients from each other — all tunnel traffic +arrives from the local forwarder (`docs/eggpool.md`) — so a naive per-peer cap +would throttle every tunneled client together. That needs its own design; the +deadline above is what removes the indefinite-hold problem. + +Tests: + +- `a_stalled_head_is_closed_at_the_head_deadline` — construct the server with + sub-second durations through the builder, send a partial head, and assert the + connection closes without a response. +- `a_stalled_body_is_closed_at_the_stall_deadline` — send a valid head with a + `Content-Length`, then one byte and silence. +- `a_slow_but_progressing_body_is_accepted` — send a body in paced writes that + together exceed the head deadline but never stall longer than the body budget; + assert `200`. This is the test that would fail if the body used a total + deadline. +- Keep the existing `413`, keep-alive, and chunked tests green; confirm the + template round-trip test (`config.rs:1519`, "template without key") still + covers every field by extending it only if it enumerates keys. + +**Exit:** no client can hold an accepted connection by dribbling bytes past the +head budget or stalling mid-body; a progressing upload still succeeds; the body +buffer grows with bytes received, not with the declared length; the config +template and `docs/configuration.md:62-64` list both new settings. + +### Stage F5 — Launch editors that carry arguments + +- Split the `$EDITOR`/`$VISUAL` value into a program and arguments with a small + private function (e.g. `split_editor_command(&str) -> Result, String>`), + used by `pick_editor` (`src/cli/commands/edit.rs:42-48`) and consumed by + `Command::new(&parts[0]).args(&parts[1..]).arg(&path)` (`:19-21`). +- Rules: whitespace separates words; single and double quotes group and are + removed; a backslash escapes only a quote, a backslash, or whitespace, and is + otherwise literal, so `"C:\Program Files\ed\ed.exe"` and `C:\tools\ed.exe` + both survive (`\P` and `\e` remain literal). Never invoke a shell. +- An unbalanced quote is an error naming the variable and its value, not a + silent fallback to `vi`: launching the wrong editor hides the typo. An empty + or whitespace-only value still falls through to the next of `$VISUAL`, + `helix`, `vim`, `nano`, `vi`. +- Update `docs/commands.md:175` to say arguments are allowed and to give + `EDITOR="code -w"` as the example. + +Tests (unit tests beside the splitter): + +- `vim -u NONE` → `["vim", "-u", "NONE"]` +- `"path with spaces/ed" -f` → `["path with spaces/ed", "-f"]` +- `C:\tools\ed.exe` → one element, backslashes preserved +- `"C:\Program Files\ed\ed.exe"` → one element with the path intact +- `"unbalanced` → error naming the value +- ` ` → empty result, falls through + +**Exit:** `EDITOR="vim -u NONE"` opens the editor with the flag and the config +path appended last; a quoted path with spaces works; an unbalanced quote is +reported; no code path reaches a shell. + +## Recommended order + +1. F1, then F4 — same code path, framing first. +2. F3 — documentation only, and it is what an operator reads while F1/F4 change + server behavior. +3. F2 — independent; needs network access to resolve the pins and a decision to + run the optional dry-run dispatch. +4. F5 — independent. + +Each stage is a separate commit with an imperative, sentence-case subject +(`server: refuse ambiguous request framing`, `ci: pin publish actions to commit +SHAs`, `docs: state the key requirement the code enforces`, +`server: bound request reads and allocate from received bytes`, +`cli: accept editor arguments in EDITOR and VISUAL`), and each must build and +pass on its own so the history stays bisect-safe. Do not combine F1 and F4 into +one commit: the framing refusal and the deadline are independently revertible. + +## Validation + +Run after each stage, and after the whole set: + +```sh +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace -- --test-threads=1 +cargo build --locked --release +git diff --check +``` + +Plus, for F2: + +```sh +grep -n 'uses:' .github/workflows/*.yml +python3 -c 'import sys,yaml; [yaml.safe_load(open(p)) for p in sys.argv[1:]]' .github/workflows/*.yml +``` + +Record the measured test count before the first change and after each stage +rather than predicting it. F1 adds roughly four tests, F4 three, F5 six; the +exact numbers depend on whether cases are table rows or separate functions. +Do not edit any recorded count in an earlier plan unless the tests described +there have changed. + +Measured: 556 passing before the first change (513 unit, 32 `eggpass-auth`, +10 `oauth_stub`, 1 doc-test) and 569 after all five stages, so 13 tests were +added: four framing/refusal tests in `http.rs`, three deadline tests, two +configuration tests, and four editor-splitter tests. + +Per commit, measured on each tree rather than inferred: `d5fbc62` 560 (517 +unit, 32 `eggpass-auth`, 10 `oauth_stub`, 1 doc-test), `d051c21` 565, +`d6c3841` 565, `882abeb` 565, `3c56070` 569. `cargo fmt --all -- --check`, +`cargo clippy --workspace --all-targets -- -D warnings` and the test suite +pass at all five, so a bisect lands on a buildable, passing tree. + +`cargo build --locked --release`, `git diff --check`, `actionlint` and a YAML +parse of every workflow pass at the final tree. + +## Risks and rollback + +- **F1 strictness.** Refusing `Content-Length` with `Transfer-Encoding`, a + leading `+`, or a non-final `chunked` coding is stricter than the current + behavior. Each is an explicit `400` with the existing body, and the refusal + is revertible on its own; no accepted request shape regresses. +- **F1 test false pass.** The socket test must authenticate, or the refusal it + observes could come from the gate instead of the framing decision. Assert the + status and the `malformed_body` code, not just the close. +- **F2 pin staleness.** A pinned SHA does not move with a security fix. Record + the resolution date in this plan and refresh at each release; do not let the + pins decay silently. +- **F4 aggressive defaults.** 60 s for a head and 120 s without body progress + are generous for real clients; both are configurable and clamped like the + existing limits. A slow-but-steady upload must keep working — that is the + test the design exists to protect. +- **F4 buffer rewrite.** An incremental read must preserve the current + `UnexpectedEof` on a short body; assert the length equality explicitly, since + `read_to_end` returns `Ok` at EOF. +- **F5 tokenizer.** Keep the escape rule minimal and unit-tested, and never pass + the value through a shell. An unbalanced quote is an error, not a fallback. +- **Rollback.** F2, F3, and F5 are independent files. F1 and F4 are separate + commits on the same functions, so either can be reverted without the other. + +## Out of scope + +- `src/provider/usage/codex_app_server.rs:43`: a `codex` resolved through + `PATH` receives provider tokens. Exploiting it requires the ability to write + to a directory earlier in `PATH` than the real binary, which is the same + privilege that can read the credential store. Recorded, not planned. +- The roughly 830 `unwrap`/`expect` occurrences: production paths were swept and + are clean; the rest are test fixtures. +- The documented SHA-256 integrity-not-authenticity model for updates and the + installer: stated design, not a defect. +- A per-peer connection cap, for the EggPool reason in F4. +- OAuth custody, the EggPool wire contract, provider logins, live probes, media + route enablement, release, publication, or pushing anything. +- Rewriting the historical research and shipped records. + +## References + +- Framing: `src/server/http.rs:457-465` (`BodyError`), `:482-518` (`read_request` + and its refusal arms), `:557-562` (`malformed_body`), `:622-664` (`read_body`), + `:679-724` (`read_chunked_body`), `:298-333` (`handle_connection`); + `src/server/tests.rs:1298` (keep-alive). +- Limits: `src/config.rs:279-288`, `:424-430`, `:577-580`, `:743-758`; + `src/server/http.rs:40-47`, `:159-198`; `src/server/mod.rs:192-197`. +- Key enforcement: `src/server/mod.rs:405-413`, `:509-527`; + `src/cli/commands/key.rs:108-118`; `docs/configuration.md:59,83`. +- Editor: `src/cli/commands/edit.rs:13-60`; `docs/commands.md:175`. +- CI: `.github/workflows/publish-crates.yml`, `publish-eggpass-auth.yml`, + `publish-eggpass-auth-pypi.yml`; pinning precedent in `release.yml:31,59,128` + and `ci.yml:65`. +- Historical records left unchanged: `docs/plans/research.md:526`, + `docs/plans/shipped-2026-11-13.md:282,550`, and the status note in + `docs/plans/README.md`. From 6fcb19df0218c6053cdc4cccbb07fa72af7a615d Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 17:37:26 +0000 Subject: [PATCH 07/10] release: prepare 0.1.4 on one eggfetch-core 0.4.1 - Resolve every eggfetch use in the repository to a single `eggfetch-core` 0.4.1: the CLI's updater adapter, the `eggpass-auth` crate, and the vendored copy the Python bindings build. `eggup-eggfetch` 0.2.2 accepts `^0.4.0`, so the updater keeps its published adapter and shares one version instead of resolving a second line alongside it. - Bump `eggpass` to 0.1.4 and `eggpass-auth` to 0.1.2, and point the CLI's dependency requirement at the new crate version. - Record the release in CHANGELOG.md: the framing refusal, the request deadlines, the editor argument split, the pinned publish actions, and the dependency alignment, all under 0.1.4 alongside the media and non-text work that had accumulated in Unreleased. --- CHANGELOG.md | 33 +++++++++++++++++-- Cargo.lock | 12 +++---- Cargo.toml | 4 +-- crates/eggpass-auth/Cargo.toml | 4 +-- python/eggpass-auth/Cargo.lock | 6 ++-- .../vendor/eggpass-auth/Cargo.toml | 4 +-- 6 files changed, 46 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 244ec2e..fa31d52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Notable changes to eggpass are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [0.1.4] - 2026-11-30 ### Added @@ -17,6 +17,9 @@ Notable changes to eggpass are listed here. The format follows - Carry request fields with a mechanical Responses equivalent, including `response_format` to `text.format`, and pass Responses-native tools through. - Add an optional `server.max_body_bytes` setting, defaulting to 32 MiB. +- Add `server.head_timeout_seconds` and `server.body_stall_timeout_seconds`, + defaulting to 60 and 120 seconds, so a request that stalls part-way through + its head or body is closed. - Add probe-gated routing for native media endpoints. A route is enabled only after `eggpass probe media` records a provider-side success for it, so an unprobed path still answers `404`. @@ -43,6 +46,10 @@ Notable changes to eggpass are listed here. The format follows `user`. - Answer a chat or Responses request without a readable `model` with `400 missing_model` instead of routing it to the default provider. +- Split `EDITOR` and `VISUAL` into a program and its arguments, so values such + as `code --wait` and `vim -f` launch the editor that was named. +- Resolve one `eggfetch-core` 0.4.1 across the CLI, `eggpass-auth` and the + Python bindings instead of mixing the lines the updater pulls in. ### Fixed @@ -51,6 +58,27 @@ Notable changes to eggpass are listed here. The format follows - Fail an answer or stream whose content cannot be expressed in the Chat Completions shape with `unmappable_output_item` instead of empty content. - Name the limit and the inline-media cause in the `413` response. +- Refuse a request whose body framing is ambiguous instead of guessing. An + unparseable `Content-Length` used to mean "no body", so its bytes were read + as the next request line and could carry a second request past the gate. +- Close a request that stalls part-way through its head or body. The idle + timeout reset on every read, so a peer sending one byte at a time was never + closed: the head now has one absolute budget measured from its first byte, + and a body has a no-progress budget that leaves a slow upload alone. +- Grow a body buffer with the bytes that arrive rather than reserving the + announced length before any of it has been sent, and reject a body that + ends early instead of accepting a truncated one. + +### Security + +- Pin every third-party action in the three publish workflows to the commit + its tag pointed at, so a moved tag cannot change what a release runs. + +### Notes + +- The server has no unauthenticated state. With neither an issued key nor a + config `api_key` it refuses every request with `401 no_api_key`, and the + documentation now says so instead of describing an open loopback endpoint. ## [0.1.3] - 2026-11-22 @@ -162,7 +190,8 @@ First release of the local OpenAI-compatible proxy for Grok and ChatGPT. - The project was renamed from `grokproxy` to `eggpass`. Existing data is copied to `~/.config/eggpass`; the old directory is left in place. -[Unreleased]: https://github.com/eggstack/eggpass/compare/v0.1.3...HEAD +[Unreleased]: https://github.com/eggstack/eggpass/compare/v0.1.4...HEAD +[0.1.4]: https://github.com/eggstack/eggpass/compare/v0.1.3...v0.1.4 [0.1.3]: https://github.com/eggstack/eggpass/compare/v0.1.2...v0.1.3 [0.1.2]: https://github.com/eggstack/eggpass/compare/v0.1.1...v0.1.2 [0.1.1]: https://github.com/eggstack/eggpass/compare/v0.1.0...v0.1.1 diff --git a/Cargo.lock b/Cargo.lock index b276c94..935fb68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -292,9 +292,9 @@ dependencies = [ [[package]] name = "eggfetch-core" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db5ee3c2312c08942874fbc4b44d91c4ef674f19fb5e9d6edd1281c94225f65e" +checksum = "0ce3da6bdaaeb29fc3f3f951f910429c5d83b5a9396b39da4f56292ec370dbe7" dependencies = [ "base64", "bytes", @@ -324,9 +324,9 @@ dependencies = [ [[package]] name = "eggfetch-http-connect" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16ee2bb546c6c60c27e32779a75f1472ccd419a3472c88ab8f03721de2223f25" +checksum = "a8aa27a14449e9760e7f2f3c6a8461cb296f4db4da43ddf1659f889cff54019b" dependencies = [ "base64", "thiserror", @@ -345,7 +345,7 @@ dependencies = [ [[package]] name = "eggpass" -version = "0.1.3" +version = "0.1.4" dependencies = [ "base64", "daemonize", @@ -375,7 +375,7 @@ dependencies = [ [[package]] name = "eggpass-auth" -version = "0.1.1" +version = "0.1.2" dependencies = [ "base64", "eggfetch-core", diff --git a/Cargo.toml b/Cargo.toml index bac4d21..853d269 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" [package] name = "eggpass" -version = "0.1.3" +version = "0.1.4" edition = "2024" rust-version = "1.89" description = "A lightweight, local, OpenAI-compatible proxy for Grok and ChatGPT, authenticated with your own subscription over OAuth" @@ -33,7 +33,7 @@ include = [ ] [dependencies] -eggpass-auth = { version = "0.1.1", path = "crates/eggpass-auth" } +eggpass-auth = { version = "0.1.2", path = "crates/eggpass-auth" } base64 = "0.23.1" # Exact Eggress reverse-client wire/API line used by EggPool. eggress-protocol-reverse = "=1.0.12" diff --git a/crates/eggpass-auth/Cargo.toml b/crates/eggpass-auth/Cargo.toml index fb6afc3..5741a2a 100644 --- a/crates/eggpass-auth/Cargo.toml +++ b/crates/eggpass-auth/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eggpass-auth" -version = "0.1.1" +version = "0.1.2" edition = "2024" rust-version = "1.89" description = "Async OAuth authentication flows for applications using Eggfetch" @@ -14,7 +14,7 @@ include = ["/src", "/README.md", "/LICENSE", "/examples"] [dependencies] base64 = "0.23.1" -eggfetch-core = { version = "0.4.0", default-features = false, features = ["native-http1", "tls-rustls"] } +eggfetch-core = { version = "0.4.1", default-features = false, features = ["native-http1", "tls-rustls"] } form_urlencoded = "1.2.2" http = "1" http-body-util = "0.1" diff --git a/python/eggpass-auth/Cargo.lock b/python/eggpass-auth/Cargo.lock index 8c11885..71c1155 100644 --- a/python/eggpass-auth/Cargo.lock +++ b/python/eggpass-auth/Cargo.lock @@ -105,9 +105,9 @@ dependencies = [ [[package]] name = "eggfetch-core" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db5ee3c2312c08942874fbc4b44d91c4ef674f19fb5e9d6edd1281c94225f65e" +checksum = "0ce3da6bdaaeb29fc3f3f951f910429c5d83b5a9396b39da4f56292ec370dbe7" dependencies = [ "bytes", "futures-core", @@ -130,7 +130,7 @@ dependencies = [ [[package]] name = "eggpass-auth" -version = "0.1.1" +version = "0.1.2" dependencies = [ "base64", "eggfetch-core", diff --git a/python/eggpass-auth/vendor/eggpass-auth/Cargo.toml b/python/eggpass-auth/vendor/eggpass-auth/Cargo.toml index fb6afc3..5741a2a 100644 --- a/python/eggpass-auth/vendor/eggpass-auth/Cargo.toml +++ b/python/eggpass-auth/vendor/eggpass-auth/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eggpass-auth" -version = "0.1.1" +version = "0.1.2" edition = "2024" rust-version = "1.89" description = "Async OAuth authentication flows for applications using Eggfetch" @@ -14,7 +14,7 @@ include = ["/src", "/README.md", "/LICENSE", "/examples"] [dependencies] base64 = "0.23.1" -eggfetch-core = { version = "0.4.0", default-features = false, features = ["native-http1", "tls-rustls"] } +eggfetch-core = { version = "0.4.1", default-features = false, features = ["native-http1", "tls-rustls"] } form_urlencoded = "1.2.2" http = "1" http-body-util = "0.1" From 0b58d7efd54b29b91caabdf36f83c39bd4d76175 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 17:37:26 +0000 Subject: [PATCH 08/10] docs: link the EggPool guide from the README - The README's documentation table skipped docs/eggpool.md, which docs/README.md lists, leaving the reverse-tunnel contract unreachable from the front page. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 73b74bb..42845bd 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ settings, timeouts, and files on disk. | [Commands](docs/commands.md) | Command syntax, options, and effects | | [Client setup](docs/client-setup.md) | OpenAI SDK, OpenCode, Cline, Continue, and curl | | [Configuration](docs/configuration.md) | Config settings and files | +| [EggPool](docs/eggpool.md) | Reverse-tunnel enrollment contract and security model | | [How it works](docs/how-it-works.md) | Routing, translation, authentication, and streaming | | [Updating](docs/updating.md) | Update verification and rollback | | [Troubleshooting](docs/troubleshooting.md) | Common errors and fixes | From fb19e15a31d86f0ad0bdb2f47d05223260fe3a23 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 17:39:05 +0000 Subject: [PATCH 09/10] docs: record the package order the release checks enforce - Say what a reader hits when they run the CLI release checks before the new `eggpass-auth` version is on crates.io: `cargo package` cannot resolve the requirement, because the packaged CLI needs the published crate rather than the path dependency. - Name that as a wrong ordering rather than a broken CLI, so the runbook's own verification step is not mistaken for a failure to fix in the CLI. --- docs/releasing.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/releasing.md b/docs/releasing.md index b95d9f1..eb479a1 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -161,6 +161,13 @@ crates.io publication runs only after a human publishes a GitHub release for that exact tag. Publish the crate before the next Eggpass crates.io release that depends on it, so Cargo can resolve the dependency. +The order is enforced, not advisory. Until the new `eggpass-auth` version is +on crates.io, `cargo package --locked -p eggpass` cannot select a version +for the requirement `eggpass-auth = "^X.Y.Z"`, because the packaged CLI must +resolve the published crate rather than the path dependency. That failure +means the order is wrong, not that the CLI is broken: release and publish +`eggpass-auth` first, then run the CLI release checks again. + ### Python distribution The Python package in `python/eggpass-auth` has its own version and uses the From 07a8ab853f1a26ea989acdba94a1d8ef0f0ef660 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 30 Nov 2026 19:25:28 +0000 Subject: [PATCH 10/10] release: bump the Python eggpass-auth distribution to 0.1.3 - The PyPI distribution vendors the `eggpass-auth` crate, whose source moved from 0.1.1 to 0.1.2 with the `eggfetch-core` 0.4.1 alignment. A 0.1.2 artifact is already published, so source that changed needs its own version rather than a republish of the same one. - Keep `pyproject.toml` and the maturin wrapper crate equal, which is what the PyPI workflow asserts, and leave the vendored crate at 0.1.2: that is the library version it contains. --- python/eggpass-auth/Cargo.lock | 2 +- python/eggpass-auth/Cargo.toml | 2 +- python/eggpass-auth/pyproject.toml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/python/eggpass-auth/Cargo.lock b/python/eggpass-auth/Cargo.lock index 71c1155..697d049 100644 --- a/python/eggpass-auth/Cargo.lock +++ b/python/eggpass-auth/Cargo.lock @@ -148,7 +148,7 @@ dependencies = [ [[package]] name = "eggpass-auth-python" -version = "0.1.2" +version = "0.1.3" dependencies = [ "eggpass-auth", "pyo3", diff --git a/python/eggpass-auth/Cargo.toml b/python/eggpass-auth/Cargo.toml index 1163d24..6055d1f 100644 --- a/python/eggpass-auth/Cargo.toml +++ b/python/eggpass-auth/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "eggpass-auth-python" -version = "0.1.2" +version = "0.1.3" edition = "2024" rust-version = "1.89" description = "Python asyncio bindings for eggpass-auth" diff --git a/python/eggpass-auth/pyproject.toml b/python/eggpass-auth/pyproject.toml index 590c768..1bbac6d 100644 --- a/python/eggpass-auth/pyproject.toml +++ b/python/eggpass-auth/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "eggpass-auth" -version = "0.1.2" +version = "0.1.3" description = "Async Python bindings for the eggpass-auth OAuth client" readme = "README.md" requires-python = ">=3.11"