From 5f7244da4d0e6cb646c069eded0a6300fdf4f250 Mon Sep 17 00:00:00 2001 From: fl0l0u Date: Fri, 30 Oct 2026 12:12:33 +0000 Subject: [PATCH] server: bound what an unauthenticated socket can make the transport hold Three ways a client spent the server's patience or memory without ever being admitted: The gate's 401 answers before any handler sees the request, so its body sits unread on a keep-alive socket, and httplib's anti-smuggling drain will wait for it: one byte per read timeout paces a whole worker, at the pacing client's chosen rate. The refusal now closes the connection instead, says so on the response, and buries the body with the socket -- which is also what makes draining a refusal pointless. A drain that does have a purpose -- a framed body on a request the router answered without reading it -- inherits the stream's 30 s read wait per packet gap and no total bound at all. It keeps both waits now: five seconds per gap (the stream's own set_read_timeout, the same knob the WebSocket upgrade uses) and five in total (a deadline the discard provider checks), then the connection dies and the timeout is restored for whatever the connection still has coming. And bodies. The per-request cap bounds one body and no sum, every byte of a body is buffered before parse, admission or any accounting sees it, and a few hundred concurrent large POSTs is an OOM that reaches the engine before any refusal does. read_and_bridge now holds every buffered byte against a transport-wide budget and answers 429 with Retry-After to the newcomer the budget has no room for; the reservation releases on every exit, including the peer vanishing mid-body. The budget defaults to eight bodies at the per-request cap and moves through ServerOptions::max_inflight_body_bytes. Vendor: the two httplib hunks are recorded as patches/0022, and UPSTREAM's "no file content differs" for the pair is replaced with what the split actually is and what is now edited in it. transport_test: a_refusal_closes_the_connection, a_stalled_drain_dies_on_its_deadline, the_inflight_body_budget. ASan+UBSan: transport/wire/lifecycle/server/config/diag/dashboard, 7/7. --- core/server/http.cpp | 48 ++++++++++- core/server/http.h | 6 ++ core/server/server.cpp | 1 + core/server/server.h | 3 + tests/transport_test.cpp | 80 +++++++++++++++++++ vendor/UPSTREAM | 50 ++++++++++-- vendor/cpp-httplib/httplib.cpp | 34 +++++++- ...ocket-and-the-drain-keeps-a-deadline.patch | 58 ++++++++++++++ 8 files changed, 268 insertions(+), 12 deletions(-) create mode 100644 vendor/patches/0022-httplib-a-refusal-closes-the-socket-and-the-drain-keeps-a-deadline.patch diff --git a/core/server/http.cpp b/core/server/http.cpp index 725cb8d1..73a7173b 100644 --- a/core/server/http.cpp +++ b/core/server/http.cpp @@ -656,24 +656,64 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { [st](bool ok) { if (st->on_close) st->on_close(ok); }); }; + /* The sum of buffered bodies across all connections, and its budget. Bodies are buffered + * whole before parse, admission or any accounting sees them, so the per-request cap alone + * bounds none of the total: a few hundred concurrent large POSTs is an OOM that reaches the + * engine before any 429 does. Over budget, the body is refused mid-read with a 429. */ + const size_t inflight_limit = + o.max_inflight_body_bytes ? o.max_inflight_body_bytes : 8 * o.max_body_bytes; + auto inflight = std::make_shared>(0); + /* A body is read straight into the string the handler parses. httplib's own Request hands * it out only const, so it would be copied and held twice. A multipart body (an image * upload) is read part by part, each into its own string, under the same limit. */ - auto read_and_bridge = [bridge](const httplib::Request& q, httplib::Response& s, - const httplib::ContentReader& read) { + auto read_and_bridge = [bridge, inflight, inflight_limit](const httplib::Request& q, + httplib::Response& s, + const httplib::ContentReader& read) { std::string body; std::vector form; + /* Every byte appended is held against the budget until the handler is done with the + * body it belongs to; the guard releases the whole reservation on any exit. */ + size_t held = 0; + struct Releaser { + std::shared_ptr> n; + size_t* held; + ~Releaser() { n->fetch_sub(*held); } + } releaser{inflight, &held}; + bool over = false; + auto room = [&](size_t n) { + held += n; + if (inflight->fetch_add(n) + n <= inflight_limit) return true; + over = true; + return false; + }; const bool ok = q.is_multipart_form_data() ? read([&form](const httplib::FormData& f) { form.push_back(FormPart{ f.name, f.filename, f.content_type, {} }); return true; }, - [&form](const char* p, size_t n) { + [&form, &room](const char* p, size_t n) { + if (!room(n)) return false; if (!form.empty()) form.back().data.append(p, n); return true; }) - : read([&body](const char* p, size_t n) { body.append(p, n); return true; }); + : read([&body, &room](const char* p, size_t n) { + if (!room(n)) return false; + body.append(p, n); + return true; + }); if (!ok) { + if (over) { + /* The summed budget, not the per-request cap: name it so the client reads the + * retry for what it is, not as its own file having grown too large. */ + s.status = 429; + s.set_header("Retry-After", "5"); + s.set_content(error_body(q.path, 429, "rate_limit_error", + "the server is holding more request bodies than its " + "total buffering budget allows; retry shortly"), + "application/json"); + return; + } /* httplib has already set 413 for a body over the limit; anything else is a peer * that stopped sending partway. */ if (s.status < 0) { diff --git a/core/server/http.h b/core/server/http.h index f475546d..ee54a969 100644 --- a/core/server/http.h +++ b/core/server/http.h @@ -195,6 +195,12 @@ struct TransportOptions { int write_timeout_s = 600; int keep_alive_timeout_s = 5; /* an idle connection's hold on a worker between requests */ size_t max_body_bytes = 512ull << 20; /* images arrive base64 inside the JSON body */ + /* The sum of bodies being buffered across all connections at once. The per-request cap says + * nothing about the sum, and a request's body is fully buffered before parse, admission or + * any memory accounting sees it; over budget, a body is refused 429 rather than pushed into + * RAM until the OOM killer chooses which process dies. 0 takes 8 concurrent bodies at the + * per-request cap. */ + size_t max_inflight_body_bytes = 0; std::string api_key; /* "" disables the check */ bool cors = true; }; diff --git a/core/server/server.cpp b/core/server/server.cpp index 8b488a4a..d4c032c4 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -276,6 +276,7 @@ int Server::run() { t.write_timeout_s = opt_.write_timeout_s; t.keep_alive_timeout_s = opt_.keep_alive_timeout_s; t.max_body_bytes = opt_.max_body_bytes; + t.max_inflight_body_bytes = opt_.max_inflight_body_bytes; return transport_.serve(router_, t); } diff --git a/core/server/server.h b/core/server/server.h index dc5a332f..f22e36ec 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -193,6 +193,9 @@ struct ServerOptions { int write_timeout_s = 600; int keep_alive_timeout_s = 5; size_t max_body_bytes = 512ull << 20; + /* The sum of in-flight request bodies across connections; 0 takes the transport's default + * (eight bodies at the per-request cap). See TransportOptions. */ + size_t max_inflight_body_bytes = 0; }; class Server { diff --git a/tests/transport_test.cpp b/tests/transport_test.cpp index ca74f8d7..a26e53af 100644 --- a/tests/transport_test.cpp +++ b/tests/transport_test.cpp @@ -325,6 +325,86 @@ TEST(the_api_key_gate_holds_every_route_but_the_probes) { CHECK_EQ(ask("HEAD / HTTP/1.1\r\nHost: t\r\n\r\n", /*head_only=*/true).status, 200); } +/* A 401 from the key gate ends the connection. The refused request's body was never read, and + * keeping the socket alive makes those bytes somebody's problem: draining them hands the + * refusing client a way to pace a worker — one byte per socket timeout, forever — and not + * draining them leaves them to be read back as the next request. The refusal closes the socket + * instead, which buries the body with it, and says so on the response itself. */ +TEST(a_refusal_closes_the_connection) { + LiveServer s(4, 1, [](ServerOptions& o) { o.api_key = "k"; }); + REQUIRE(s.srv->port() > 0); + s.sched.hang = false; + s.sched.reply = "ok"; + const std::string body = "{\"prompt\":\"" + std::string(4096, 'x') + "\"}"; + const int fd = s.open(post("/v1/completions", body, "Authorization: Bearer wrong\r\n")); + REQUIRE(fd >= 0); + const Reply r = read_reply(fd); + CHECK_EQ(r.status, 401); + CHECK_EQ(r.header("Connection"), std::string("close")); + /* Nothing follows the response: the server is done with this connection, however much of + * the body the client had already pushed at it. */ + char c; + CHECK_EQ(::recv(fd, &c, 1, 0), (ssize_t)0); + /* And the very next connection lives — the pool is not, and the request that carries the + * key still reads normally. */ + CHECK_EQ(ask(s, post("/v1/completions", body, "Authorization: Bearer k\r\n")).status, 200); +} + +/* A drain that does run dies on its deadline. A GET carries its framed body to no handler at + * all — the router answers it in pre-routing, unread — and the anti-smuggling drain reads that + * body only to discard it. The connection's own 30 s read timeout bounds each packet gap, not + * the drain, so without a deadline a client dribbling one byte per gap holds a worker on a + * request that was already answered. With it: five seconds, then the connection. */ +TEST(a_stalled_drain_dies_on_its_deadline) { + LiveServer s(4, 1); + REQUIRE(s.srv->port() > 0); + const int fd = s.open("GET /health HTTP/1.1\r\nHost: t\r\nContent-Length: 200\r\n\r\n" + "xxxxxxxxxxxxxxxx", 12); + REQUIRE(fd >= 0); + CHECK(has(status_line(fd), " 200 ")); /* health answered before the drain began */ + const auto t0 = std::chrono::steady_clock::now(); + char c; + const ssize_t n = ::recv(fd, &c, 1, 0); /* ends when the drain gives up, not at 30 s */ + const int64_t secs = (int64_t)std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0).count(); + CHECK_EQ(n, (ssize_t)0); + CHECK(secs >= 4 && secs <= 9); +} + +/* The per-request body cap says nothing about the SUM of bodies buffering at once, and every + * byte of a body lands in RAM before parsing, admission or any accounting sees it. The summed + * budget refuses the newcomer with a 429 naming itself, and releases the reservation when the + * stalled peer goes — the next body of the same size then fits. */ +TEST(the_inflight_body_budget_refuses_the_newcomer_and_releases_the_stallers) { + LiveServer s(4, 1, [](ServerOptions& o) { o.max_inflight_body_bytes = 256; }); + REQUIRE(s.srv->port() > 0); + s.sched.hang = false; + s.sched.reply = "ok"; + + /* A: 200 bytes announced, 120 sent, then silence. The worker sits in the read holding 120. */ + const int a = s.open("POST /v1/completions HTTP/1.1\r\nHost: t\r\n" + "Content-Type: application/json\r\nContent-Length: 200\r\n\r\n" + + std::string(120, 'x')); + REQUIRE(a >= 0); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + + /* B: a complete, modest 200-byte body — under its own cap, over the shared budget. */ + const std::string body = "{\"prompt\":\"" + std::string(200 - 13, 'x') + "\"}"; + REQUIRE_EQ(body.size(), (size_t)200); + const Reply over = ask(s, post("/v1/completions", body)); + CHECK_EQ(over.status, 429); + CHECK_EQ(over.header("Retry-After"), std::string("5")); + CHECK(has(over.body, "budget")); + CHECK(!has(over.body, "too large")); /* not dressed up as the per-request cap */ + + /* A hangs up; its bytes come off the budget with it. */ + ::close(a); + s.fds.erase(std::find(s.fds.begin(), s.fds.end(), a)); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + const Reply fit = ask(s, post("/v1/completions", body)); + CHECK_EQ(fit.status, 200); +} + /* A refusal the transport writes itself on an Anthropic path (the key gate's 401, a body over * the limit, a wrong method, an unknown path below /v1/messages) is in Anthropic's envelope, as * the handlers' refusals there are; the same refusal elsewhere stays OpenAI's. */ diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index 9faf508b..433f4926 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -143,11 +143,15 @@ vendor/cpp-httplib/httplib.h vendor/cpp-httplib/httplib.cpp vendor/cpp-httplib/LICENSE <- llama.cpp vendor/cpp-httplib/cpp-httplib/* - Header-only JSON and a split-source HTTP library, both unmodified. The only difference from - upstream is the PATH: llama.cpp nests them one directory deeper (vendor/nlohmann/nlohmann/) - and puts the outer directory on the include path. Flattening lets `` and - `` resolve with vendor/ alone on the path, which is the one include - directory core/CMakeLists.txt already adds. No file content differs. + Header-only JSON, byte for byte as lifted, and the HTTP library at cpp-httplib v0.46.1 SPLIT from + upstream's single ~20,400-line header into a .h/.cpp pair, so one translation unit pays for it. + Apart from the split the httplib pair matched upstream exactly when it was lifted; the split itself + drops two decorative `// ----` separator comment lines, moves `inline` from definitions to + declarations, and adds the .cpp's `#include "httplib.h"` and namespace brace. The only difference + from upstream for both is the PATH: llama.cpp nests them one directory deeper + (vendor/nlohmann/nlohmann/) and puts the outer directory on the include path. Flattening lets + `` and `` resolve with vendor/ alone on the path, which + is the one include directory core/CMakeLists.txt already adds. cpp-httplib's own CMakeLists.txt is NOT carried. vendor/CMakeLists.txt builds httplib.cpp itself, because upstream's version reaches for llama.cpp's license and compile-flag helpers @@ -156,7 +160,19 @@ vendor/cpp-httplib/LICENSE <- llama.cpp vendor/cpp-httplib/cpp vendor/CMakeLists.txt sets, so a future disagreement between them would have been invisible -- the copy nobody builds is the copy nobody checks. - LOCAL CHANGES: none. + Upstream is several majors ahead of v0.46.1 now — 0.46.1 is what llama.cpp carried at the lifted + commit. The lift is owed; when it happens, the patch below must be re-checked against the newer + library's own keep-alive refusal and exception handling (its serve_guarded makes the provider-side + catch core/server/http.cpp carries redundant), not just re-applied. + + LOCAL CHANGES: patches/0022-httplib-a-refusal-closes-the-socket-and-the-drain-keeps-a-deadline.patch + + On 0022: the API-key gate answers 401 before a handler runs, so the refused request's body sits + unread on the keep-alive socket and upstream's anti-smuggling drain reads it byte by byte — one + byte per socket timeout paces a whole worker, and the attacker chooses the pace. 0022 hands every + such refusal a closed connection (the unread bytes die with it, which is also what makes the drain + moot) and gives a drain that does run a 5 s budget — per packet gap and in total — after which the + connection closes too. REWRITTEN INTO core/ INSTEAD @@ -564,3 +580,25 @@ PATCH SERIES with `m.content.0.type`, and since the probe swallows the throw the template came back as tools=0 tool_calls=0, as 0006 describes: every request with `tools` was refused. tests/chat_test.cpp (a_dotted_integer_is_an_index_as_in_jinja2). + + patches/0022-httplib-a-refusal-closes-the-socket-and-the-drain-keeps-a-deadline.patch + + vendor/cpp-httplib/, not vendor/llama/: applies from vendor/cpp-httplib/ with `patch -p1`. + + Upstream's tail of process_request() drains an unconsumed framed body to keep it from being + read back as the next request on a keep-alive connection. The drain has two ways to be + weaponed against this server. A request the API-key gate refused (401 answered before any + handler saw it) has a whole body sitting unread, and the drain will wait for it: the stream's + read wait (30 s here) bounds each packet gap, not the drain, so a client that dribbles one + byte per timeout holds that worker for as long as it likes, on a socket that was never going to + be used again. And the same dribble works on any 404 with a body — the drain there has a + purpose, but no bound. + + The patch closes the connection on every 401 that left a framed body unread — `Connection: + close` on the refusal itself, and the socket shut after it — and gives every drain that does + run a 5 s budget, bounded twice: the stream's read wait shortened for the drain (the WebSocket + upgrade already used set_read_timeout for exactly this) and a steady_clock deadline in the + discard provider for the total. Past either, the connection is + closed and the unread bytes die with it. The socket's own read timeout is restored after, so + the next keep-alive request is unaffected. Tests: transport_test + (a_refusal_closes_the_connection, the_inflight_body_budget). diff --git a/vendor/cpp-httplib/httplib.cpp b/vendor/cpp-httplib/httplib.cpp index b9d05d92..fe98b5f6 100644 --- a/vendor/cpp-httplib/httplib.cpp +++ b/vendor/cpp-httplib/httplib.cpp @@ -8453,6 +8453,20 @@ Server::process_request(Stream &strm, const std::string &remote_addr, : StatusCode::PartialContent_206; } + // LOCAL CHANGE (radiance): a request the API-key gate refused (401 + // answered before any handler saw it) has no further use for this + // connection, and must not keep one: its unread body would otherwise be + // drained on the keep-alive socket, which hands the refusing client a + // way to pace this worker — one byte per socket timeout, indefinitely. + // Say close on the response itself and end the connection; the unread + // bytes die with it, which is also what makes the drain below moot for + // the refusal. + if (res.status == StatusCode::Unauthorized_401 && !req.body_consumed_ && + detail::has_framed_body(req)) { + close_connection = true; + connection_closed = true; + } + // Serve file content by using a content provider auto file_open_error = false; if (!res.file_content_path_.empty()) { @@ -8499,14 +8513,30 @@ Server::process_request(Stream &strm, const std::string &remote_addr, // Drain any unconsumed framed body to prevent request smuggling on // keep-alive. Without framing there is no body to drain — reading would - // consume the next request (issue #2450). + // consume the next request (issue #2450). A 401 refusal never gets here + // with a live connection (see the LOCAL CHANGE above). + // + // LOCAL CHANGE (radiance): the drain is bounded by a deadline, twice + // over — per packet gap (the stream's read wait shortened to 5 s for the + // drain: the connection's own 30 s bounds a gap, not the drain, and a + // client dribbling one byte per timeout would pace this worker + // indefinitely) and in total (the provider stops once 5 s have passed). + // Past either, the connection is closed and the unread bytes die with it. if (!req.body_consumed_ && detail::has_framed_body(req)) { + constexpr time_t kDrainBudgetSec = 5; + strm.set_read_timeout(kDrainBudgetSec, 0); + const auto drain_until = std::chrono::steady_clock::now() + + std::chrono::seconds(kDrainBudgetSec); int dummy_status; if (!detail::read_content( strm, req, payload_max_length_, dummy_status, nullptr, - [](const char *, size_t, size_t, size_t) { return true; }, false)) { + [drain_until](const char *, size_t, size_t, size_t) { + return std::chrono::steady_clock::now() < drain_until; + }, + false)) { connection_closed = true; } + strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_); } return ret; diff --git a/vendor/patches/0022-httplib-a-refusal-closes-the-socket-and-the-drain-keeps-a-deadline.patch b/vendor/patches/0022-httplib-a-refusal-closes-the-socket-and-the-drain-keeps-a-deadline.patch new file mode 100644 index 00000000..b104771d --- /dev/null +++ b/vendor/patches/0022-httplib-a-refusal-closes-the-socket-and-the-drain-keeps-a-deadline.patch @@ -0,0 +1,58 @@ +diff --git a/httplib.cpp b/httplib.cpp +index b9d05d9..fe98b5f 100644 +--- a/httplib.cpp ++++ b/httplib.cpp +@@ -8453,6 +8453,20 @@ Server::process_request(Stream &strm, const std::string &remote_addr, + : StatusCode::PartialContent_206; + } + ++ // LOCAL CHANGE (radiance): a request the API-key gate refused (401 ++ // answered before any handler saw it) has no further use for this ++ // connection, and must not keep one: its unread body would otherwise be ++ // drained on the keep-alive socket, which hands the refusing client a ++ // way to pace this worker — one byte per socket timeout, indefinitely. ++ // Say close on the response itself and end the connection; the unread ++ // bytes die with it, which is also what makes the drain below moot for ++ // the refusal. ++ if (res.status == StatusCode::Unauthorized_401 && !req.body_consumed_ && ++ detail::has_framed_body(req)) { ++ close_connection = true; ++ connection_closed = true; ++ } ++ + // Serve file content by using a content provider + auto file_open_error = false; + if (!res.file_content_path_.empty()) { +@@ -8499,14 +8513,30 @@ Server::process_request(Stream &strm, const std::string &remote_addr, + + // Drain any unconsumed framed body to prevent request smuggling on + // keep-alive. Without framing there is no body to drain — reading would +- // consume the next request (issue #2450). ++ // consume the next request (issue #2450). A 401 refusal never gets here ++ // with a live connection (see the LOCAL CHANGE above). ++ // ++ // LOCAL CHANGE (radiance): the drain is bounded by a deadline, twice ++ // over — per packet gap (the stream's read wait shortened to 5 s for the ++ // drain: the connection's own 30 s bounds a gap, not the drain, and a ++ // client dribbling one byte per timeout would pace this worker ++ // indefinitely) and in total (the provider stops once 5 s have passed). ++ // Past either, the connection is closed and the unread bytes die with it. + if (!req.body_consumed_ && detail::has_framed_body(req)) { ++ constexpr time_t kDrainBudgetSec = 5; ++ strm.set_read_timeout(kDrainBudgetSec, 0); ++ const auto drain_until = std::chrono::steady_clock::now() + ++ std::chrono::seconds(kDrainBudgetSec); + int dummy_status; + if (!detail::read_content( + strm, req, payload_max_length_, dummy_status, nullptr, +- [](const char *, size_t, size_t, size_t) { return true; }, false)) { ++ [drain_until](const char *, size_t, size_t, size_t) { ++ return std::chrono::steady_clock::now() < drain_until; ++ }, ++ false)) { + connection_closed = true; + } ++ strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_); + } + + return ret;