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

+19
View File
@@ -4747,6 +4747,10 @@ TEST(the_control_vector_field_overrides_the_default_or_is_refused) {
CHECK(!def);
/* Refuses a body that names no boolean rather than guessing. */
CHECK_EQ(f.post("/admin/control-vector", R"({"enabled":"yes"})").status, 400);
/* And a body that is brackets alone: valid JSON, nested deeper than any stack wants to
* tear down, parsed bounded and refused. */
CHECK_EQ(f.post("/admin/control-vector",
std::string(20000, '[') + std::string(20000, ']')).status, 400);
/* Without --api-key a change comes from loopback only; reading it is not restricted. */
HttpRequest q;
q.method = "POST";
@@ -4758,6 +4762,21 @@ TEST(the_control_vector_field_overrides_the_default_or_is_refused) {
q.peer = "127.0.0.1:50122";
CHECK_EQ(f.srv->router().dispatch(q).status, 200);
CHECK(def);
/* A browser page on another origin is not a loopback client, even though its own
* browser makes the request arrive loopback: defeating the guard that way is exactly
* what the drive-by would do. Same-origin browser traffic still passes. */
HttpRequest x;
x.method = "POST";
x.path = "/admin/control-vector";
x.body = R"({"enabled":false})";
x.peer = "127.0.0.1:50122";
x.headers["Origin"] = "http://evil.test";
x.headers["Host"] = "127.0.0.1:8080";
CHECK_EQ(f.srv->router().dispatch(x).status, 403);
CHECK(def);
x.headers["Origin"] = "http://127.0.0.1:8080";
CHECK_EQ(f.srv->router().dispatch(x).status, 200);
CHECK(!def);
HttpRequest g2;
g2.path = "/admin/control-vector";
g2.peer = "192.168.1.20:50122";
+20
View File
@@ -299,6 +299,26 @@ TEST(a_speech_session_refuses_what_it_cannot_take_and_goes_on) {
CHECK(!s.conn.closed);
}
/* A frame that is brackets alone, nested tens of thousands deep, is still valid JSON: parsing it
* into a tree and tearing that tree down both recurse once per level, so the session parses it
* bounded — the tree never outgrows the stack — answers its invalid-message error, and goes on.
*/
TEST(a_deeply_nested_frame_is_refused_not_fatal) {
Stream s;
const std::string deep = std::string(20000, '[') + std::string(20000, ']');
{
std::lock_guard<std::mutex> lk(s.conn.m);
s.conn.in.push_back(deep);
s.conn.cv.notify_all();
}
CHECK(!s.conn.wait_for("error").is_null());
CHECK(!s.conn.closed);
s.config();
s.text("Still here.");
s.done();
REQUIRE(!s.conn.wait_for("session.done").is_null());
}
/* A sentence the generator refuses or fails is an error and an audio.done saying so; the next
* sentence is spoken as usual. */
TEST(a_failed_sentence_says_so_and_the_next_is_spoken) {
+26 -1
View File
@@ -261,7 +261,9 @@ TEST(the_api_key_gate_holds_every_route_but_the_probes) {
REQUIRE(s.srv->port() > 0);
s.sched.hang = false;
s.sched.reply = "ok";
auto ask = [&](const std::string& req) { return ::ask(s, req); };
auto ask = [&](const std::string& req, bool head_only = false) {
return ::ask(s, req, head_only);
};
for (const char* h : { "", "Authorization: Bearer wrong\r\n", "X-Api-Key: wrong\r\n",
"Authorization: k\r\n", "Authorization: Basic k\r\n" }) {
const Reply r = ask(get("/v1/models", h));
@@ -279,6 +281,16 @@ TEST(the_api_key_gate_holds_every_route_but_the_probes) {
}
for (const char* p : { "/health", "/v1/health", "/ping", "/", "/dashboard" })
CHECK_EQ(ask(get(p)).status, 200);
/* The page says what bounds it: a CSP that lets its own script talk only to this origin and
* keeps it out of a frame, and a type no browser may second-guess — the last on every
* response, refusals included. */
const Reply page = ask(get("/"));
CHECK(has(page.header("Content-Security-Policy"), "frame-ancestors 'none'"));
CHECK(has(page.header("Content-Security-Policy"), "connect-src 'self'"));
CHECK_EQ(page.header("X-Frame-Options"), std::string("DENY"));
CHECK_EQ(page.header("X-Content-Type-Options"), std::string("nosniff"));
CHECK_EQ(ask(get("/stats", "Authorization: Bearer k\r\n")).header("X-Content-Type-Options"),
std::string("nosniff"));
CHECK_EQ(ask(get("/metrics")).status, 401);
CHECK_EQ(ask(get("/stats")).status, 401);
CHECK_EQ(ask(post("/tokenize", R"({"prompt":"a"})")).status, 401);
@@ -298,6 +310,19 @@ TEST(the_api_key_gate_holds_every_route_but_the_probes) {
const Reply big = ask("POST /v1/completions HTTP/1.1\r\nHost: t\r\nContent-Type: application/json\r\n"
"Content-Length: 100000000\r\n\r\n");
CHECK_EQ(big.status, 401);
/* The exemption is a closed set of decoded paths and methods. Paths that only reach a
* guarded route after the router's own matching (empty segments collapse there, dot segments
* resolve nowhere) pay the key; and so does any method on an exempt path that no route
* answers, so the exemption can never ride a future mutating route. */
for (const char* p : { "//stats", "/%2Fstats", "/dashboard/../sessions", "/stats/", "/Stats",
"/stats;x", "/health//", "//health", "/HEALTH" })
CHECK_EQ(ask(get(p)).status, 401);
CHECK_EQ(ask("POST / HTTP/1.1\r\nHost: t\r\nContent-Length: 0\r\n\r\n").status, 401);
CHECK_EQ(ask("DELETE /health HTTP/1.1\r\nHost: t\r\n\r\n").status, 401);
/* POST /ping is the health-check convention and stays exempt, as every read on an exempt
* path does. */
CHECK_EQ(ask("POST /ping HTTP/1.1\r\nHost: t\r\nContent-Length: 0\r\n\r\n").status, 200);
CHECK_EQ(ask("HEAD / HTTP/1.1\r\nHost: t\r\n\r\n", /*head_only=*/true).status, 200);
}
/* A refusal the transport writes itself on an Anthropic path (the key gate's 401, a body over