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

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