server: bound, gate and sanitize every request entry point

Prepared for exposing the dashboard and the API beyond the local machine. Each piece
answers a finding from the review; none changes what a legitimate client sees.

Parsing. Six entry points still called json::parse with no bound on the tree: the two
WebSocket sessions, the image form's loras field, the two re-parses of template kwargs,
the control-vector POST and the lora-admin body. A legal frame or body of brackets alone
built a tree whose teardown recurses once per level -- one worker stack, one process.
They all go through parse_json_bounded now, the body cap's own value and depth limits.
The same reasoning already refused deep bodies on the generation routes; frames and form
fields were the ones that never passed a gate.

Errors. ApiError::dump threw on invalid UTF-8, and URL-decoded params reach messages
without passing a JSON parser: a 404 becomes a 500, or worse a closed connection. The
dumps replace bad bytes instead of dying.

Logs. Session labels and echoed request text reach the log; an embedded newline forged a
line and an escape sequence drove the terminal reading it. log_sanitize filters control
bytes at the entry points -- labels, refusal logs, the exception handler -- while the
three loggers that print multi-line reports deliberately keep their newlines.

The browser. The dashboard page ships a CSP (its script talks only to its own origin)
and X-Frame-Options DENY; every response carries X-Content-Type-Options: nosniff. And
the loopback-only guards -- control-vector default, runtime LoRA, diagnostics -- now
treat a cross-origin browser as the remote client it is: a hostile page reaches them
through the victim's own browser, which is exactly loopback. Origin not matching Host
refuses; same-origin and non-browser traffic are untouched.

The gate. The API key's path exemptions are method-scoped (reads, plus the POST /ping of
the health-check convention), so an exemption can never ride a method no route answers.
An empty --api-key value is now a startup error rather than a server that looks guarded.

SSE. In the vendored httplib 0.46 an exception escaping a content provider aborts the
process; the provider ends the response instead. Upstream's 0.54 serve_guarded fixes the
cause -- the vendor lift is owed either way, and the catch is harmless belt until it.
This commit is contained in:
fl0l0u authored and StillDeadcode committed 2026-10-29 16:22:35 +01:00
1 parent a28221eb6a
commit b9c685a9c3
16 files changed
+245 -48

No files matched your search

+41 -5
View File
@@ -433,6 +433,14 @@ static std::string lower_ascii(std::string s) {
return s;
}
bool HttpRequest::is_cross_origin() const {
const std::string origin = header("Origin");
if (origin.empty()) return false;
const size_t at = origin.find("://");
const std::string auth = at == std::string::npos ? origin : origin.substr(at + 3);
return lower_ascii(auth) != lower_ascii(header("Host"));
}
/* The API key a browser's socket carries. A browser cannot set a header on a WebSocket, so
* OpenAI's browser clients offer it as a subprotocol, `openai-insecure-api-key.<key>`, beside
* `realtime`; the subprotocol chosen is never that one. Compared in constant time, as the header
@@ -486,6 +494,11 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
const size_t queued = (size_t)std::max<int64_t>(o.max_queued, 0);
svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); };
/* Every response, refusals and preflights included: no browser may second-guess the type.
* The JSON routes answer only the dashboard's own fetch, and a body sniffed as HTML would
* otherwise execute where it was only meant to be read. */
svr.set_default_headers({{"X-Content-Type-Options", "nosniff"}});
/* An exception escaping a handler would close the connection with no body; answer 500 with
* an error object instead. */
svr.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
@@ -494,7 +507,9 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
try { std::rethrow_exception(ep); }
catch (const std::exception& e) { what = e.what(); }
catch (...) {}
RAD_ERR("server: %s", what.c_str());
/* e.what() can carry request text (a path, a header): keep it off the log as an
* escape-sequence vector. */
RAD_ERR("server: %s", log_sanitize(what).c_str());
res.status = 500;
res.set_content(error_body(req.path, 500, "internal_server_error", what),
"application/json");
@@ -534,10 +549,17 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
/* The probe paths and the dashboard page are exempt. A load balancer cannot send a
* bearer token, and a browser opening the page cannot send a header; the page holds no
* data and sends the key on every data fetch. Everything else is guarded, including
* /tokenize, which vLLM leaves open (it only guards /v1). */
* /tokenize, which vLLM leaves open (it only guards /v1).
*
* The exemption follows the methods those paths actually answer — reads, plus the POST
* /ping of the health-check convention — so it cannot ride a method the router might
* one day put behind one of these paths. */
const std::string& p = hreq.path;
if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
p != "/dashboard") {
const std::string& m = hreq.method;
const bool reads = m == "GET" || m == "HEAD";
const bool probe = p == "/health" || p == "/v1/health" || p == "/" || p == "/dashboard";
const bool exempt = (reads && (probe || p == "/ping")) || (p == "/ping" && m == "POST");
if (!api_key.empty() && !exempt) {
if (!key_ok(hreq)) {
/* Logged in Server::error_response's format; the gate answers before the router. */
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
@@ -582,8 +604,22 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
hres.set_chunked_content_provider(
st->content_type,
[st](size_t /*offset*/, httplib::DataSink& sink) -> bool {
/* In the vendored 0.46 an exception escaping the provider unwinds the task queue
* and aborts the process (upstream's 0.54.0 serve_guarded fixed exactly this);
* until the lift moves, a throwing next() ends this response, not the server. */
std::string chunk;
bool more = st->next(chunk);
bool more = true;
try {
more = st->next(chunk);
} catch (const std::exception& e) {
RAD_ERR("server: stream provider threw: %s", log_sanitize(e.what()).c_str());
sink.done();
return true;
} catch (...) {
RAD_ERR("server: stream provider threw a non-standard exception");
sink.done();
return true;
}
if (!chunk.empty()) {
if (!sink.write(chunk.data(), chunk.size())) return false; /* peer gone */
}