fix(web): harden WebSocket and net host boundaries

- WS handshake: same-origin CheckOrigin instead of allow-all
- route_ws require_auth/需要登录: broadcast/room need a session by default,
  explicit opt-out for public feeds; unauthenticated handshakes get 401
- WS limits: 1 MiB per message, 256 replies per connect; transport errors
  return {ok:false, error} instead of an empty success; empty rooms GC'd
- net host: enforce the 8 MiB response cap while reading (incl. error and
  SSE error paths) so a peer cannot exhaust memory
- url_encode: %20 for space (URL segment semantics, not form +)
- docs: sync 网页 (route_ws 需要登录, connect caps) and CHANGELOG
- tests: gold expectations, live fixture opt-out, hub GC, ws auth gate

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-22 15:14:35 +08:00
1 parent 8e23a5395a
commit 86b183e2d7
15 files changed
+233 -28

No files matched your search

+41 -10
View File
@@ -1,6 +1,6 @@
//! HTTP host primitives (HTTP and HTTPS via ureq).
use std::io::Write;
use std::io::{Read, Write};
#[cfg(feature = "net-host")]
use std::io::{BufRead, BufReader};
#[cfg(feature = "net-host")]
@@ -32,6 +32,26 @@ fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>,
}
}
/// Maximum response body accepted by the text HTTP helpers.
///
/// Read the limit from the stream, rather than after converting it to a `String`:
/// an untrusted peer must never be able to allocate an arbitrary response in memory.
#[cfg(feature = "net-host")]
const MAX_HTTP_BODY_BYTES: usize = 8 * 1024 * 1024;
#[cfg(feature = "net-host")]
fn read_response_text<R: Read>(reader: R) -> Result<String, String> {
let mut bytes = Vec::new();
reader
.take(MAX_HTTP_BODY_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.map_err(|e| format!("http read body: {e}"))?;
if bytes.len() > MAX_HTTP_BODY_BYTES {
return Err("http response exceeds 8MiB limit".into());
}
Ok(String::from_utf8_lossy(&bytes).into_owned())
}
#[cfg(feature = "net-host")]
fn http_exchange(
method: &str,
@@ -74,16 +94,11 @@ fn http_exchange(
match resp {
Ok(r) => {
let status = r.status();
let text = r
.into_string()
.map_err(|e| format!("http read body: {e}"))?;
if text.len() > 8 * 1024 * 1024 {
return Err("http response exceeds 8MiB limit".into());
}
let text = read_response_text(r.into_reader())?;
Ok((status, text))
}
Err(ureq::Error::Status(code, r)) => {
let text = r.into_string().unwrap_or_default();
let text = read_response_text(r.into_reader())?;
Ok((code, text))
}
Err(e) => Err(format!("http {method} {url}: {e}")),
@@ -177,7 +192,9 @@ pub fn url_encode(text: &Value) -> Result<Value, String> {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
(b as char).to_string()
}
b' ' => "+".into(),
// `url_encode` documents a URL *segment*. `+` is form/query
// encoding, where it is ambiguous with a literal plus in a path.
b' ' => "%20".into(),
_ => format!("%{b:02X}"),
})
.collect(),
@@ -809,7 +826,7 @@ pub fn http_post_sse(
]))
}
Err(ureq::Error::Status(code, r)) => {
let text = r.into_string().unwrap_or_default();
let text = read_response_text(r.into_reader())?;
Ok(Value::Map(vec![
("status".into(), Value::Int(code as i64)),
(
@@ -842,6 +859,20 @@ mod tests {
.any(|(k, v)| k == "Authorization" && v == "Bearer x"));
}
#[cfg(feature = "net-host")]
#[test]
fn response_limit_stops_before_unbounded_allocation() {
let body = vec![b'x'; MAX_HTTP_BODY_BYTES + 1];
let err = read_response_text(std::io::Cursor::new(body)).unwrap_err();
assert_eq!(err, "http response exceeds 8MiB limit");
}
#[test]
fn url_segment_encoding_keeps_space_and_plus_distinct() {
let encoded = url_encode(&Value::Text("a b+c".into())).unwrap();
assert!(matches!(encoded, Value::Text(text) if text == "a%20b%2Bc"));
}
#[test]
fn openai_sse_fixture_to_events() {
let fixture = "\