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

+3 -1
View File
@@ -502,7 +502,9 @@ HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
return error_response(err_not_implemented(
"the server was not given a diagnostics provider; this build has no engine attached"),
req.peer);
if (opt_.api_key.empty() && !req.peer_is_loopback()) {
if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) {
/* A cross-origin browser is not a loopback client even when its own machine serves
* this port: the drive-by that guard exists to refuse. */
ApiError e;
e.status = 403;
e.type = "permission_error";
+22 -8
View File
@@ -13,6 +13,7 @@
* collapsing while the pooled acceptance rate stays plausible.
*/
#include "server.h"
#include "oai.h"
#include "rad_internal.h"
@@ -57,8 +58,10 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) {
if (req.method == "POST") {
/* The default applies to every client's requests that name no choice, so a server
* started without --api-key takes the change from a loopback client only, as it does a
* runtime adapter load. */
if (opt_.api_key.empty() && !req.peer_is_loopback()) {
* runtime adapter load. A browser page on another origin does not qualify even when the
* victim's own browser makes it loopback: that is the drive-by this guard must refuse.
*/
if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) {
ApiError e;
e.status = 403;
e.type = "permission_error";
@@ -67,12 +70,12 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) {
"elsewhere";
return error_response(e, req.peer);
}
json body;
try {
body = json::parse(req.body.empty() ? "{}" : req.body);
} catch (const std::exception& e) {
return error_response(err_bad("body", std::string("not JSON: ") + e.what()), req.peer);
}
bool over = false, deep = false;
json body = parse_json_bounded(req.body.empty() ? "{}" : req.body, 0, &over, &deep);
if (body.is_discarded()) return error_response(err_bad("body", "not JSON"), req.peer);
if (over || deep)
return error_response(err_bad("body", "expected {\"enabled\": true|false} and "
"nothing deeper than that"), req.peer);
const auto it = body.find("enabled");
if (it == body.end() || !it->is_boolean())
return error_response(err_bad("enabled", "a boolean is required"), req.peer);
@@ -3669,6 +3672,17 @@ HttpResponse Server::handle_dashboard(const HttpRequest&) {
/* No caching: the page must match the binary's /stats shape, and a stale copy shows only
* blank panels. */
r.set_header("Cache-Control", "no-store");
/* The page is fixed markup that talks only to its own origin, and CSP is how that promise
* becomes enforceable: even a future markup bug could not phone an injected payload's
* findings home, and could not reach the key beyond this origin. script/style 'unsafe-inline'
* is the cost of shipping as one compiled-in literal with its own <style> and <script>;
* frame-ancestors keeps a hostile page from framing the Model view and clickjacking its
* guardrail toggle. */
r.set_header("Content-Security-Policy",
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
"connect-src 'self'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'; "
"form-action 'none'");
r.set_header("X-Frame-Options", "DENY");
return r;
}
+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 */
}
+5
View File
@@ -52,6 +52,11 @@ struct HttpRequest {
bool peer_gone() const { return closed && closed(); }
/* True for 127.0.0.0/8, ::1, an IPv4-mapped 127.x address, and an in-process request. */
bool peer_is_loopback() const;
/* True when the request comes from a browser on another origin: an `Origin` header whose
* authority differs from `Host`. Scripts send no Origin, so this never fires for curl or an
* SDK. Through a proxy that rewrites Host, every browser reads as cross-origin — which is
* exactly the case the "loopback-only" guards must not wave through. */
bool is_cross_origin() const;
};
struct HttpResponse {
+26 -6
View File
@@ -92,10 +92,13 @@ json form_value(const std::string& key, const std::string& v) {
if (v == "true" || v == "1") return json(true);
if (v == "false" || v == "0") return json(false);
}
/* `loras` as JSON text, or one adapter's name. */
/* `loras` as JSON text, or one adapter's name. Bounded like a request body: a form field
* under the body cap can be brackets alone, and the deep tree's teardown would take the
* process with it. Over-deep or over-budget reads as plain text, as a discarded parse did. */
if ((key == "loras" || key == "lora") && !v.empty() && (v[0] == '[' || v[0] == '{')) {
json j = json::parse(v, nullptr, false);
if (!j.is_discarded()) return j;
bool over = false, deep = false;
json j = parse_json_bounded(v, 0, &over, &deep);
if (!j.is_discarded() && !over && !deep) return j;
}
return json(v);
}
@@ -623,7 +626,16 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
src_px = std::move(src.rgba);
}
auto render = [&](const std::string& prompt, gen::Branch* out, ApiError* err) -> int {
auto render = [&](const std::string& prompt, const char* field, gen::Branch* out,
ApiError* err) -> int {
/* A prompt spelling the media marker would be scanned for pictures this request never
* uploaded, and the scan would walk off the item list: refuse the text, as the chat and
* embeddings paths refuse marker text (oai.cpp). */
if (prompt.find(RAD_MEDIA_MARKER) != std::string::npos) {
*err = err_bad(field, std::string("contains \"") + RAD_MEDIA_MARKER +
"\": it names a picture this request did not upload");
return RAD_E_INVAL;
}
std::string text = r.background == "transparent" && !info.tmpl_transparent.empty()
? replace_all(info.tmpl_transparent, "{prompt}", prompt)
: prompt;
@@ -651,6 +663,14 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
out->tokens.insert(out->tokens.end(), ids.begin(), ids.end());
}
if (at == std::string::npos) break;
if (mi >= items.size()) {
/* Unreachable for any request: the prompt text is refused above, so only a model
* template that spells the marker past its pictures could reach it. Belt for the
* day one does. */
*err = err_internal("the render template spells the media marker more times "
"than the request has pictures");
return RAD_E_STATE;
}
mm::Placed pl;
pl.item = items[mi++];
pl.tok = (int32_t)out->tokens.size();
@@ -716,8 +736,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
};
{
ApiError err;
if (render(r.prompt, &g->pos, &err) < 0) return error_response(err, req.peer);
if (r.has_neg && render(r.negative, &g->neg, &err) < 0)
if (render(r.prompt, "prompt", &g->pos, &err) < 0) return error_response(err, req.peer);
if (r.has_neg && render(r.negative, "negative_prompt", &g->neg, &err) < 0)
return error_response(err, req.peer);
}
+22 -10
View File
@@ -163,7 +163,11 @@ std::string ApiError::dump() const {
if (n_ctx >= 0) e["n_ctx"] = n_ctx;
json o;
o["error"] = e;
return o.dump();
/* A message can carry raw request text (a URL-decoded label, an echoed field name): dump
* must survive invalid UTF-8 by replacing it rather than throwing and turning a 404 into
* a 500. The JSON parsers refuse invalid UTF-8 in bodies, but URL-decoded params do not
* pass through one. */
return o.dump(-1, ' ', false, json::error_handler_t::replace);
}
ApiError err_bad(const std::string& param, const std::string& why) {
@@ -431,13 +435,16 @@ std::string str_or(const json& o, const char* k, const std::string& def = std::s
}
/* A conversation's label for /sessions: at most 128 bytes, cut at a UTF-8 character boundary
* because the label is serialised into JSON. */
* because the label is serialised into JSON. Control bytes are dropped at the door: the label
* is logged on release and shown on the dashboard, and an embedded ESC sequence would drive
* whatever terminal renders it. */
std::string session_label_of(const std::string& s) {
std::string t = log_sanitize(s);
constexpr size_t kMax = 128;
if (s.size() <= kMax) return s;
if (t.size() <= kMax) return t;
size_t cut = kMax;
while (cut > 0 && ((unsigned char)s[cut] & 0xC0) == 0x80) --cut;
return s.substr(0, cut);
while (cut > 0 && ((unsigned char)t[cut] & 0xC0) == 0x80) --cut;
return t.substr(0, cut);
}
/* One field under several spellings (OpenAI's, vLLM's, llama.cpp's), read as a number (double)
@@ -1053,8 +1060,11 @@ void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt) {
if (lim.reasoning_effort_map.empty()) return;
auto it = opt->template_kwargs.find("reasoning_effort");
if (it == opt->template_kwargs.end()) return;
const json v = json::parse(it->second, nullptr, false);
if (!v.is_string()) return;
/* The kwarg is client text re-parsed as JSON: bound it like a body, a string of brackets
* would overflow this worker's stack when the tree comes down. */
bool over = false, deep = false;
const json v = parse_json_bounded(it->second, 0, &over, &deep);
if (over || deep || !v.is_string()) return;
auto m = lim.reasoning_effort_map.find(v.get<std::string>());
if (m == lim.reasoning_effort_map.end()) return;
if (m->second == "none" || m->second == "minimal") {
@@ -1071,9 +1081,11 @@ ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, in
* variable was in the render. The set is more actionable than the template's traceback. */
auto it = opt.template_kwargs.find("reasoning_effort");
if (it != opt.template_kwargs.end() && !lim.reasoning_efforts.empty()) {
const json v = json::parse(it->second, nullptr, false);
bool over = false, deep = false;
const json v = parse_json_bounded(it->second, 0, &over, &deep);
const std::vector<std::string>& set = lim.reasoning_efforts;
if (v.is_string() && std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
if (!over && !deep && v.is_string() &&
std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
std::string list;
for (size_t i = 0; i < set.size(); ++i)
list += (i ? (i + 1 == set.size() ? " and " : ", ") : "") + ("'" + set[i] + "'");
@@ -3782,7 +3794,7 @@ std::string anthropic_error_body(const ApiError& e) {
json o;
o["type"] = "error";
o["error"] = json{ { "type", anthropic_error_type(e.status) }, { "message", e.message } };
return o.dump();
return o.dump(-1, ' ', false, json::error_handler_t::replace); /* see ApiError::dump */
}
AnthropicStream::AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser)
+7 -2
View File
@@ -38,6 +38,7 @@
*/
#include "server.h"
#include "server_priv.h"
#include "oai.h"
#include "mm/processor.h"
#include "mm/resample.h"
@@ -658,8 +659,12 @@ bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
auto handle = [&](const std::string& msg, bool binary) {
if (binary) return append_pcm((const uint8_t*)msg.data(), msg.size(), nullptr);
const ojson j = ojson::parse(msg, nullptr, /*allow_exceptions=*/false);
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string())
/* Bounded like a request body: 2 MiB of brackets is a legal WebSocket frame, and the
* recursive teardown of a deep tree would take the whole process down with it. */
bool over = false, deep = false;
const ojson j = parse_json_bounded(msg, 0, &over, &deep);
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("type") ||
!j["type"].is_string())
return error("invalid_request_error", "invalid_json",
"a client event is a JSON object with a string `type`", "", nullptr);
const std::string type = j["type"].get<std::string>();
+16 -9
View File
@@ -400,13 +400,15 @@ static std::string from_peer(const std::string& peer) {
HttpResponse Server::error_response(const ApiError& e, const std::string& peer, ApiShape shape) {
metrics_.observe_http(e.status);
/* Log every refusal with status, type, message and peer: 4xx at info (the client's doing),
* 5xx as a warning (ours). */
* 5xx as a warning (ours). The message can echo request text (a URL-decoded label, a field
* name), so the log copy is control-byte-clean; the wire copy keeps the bytes. */
const std::string msg = log_sanitize(e.message), typ = log_sanitize(e.type);
if (e.status >= 500)
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
e.message.c_str());
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, typ.c_str(),
msg.c_str());
else
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
e.message.c_str());
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, typ.c_str(),
msg.c_str());
HttpResponse r = HttpResponse::json_body(
e.status, shape == ApiShape::Anthropic ? anthropic_error_body(e) : e.dump());
if (e.status == 429) r.set_header("Retry-After", std::to_string(opt_.retry_after_s));
@@ -1912,7 +1914,6 @@ HttpResponse Server::handle_loras(const HttpRequest& req) {
}
HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
using json = nlohmann::json;
auto fail = [&](int status, const char* type, const std::string& msg) {
ApiError e;
e.status = status;
@@ -1923,12 +1924,18 @@ HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
if (!opt_.lora_load || !opt_.lora_unload)
return fail(404, "not_found_error", "this server was started without runtime LoRA (--lora or "
"--max-loras)");
if (opt_.api_key.empty() && !req.peer_is_loopback())
if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin()))
/* A cross-origin browser counts as neither loopback nor local: the victim's own browser
* is loopback to this port, and that is exactly how a hostile page would reach here. */
return fail(403, "permission_error", "loading an adapter reads a path on this machine, and a "
"server started without --api-key takes it only from a "
"loopback client");
const json j = json::parse(req.body, nullptr, false);
if (j.is_discarded() || !j.is_object() || !j.contains("lora_name") || !j["lora_name"].is_string())
/* Bounded like a generation body: this parses client text the same way, and a deep bracket
* nest would overflow this worker's stack when the tree is torn down. */
bool over = false, deep = false;
const json j = parse_json_bounded(req.body, 0, &over, &deep);
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("lora_name") ||
!j["lora_name"].is_string())
return fail(400, "invalid_request_error", "the body must be a JSON object with lora_name");
const std::string name = j["lora_name"].get<std::string>();
if (name.empty() || name == opt_.model_id)
+7 -2
View File
@@ -27,6 +27,7 @@
*/
#include "server.h"
#include "server_priv.h"
#include "oai.h"
#include "text_split.h"
#include "gen/audio.h"
@@ -279,8 +280,12 @@ bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) {
"session.close");
return false;
}
const json j = json::parse(msg, nullptr, /*allow_exceptions=*/false);
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string()) {
/* Bounded like a request body: a deep bracket nest is a legal frame, and tearing its
* tree down recurses once per level. */
bool over = false, deep = false;
const json j = parse_json_bounded(msg, 0, &over, &deep);
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("type") ||
!j["type"].is_string()) {
error("a client message is a JSON object with a string `type`");
return false;
}