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:
1 parent
a28221eb6a
commit
b9c685a9c3
16 files changed
+245
-48
No files matched your search
+8
-1
@@ -769,7 +769,14 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
else if (S("--host")) { if (!(v = need(i))) return RAD_E_INVAL; c->host = v; }
|
||||
else if (S("--port")) { if (!num(0, 65535, &c->port)) return RAD_E_INVAL; }
|
||||
else if (S("--api-key")) { if (!(v = need(i))) return RAD_E_INVAL; c->api_key = v; }
|
||||
else if (S("--api-key")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
/* An empty key is no key: --api-key "" or --api-key "$UNSET_VAR" must not start a
|
||||
* server that looks guarded and answers everything keyless. */
|
||||
if (!*v) { RAD_ERR("--api-key takes a non-empty key; an empty value guards nothing");
|
||||
return RAD_E_INVAL; }
|
||||
c->api_key = v;
|
||||
}
|
||||
else if (S("--served-model-name")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!*v) { RAD_ERR("--served-model-name takes a non-empty name"); return RAD_E_INVAL; }
|
||||
|
||||
@@ -29,6 +29,12 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...)
|
||||
* the first. */
|
||||
uint64_t log_last_line_ns();
|
||||
|
||||
/* A copy safe to interpolate into a log line: every byte below 0x20 but '\t', and DEL, becomes
|
||||
* '?'. Client-controlled text reaches the log — session labels, echoed request fields — and an
|
||||
* unfiltered newline forges a line while an ESC sequence drives the terminal that reads it.
|
||||
* Multi-byte UTF-8 is left alone; only control bytes are replaced. */
|
||||
std::string log_sanitize(const std::string& s);
|
||||
|
||||
/* Rank tags on log lines. Per-rank components (pools, planner, mover, sampler) print the same
|
||||
* line once per rank, so under TP each line needs its rank. LogRank sets the tag as a scope
|
||||
* because the printers are several layers down, where threading a rank argument through every
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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
@@ -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 */
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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)
|
||||
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -68,6 +68,15 @@ LogRank::~LogRank() { g_log_rank = prev_; }
|
||||
static std::atomic<uint64_t> g_last_line_ns{0};
|
||||
uint64_t log_last_line_ns() { return g_last_line_ns.load(std::memory_order_relaxed); }
|
||||
|
||||
std::string log_sanitize(const std::string& s) {
|
||||
std::string out = s;
|
||||
for (char& c : out) {
|
||||
const unsigned char b = (unsigned char)c;
|
||||
if ((b < 0x20 && b != '\t') || b == 0x7f) c = '?';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
|
||||
const char* base = std::strrchr(file, '/');
|
||||
base = base ? base + 1 : file;
|
||||
|
||||
+8
-3
@@ -2070,7 +2070,7 @@ by 0.002-0.003 nats.
|
||||
|---|---|---|
|
||||
| `--host ADDR` | 0.0.0.0 | listen address |
|
||||
| `--port N` | 8000 | listen port |
|
||||
| `--api-key KEY` | none | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6) |
|
||||
| `--api-key KEY` | none | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6); the key must be non-empty |
|
||||
| `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the loaded one serves it |
|
||||
| `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels, 14x14 on GLM-5.3). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card. A pass is not one tower invocation: inside it the tower batches at most 8 tiles per weight read, and the pass size may reduce that (4 tiles at the 64-pixel grid with the default 16384 patches); a picture contributes a separate pass per grid. See the concurrency notes for Unlimited-OCR (§5.17) |
|
||||
| `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the container's. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup |
|
||||
@@ -3594,11 +3594,16 @@ With a key, every request must carry `Authorization: Bearer KEY` (or Anthropic's
|
||||
or it is answered 401, `/tokenize` and `/server_info` included. Exempt are `/health`, `/v1/health` and
|
||||
`/ping`, because load balancers cannot send a bearer token, and the dashboard page (`/`,
|
||||
`/dashboard`), which holds no data: on a 401 it asks for the key, keeps it in the browser's storage
|
||||
and sends it on every data fetch.
|
||||
and sends it on every data fetch. The exemption follows those paths' methods -- reads, plus the
|
||||
`POST /ping` of the health-check convention -- so it cannot follow a method no route answers.
|
||||
An empty `--api-key` value is a startup error: it would guard nothing.
|
||||
|
||||
Without a key, `/diagnostics` answers only loopback clients (others get 403), because it describes
|
||||
the host: kernel, boot parameters, PCI layout, memory limits. Read it on the machine, or start the
|
||||
server with `--api-key`.
|
||||
server with `--api-key`. The same loopback-only rule covers the control-vector default and runtime
|
||||
LoRA loads, and a browser page on another origin does not qualify as a loopback client even when
|
||||
its own machine serves the port: that is how a hostile web page would reach these routes through a
|
||||
victim's browser, and a request that says `Origin: http://evil` is refused the way a remote one is.
|
||||
|
||||
The key is not encrypted in transit. On a network you do not control, bind to localhost behind a
|
||||
TLS-terminating reverse proxy:
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user