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

+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)