From b6acbd69e475b064f61c76ef7dbdea4e22956394 Mon Sep 17 00:00:00 2001 From: fl0l0u Date: Fri, 30 Oct 2026 21:40:32 +0000 Subject: [PATCH] server: name the caller a vouched proxy carried, without arming the guard An operator running radiance behind a reverse proxy sees one address in every log line: the proxy's. --trusted-proxy CIDR (repeatable) vouches for the networks whose sockets may say who they carried. An X-Forwarded-For from inside a vouched network is walked from the right: vouched hops are skipped, the first address no vouched CIDR covers is the caller, a chain of only vouched hops ends at its leftmost, and anything else falls back to the socket. From an unvouched socket the header names no one, because it has not been vouched for. Attribution is not authority, and the split that keeps them apart is mechanical. HttpRequest carries `peer`, the attributed caller, sanitized where it is built because a named address arrives in a header and the log keeps no client text otherwise -- and `raw_peer`, the socket as the kernel saw it, which is now the only address peer_is_loopback() reads. A proxy on loopback therefore hands the keyless loopback-only routes to none of its clients; it only names them where the proxy used to stand. transport_test pins both halves: the walk at the unit level, and over a real socket that a vouched proxy plus X-Forwarded-For leaves the loopback guard answering 200 and the cross-origin 403 untouched. httplib's own set_trusted_proxies -- new this side of the vendor bump -- is deliberately unarmed. It rewrites req.remote_addr, the very field the guards would read as the socket peer, so one over-broad vouched network would move the guard rather than the log line. Radiance reads the header itself, and ip_in_cidr refuses across families: a vouched ::ffff:0:0/96 vouches for no IPv4 socket. Config rejects anything but a numeric network with a prefix at startup, because a typo there would silently unvouch a proxy; the refusals the transport answers before the router log the attributed caller too, so the audit trail stays one line per request whoever the socket belongs to. --- core/config.cpp | 17 ++++ core/engine.cpp | 1 + core/rad_core.h | 4 + core/server/http.cpp | 173 ++++++++++++++++++++++++++++++++++----- core/server/http.h | 41 +++++++++- core/server/server.cpp | 1 + core/server/server.h | 3 + docs/GUIDE.md | 15 ++++ tests/config_test.cpp | 17 ++++ tests/server_test.cpp | 10 +++ tests/transport_test.cpp | 92 +++++++++++++++++++++ 11 files changed, 352 insertions(+), 22 deletions(-) diff --git a/core/config.cpp b/core/config.cpp index 78133a37..b0c63b42 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -8,6 +8,7 @@ #include "format/rope_override.h" #include "sample/host_ref.h" #include "server/oai.h" +#include "server/http.h" #include "diag/diag.h" #include "util/kernel_list.h" #include "place/planner.h" @@ -220,6 +221,9 @@ static const Flag g_flags[] = { { "--allow-host", "NAME", "a Host name the keyless loopback-only routes (/diagnostics,\n" " /admin/control-vector, the LoRA and session admin) accept besides\n" " localhost; repeatable" }, + { "--trusted-proxy", "CIDR", "a network whose sockets may name the client behind them via\n" + " X-Forwarded-For, for the log; vouching changes attribution,\n" + " never access; repeatable" }, { "--served-model-name", "NAME", "the model id /v1/models lists and responses carry; default the container's name" }, { "--mm-max-patches", "N", "patches one encoder pass carries, and so the largest image (a patch is 16x16\n" "pixels). Default `auto`: 16384 when the container carries a vision tower. 0\n" @@ -850,6 +854,15 @@ int config_parse(int argc, char** argv, Config* c) { if (!*v) { RAD_ERR("--allow-host takes a non-empty name"); return RAD_E_INVAL; } c->allow_hosts.emplace_back(v); } + else if (S("--trusted-proxy")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!server::cidr_valid(v)) { + RAD_ERR("--trusted-proxy takes a numeric network with a prefix length, like " + "127.0.0.0/8 or ::1/128 (no brackets, no bare address), got '%s'", v); + return RAD_E_INVAL; + } + c->trusted_proxies.emplace_back(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; } @@ -1380,6 +1393,10 @@ const ShowRow kShow[] = { std::string o; for (const std::string& h : c.allow_hosts) o += (o.empty() ? "" : ",") + h; return o.empty() ? std::string("the loopback names only") : o; } }, + { "--trusted-proxy", [](const Config& c) { + std::string o; + for (const std::string& p : c.trusted_proxies) o += (o.empty() ? "" : ",") + p; + return o.empty() ? std::string("no socket vouches for a caller") : o; } }, { "--served-model-name", [](const Config& c) { return or_none(c.served_model_name, "the container's name"); } }, { "--mm-max-patches", [](const Config& c) { return c.mm_max_patches < 0 ? std::string("auto") : num(c.mm_max_patches); } }, { "--image-gen-max-pixels", [](const Config& c) { return c.image_gen_max_pixels > 0 ? num(c.image_gen_max_pixels) : std::string("the model's"); } }, diff --git a/core/engine.cpp b/core/engine.cpp index 651074a8..83d8d62f 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2639,6 +2639,7 @@ int Engine::run_server() { o.port = cfg_.port; o.api_key = cfg_.api_key; o.local_hosts = cfg_.allow_hosts; + o.trusted_proxies = cfg_.trusted_proxies; o.max_seqs = cfg_.max_seqs; /* `n` fans one request out over the batch, so the default scales with --max-num-seqs; the * floor of 8 keeps a small batch from refusing what it would queue. */ diff --git a/core/rad_core.h b/core/rad_core.h index 83407b1b..b92a1d5b 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -1057,6 +1057,10 @@ struct Config { /* --allow-host, repeatable: Host names the keyless loopback-only routes accept beside the * loopback names themselves, for operators who reach the box by another name. */ std::vector allow_hosts; + /* --trusted-proxy, repeatable: CIDRs whose sockets may vouch for the caller behind them + * through X-Forwarded-For. The vouched address names who the log and audit talk about -- + * it grants nothing: loopback, the Host name and the key stay the guards' whole world. */ + std::vector trusted_proxies; /* --served-model-name: the id /v1/models lists, a response names when its request named none, * and the metrics carry. Empty takes the container's own name. A request may still name any * model: one model is loaded and every request is served by it. */ diff --git a/core/server/http.cpp b/core/server/http.cpp index 3ef8c323..bb61a27a 100644 --- a/core/server/http.cpp +++ b/core/server/http.cpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include #include #include #include @@ -47,10 +49,12 @@ std::string HttpRequest::param(const std::string& k, const std::string& def) con } bool HttpRequest::peer_is_loopback() const { - if (peer.empty()) return true; + /* The socket, never the attributed peer: `peer` is whatever a vouched proxy said, and a + * guard that read it would let a proxy hand out loopback to the world. */ + if (raw_peer.empty()) return true; /* "addr:port", where an IPv6 address carries colons of its own: the port is after the last. */ - const size_t colon = peer.rfind(':'); - std::string addr = colon == std::string::npos ? peer : peer.substr(0, colon); + const size_t colon = raw_peer.rfind(':'); + std::string addr = colon == std::string::npos ? raw_peer : raw_peer.substr(0, colon); if (addr.size() >= 2 && addr.front() == '[' && addr.back() == ']') addr = addr.substr(1, addr.size() - 2); in_addr v4{}; @@ -61,6 +65,115 @@ bool HttpRequest::peer_is_loopback() const { return IN6_IS_ADDR_V4MAPPED(&v6) && v6.s6_addr[12] == 127; } +/* The parsed form of one "--trusted-proxy CIDR": network, prefix length, family. */ +namespace { +struct Cidr { + bool ok = false; + bool v6 = false; + uint8_t net[16] = {}; + int bits = 0; +}; + +Cidr parse_cidr(const std::string& cidr) { + Cidr c; + const size_t slash = cidr.find('/'); + if (slash == std::string::npos || slash == 0 || slash + 1 >= cidr.size()) return c; + const std::string net = cidr.substr(0, slash); + const std::string pfx = cidr.substr(slash + 1); + if (pfx.find_first_not_of("0123456789") != std::string::npos || pfx.size() > 3) return c; + const long bits = std::strtol(pfx.c_str(), nullptr, 10); + in_addr v4{}; + in6_addr v6{}; + if (inet_pton(AF_INET, net.c_str(), &v4) == 1) { + if (bits < 0 || bits > 32) return c; + c.ok = true; c.v6 = false; c.bits = (int)bits; + std::memcpy(c.net, &v4, 4); + return c; + } + if (inet_pton(AF_INET6, net.c_str(), &v6) == 1) { + if (bits < 0 || bits > 128) return c; + c.ok = true; c.v6 = true; c.bits = (int)bits; + std::memcpy(c.net, &v6, 16); + } + return c; +} + +/* Numeric address (no port, no zone) into its bytes; false if it is anything else. */ +bool parse_addr(const std::string& addr, bool* v6, uint8_t* out) { + in_addr a4{}; + if (inet_pton(AF_INET, addr.c_str(), &a4) == 1) { + *v6 = false; + std::memcpy(out, &a4, 4); + return true; + } + in6_addr a6{}; + if (inet_pton(AF_INET6, addr.c_str(), &a6) == 1) { + *v6 = true; + std::memcpy(out, &a6, 16); + return true; + } + return false; +} +} // namespace + +bool cidr_valid(const std::string& cidr) { return parse_cidr(cidr).ok; } + +bool ip_in_cidr(const std::string& addr, const std::string& cidr) { + const Cidr c = parse_cidr(cidr); + uint8_t a[16]; + bool v6 = false; + if (!c.ok || !parse_addr(addr, &v6, a) || v6 != c.v6) return false; + /* Families must agree. inet_pton does not map: an IPv4 socket is not inside an IPv6 + * network that happens to embed the same bytes, so a vouched ::ffff:0:0/96 does not + * vouch for 1.2.3.4 -- an operator who means both writes both. */ + int left = c.bits; + const int len = v6 ? 16 : 4; + for (int i = 0; i < len && left > 0; ++i) { + const int b = left >= 8 ? 8 : left; + const unsigned mask = (0xffu << (8 - b)) & 0xffu; + if (((a[i] ^ c.net[i]) & mask) != 0) return false; + left -= b; + } + return true; +} + +std::string attributed_client(const std::string& raw_addr, const std::string& xff, + const std::vector& trusted) { + if (xff.empty() || trusted.empty()) return raw_addr; + /* The socket first: a peer no operator vouched for gets no say in who it claims to be. */ + bool vouched = false; + for (const std::string& cidr : trusted) + if (ip_in_cidr(raw_addr, cidr)) { vouched = true; break; } + if (!vouched) return raw_addr; + + /* Split the chain; a request may carry the header once with a comma list, and this reads + * the first copy (a duplicate X-Forwarded-For is two chains and no honest reading). */ + std::vector hops; + size_t i = 0; + while (i <= xff.size()) { + size_t comma = xff.find(',', i); + if (comma == std::string::npos) comma = xff.size(); + size_t b = xff.find_first_not_of(" \t", i); + size_t e = xff.find_last_not_of(" \t", comma ? comma - 1 : 0); + if (b != std::string::npos && e != std::string::npos && b < comma) + hops.push_back(xff.substr(b, e - b + 1)); + i = comma + 1; + } + if (hops.empty()) return raw_addr; + + /* Right to left: each vouched hop is one more proxy the operator named, and its neighbour + * to the left is who that proxy saw. The first name no vouched CIDR covers is the caller; + * a chain of only vouched hops bottoms out at the leftmost, the original client as the + * outermost proxy saw it. */ + for (size_t h = hops.size(); h-- > 0;) { + bool covered = false; + for (const std::string& cidr : trusted) + if (ip_in_cidr(hops[h], cidr)) { covered = true; break; } + if (!covered) return hops[h]; + } + return hops.front(); +} + int idle_workers(int n_threads) { const int n = n_threads > 0 ? n_threads : (int)std::thread::hardware_concurrency(); return std::max(n, 4); @@ -544,6 +657,25 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { const std::string api_key = o.api_key; const bool cors = o.cors; + const std::vector trusted = o.trusted_proxies; + /* The two addresses every bridged request carries: the socket as the kernel saw it, and + * the caller the vouched chain names. Only the first is ever read for authority. The + * attributed name arrives in a header, so it is sanitized where it is made — `peer` is + * log-facing text by construction, and a guard must never meet it anyway. */ + auto fill_peers = [trusted](HttpRequest& req, const httplib::Request& hreq) { + req.raw_peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port); + req.peer = log_sanitize(attributed_client(hreq.remote_addr, + hreq.get_header_value("X-Forwarded-For"), + trusted)) + + ":" + std::to_string(hreq.remote_port); + }; + /* The same identity for refusals answered before any HttpRequest exists (the key gate, the + * duplicated security header): one audit trail, whoever the socket belongs to. */ + auto who = [trusted](const httplib::Request& q) { + return log_sanitize(attributed_client(q.remote_addr, + q.get_header_value("X-Forwarded-For"), trusted)) + + ":" + std::to_string(q.remote_port); + }; /* The headers a cross-origin client sends: the body type, either form of the API key, and the * anthropic-version and anthropic-beta headers of Anthropic's clients, which nothing reads. */ static const char* const kCorsHeaders = @@ -566,8 +698,8 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { }; /* What a request must pass before its body is read, so a refused one never has it buffered. */ - auto gate = [api_key, cors, key_ok](const httplib::Request& hreq, - httplib::Response& hres) -> bool { + auto gate = [api_key, cors, key_ok, who](const httplib::Request& hreq, + httplib::Response& hres) -> bool { if (cors) { hres.set_header("Access-Control-Allow-Origin", "*"); hres.set_header("Access-Control-Allow-Headers", kCorsHeaders); @@ -589,8 +721,8 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { 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", - hreq.remote_addr.c_str(), hreq.remote_port); + RAD_INFO("req refused from %s -> 401 authentication_error: invalid api key", + who(hreq).c_str()); hres.status = 401; hres.set_content(error_body(p, 401, "authentication_error", "invalid api key"), "application/json"); @@ -600,7 +732,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { return true; }; - auto bridge = [&router](const httplib::Request& hreq, std::string body, + auto bridge = [&router, fill_peers](const httplib::Request& hreq, std::string body, httplib::Response& hres, std::vector form = {}) { HttpRequest req; /* HEAD is GET without the body, which httplib leaves off the wire. */ @@ -608,7 +740,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { req.path = hreq.path; req.body = std::move(body); req.form = std::move(form); - req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port); + fill_peers(req, hreq); req.t_received_ns = std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()).count(); for (auto& h : hreq.headers) req.headers[h.first] = h.second; @@ -631,9 +763,10 @@ 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. */ + /* The vendored 0.64 wraps this whole side of the socket in serve_guarded, so a + * throwing next() can no longer unwind the task queue; the catch stays as the + * place this file says what happened -- guarded or not, an unlogged stream + * death is one nobody can debug. */ std::string chunk; bool more = true; try { @@ -747,10 +880,10 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { * ways a socket client can carry it, and, with CORS off, by its Origin: a browser lets any * page open a socket to any host, and CORS is what would otherwise keep another site's page * out. True when the upgrade may proceed; false with the refusal in `s`. */ - auto socket_gate = [api_key, cors, key_ok](const httplib::Request& q, - httplib::Response& s) -> bool { + auto socket_gate = [api_key, cors, key_ok, who](const httplib::Request& q, + httplib::Response& s) -> bool { auto refuse = [&](int status, const char* type, const std::string& why) { - RAD_INFO("req refused from %s:%d -> %d %s: %s", q.remote_addr.c_str(), q.remote_port, + RAD_INFO("req refused from %s -> %d %s: %s", who(q).c_str(), status, type, why.c_str()); s.status = status; s.set_content(error_body(q.path, status, type, why), "application/json"); @@ -773,11 +906,11 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { const SocketHandler h = *router.socket_for(path); svr.WebSocket( path, - [h](const httplib::Request& hreq, httplib::ws::WebSocket& ws) { + [h, fill_peers](const httplib::Request& hreq, httplib::ws::WebSocket& ws) { HttpRequest req; req.method = hreq.method; req.path = hreq.path; - req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port); + fill_peers(req, hreq); for (auto& hd : hreq.headers) req.headers[hd.first] = hd.second; for (auto& p : hreq.params) req.query[p.first] = p.second; HttplibConn conn(ws); @@ -805,7 +938,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { * it with a body to read: httplib hands its body reader only to a route's handler, so those * routes are registered below and left to it. A request no route takes is answered without * its body being read. */ - svr.set_pre_routing_handler([&router, gate, socket_gate, bridge, + svr.set_pre_routing_handler([&router, gate, socket_gate, bridge, who, preflight](const httplib::Request& q, httplib::Response& s) { /* A security-relevant header sent twice is a request built to be read two ways: this * server reads the first copy, a proxy in front may read the last or join them, and any @@ -815,8 +948,8 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { * is case-insensitive, so `Authorization` beside `authorization` counts as two. */ for (const char* h : {"Host", "Authorization", "X-Api-Key", "Origin"}) { if (q.get_header_value_count(h) > 1) { - RAD_INFO("req refused from %s:%d -> 400 invalid_request_error: duplicate %s header", - q.remote_addr.c_str(), q.remote_port, h); + RAD_INFO("req refused from %s -> 400 invalid_request_error: duplicate %s header", + who(q).c_str(), h); s.status = 400; s.set_content(error_body(q.path, 400, "invalid_request_error", std::string("the ") + h + " header was sent twice"), diff --git a/core/server/http.h b/core/server/http.h index ee54a969..6445ef1d 100644 --- a/core/server/http.h +++ b/core/server/http.h @@ -36,7 +36,16 @@ struct HttpRequest { std::map headers; std::map query; std::map params; /* from a ":name" route segment */ - std::string peer; /* "addr:port"; empty in-process */ + std::string peer; /* "addr:port"; empty in-process. The + ATTRIBUTED caller: with --trusted-proxy + and an X-Forwarded-For, the address the + proxy chain names; the port is always + the last hop's -- the chain carries no + port. For logs and audit, never for + authority. */ + std::string raw_peer; /* "addr:port" of the socket peer as the + kernel saw it; empty in-process. The + only address the guards read. */ /* Steady-clock nanoseconds at which the whole body had arrived. The server's own time for * the request starts here, before parsing, so network time is excluded. -1 in-process. */ int64_t t_received_ns = -1; @@ -50,7 +59,9 @@ struct HttpRequest { /* The first form part named `k` (a field or a file), or null. */ const FormPart* part(const std::string& k) const; 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. */ + /* True when raw_peer is 127.0.0.0/8, ::1, an IPv4-mapped 127.x address, or absent (the + * in-process request). Reads the socket, never the attributed peer: a proxy an operator + * vouched for can name any caller it likes; that changes the log line, not the guard. */ 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 @@ -68,6 +79,28 @@ struct HttpRequest { bool host_is_loopback() const; }; +/* Whether `cidr` is in the one form --trusted-proxy takes: numeric "addr/prefix", prefix within + * its family. Config refuses anything else at startup, so a typo cannot silently unvouch a + * proxy; ip_in_cidr treats the same rejection as simply no match. */ +bool cidr_valid(const std::string& cidr); + +/* True when the numeric address `addr` (no port, no zone) falls inside `cidr`. Families must + * agree: this is not RFC 6052 translation, an IPv4 peer is not inside an IPv6 network that + * happens to embed it. */ +bool ip_in_cidr(const std::string& addr, const std::string& cidr); + +/* The caller a proxy chain vouches for. `raw_addr` is the socket peer (no port), `xff` the + * request's X-Forwarded-For value ("" when there is none), `trusted` the vouched CIDRs. + * Nothing is read from the header unless the socket itself belongs to a vouched CIDR -- an + * unvouched peer can name any address it likes and names none. Then the chain is walked from + * the right (the hop nearest us, which our vouched proxy appended): the first entry that no + * vouched CIDR covers is the caller; a chain of only vouched hops ends at its leftmost entry, + * the original client as the outermost proxy saw it. Malformed entries stop the walk where + * they stand -- the chain is reported, not interpreted, and the log sanitizer owns the bytes. + * Fallback is `raw_addr`, always. */ +std::string attributed_client(const std::string& raw_addr, const std::string& xff, + const std::vector& trusted); + struct HttpResponse { int status = 200; std::string content_type = "application/json; charset=utf-8"; @@ -203,6 +236,10 @@ struct TransportOptions { size_t max_inflight_body_bytes = 0; std::string api_key; /* "" disables the check */ bool cors = true; + /* --trusted-proxy, repeatable: CIDRs whose sockets may vouch for their caller through + * X-Forwarded-For. Empty: no socket vouches for anything and peer always equals raw_peer. + * Attribution rewrites the logged caller, never an authority -- see HttpRequest::peer. */ + std::vector trusted_proxies; }; /* Idle workers kept for TransportOptions::n_threads: that many, one per hardware thread for 0, diff --git a/core/server/server.cpp b/core/server/server.cpp index f413bb46..84432396 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -277,6 +277,7 @@ int Server::run() { t.keep_alive_timeout_s = opt_.keep_alive_timeout_s; t.max_body_bytes = opt_.max_body_bytes; t.max_inflight_body_bytes = opt_.max_inflight_body_bytes; + t.trusted_proxies = opt_.trusted_proxies; return transport_.serve(router_, t); } diff --git a/core/server/server.h b/core/server/server.h index f22e36ec..582a763c 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -186,6 +186,9 @@ struct ServerOptions { /* Extra Host authorities the keyless "loopback only" guards accept (--allow-host): names an * operator reaches the box by that the loopback IP check cannot know. Case-insensitive. */ std::vector local_hosts; + /* --trusted-proxy: CIDRs whose sockets may name the client behind them via X-Forwarded-For. + * Attribution for the log; no guard reads it. See TransportOptions::trusted_proxies. */ + std::vector trusted_proxies; bool cors = true; /* The transport's timeouts and body bound. See TransportOptions. */ diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 7cc5ba1a..2c1fc16e 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2130,6 +2130,7 @@ by 0.002-0.003 nats. | `--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 | | `--api-key-env NAME` | — | read the API key from the environment variable `NAME` instead of the command line, where every process on the machine reads it in `ps`; an unset or empty `NAME` refuses startup like an empty `--api-key` | | `--allow-host NAME` | — | a `Host` name the keyless loopback-only routes accept besides the loopback names; repeatable (§6.6) | +| `--trusted-proxy CIDR` | — | a network whose sockets may name the client behind them, via `X-Forwarded-For`, for the log; vouching changes attribution, never access; repeatable (§6.6) | | `--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 | @@ -3836,6 +3837,20 @@ tunnel pass. If you reach the box by another name from the box itself, list it: (repeatable). A local user on the server's own console is admitted either way — the boundary is against remote callers, not against whoever owns the machine. +Behind a reverse proxy every socket arrives as the proxy, and every log line names it instead of +the caller. `--trusted-proxy 127.0.0.0/8` (repeatable; a numeric network with a prefix, like +`::1/128`) vouches for those networks: a request whose socket belongs to a vouched network is +attributed to the client it names, reading `X-Forwarded-For` from the right and skipping vouched +hops — the first address no vouched network covers is the caller, a chain of only vouched hops +ends at its leftmost, and anything else falls back to the socket. Attribution is not authority: +the guards above read the socket and never the named address, so a proxy on loopback hands the +loopback-only routes to none of its clients — it only puts their addresses in the log where the +proxy's would stand. An `X-Forwarded-For` from an unvouched socket is never read: the header +says nothing until the machine sending it has been named. (This is why the server parses the +header itself rather than arming the HTTP library's own trusted-proxy support: that support +rewrites the very address the handlers read as the socket peer, so one over-broad vouched +network would move the guard, not just the log line.) + The key is not encrypted in transit. On a network you do not control, bind to localhost behind a TLS-terminating reverse proxy: diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 72616748..4875f010 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -127,6 +127,22 @@ TEST(allow_host_repeats_and_refuses_the_empty_name) { CHECK(c.allow_hosts[0] == "box" && c.allow_hosts[1] == "box.example"); } +/* --trusted-proxy repeats: the sockets inside these networks may name the client behind them + * for the log. Anything but a numeric network with a prefix is refused at startup, because a + * typo there silently unvouches a proxy -- the server would keep answering through it and log + * the proxy on every line, with nothing to show for the flag. */ +TEST(trusted_proxy_repeats_and_refuses_anything_but_a_cidr) { + CHECK_EQ(parse_fresh({ "--trusted-proxy", "127.0.0.1" }), RAD_E_INVAL); /* no prefix */ + CHECK_EQ(parse_fresh({ "--trusted-proxy", "127.0.0.0/33" }), RAD_E_INVAL); /* out of family */ + CHECK_EQ(parse_fresh({ "--trusted-proxy", "::1/129" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--trusted-proxy", "proxy.internal/32" }), RAD_E_INVAL);/* not numeric */ + CHECK_EQ(parse_fresh({ "--trusted-proxy", "[::1]/128" }), RAD_E_INVAL); /* URL form, not CIDR */ + Config c; + CHECK_EQ(parse({ "--trusted-proxy", "127.0.0.0/8", "--trusted-proxy", "::1/128" }, &c), 0); + CHECK(c.trusted_proxies.size() == 2); + CHECK(c.trusted_proxies[0] == "127.0.0.0/8" && c.trusted_proxies[1] == "::1/128"); +} + /* A flag written last with no argument is refused rather than reading past argv. */ TEST(a_flag_missing_its_argument_is_refused_rather_than_read_past) { Config c; @@ -510,6 +526,7 @@ const std::map>& legal_values() { { "--host", { "127.0.0.1" } }, { "--port", { "8001" } }, { "--api-key", { "k" } }, { "--api-key-env", { "RAD_KEY_ENV_INVENTORY" } }, { "--allow-host", { "box" } }, + { "--trusted-proxy", { "127.0.0.0/8" } }, { "--served-model-name", { "m" } }, { "--mm-max-patches", { "1024" } }, { "--control-vector", { "off" } }, { "--generation-config", { "/g.json" } }, { "--override-chat-template", { "/t.jinja" } }, diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 043d8dcd..d1efe292 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -2756,6 +2756,7 @@ TEST(the_models_root_path_follows_the_key) { HttpRequest remote; remote.path = "/v1/models"; remote.peer = "192.168.1.20:50122"; + remote.raw_peer = remote.peer; remote.headers["Host"] = "box.example:8000"; CHECK(!json::parse(f.srv->router().dispatch(remote).body)["data"][0].contains("root")); /* The rebinding page: a loopback socket, an attacker's Origin and Host -- the pair the @@ -2763,12 +2764,14 @@ TEST(the_models_root_path_follows_the_key) { HttpRequest rebinding; rebinding.path = "/v1/models"; rebinding.peer = "127.0.0.1:50122"; + rebinding.raw_peer = rebinding.peer; rebinding.headers["Host"] = "evil.test:8000"; rebinding.headers["Origin"] = "http://evil.test:8000"; CHECK(!json::parse(f.srv->router().dispatch(rebinding).body)["data"][0].contains("root")); HttpRequest local; local.path = "/v1/models"; local.peer = "127.0.0.1:50122"; + local.raw_peer = local.peer; local.headers["Host"] = "localhost:8000"; CHECK_EQ(json::parse(f.srv->router().dispatch(local).body)["data"][0] .value("root", std::string()), @@ -3097,6 +3100,7 @@ TEST(diagnostics_without_a_key_answers_loopback_only) { HttpRequest q; q.path = "/diagnostics"; q.peer = peer; + q.raw_peer = peer; if (host) q.headers["Host"] = host; if (origin) q.headers["Origin"] = origin; return s.router().dispatch(q).status; @@ -3148,6 +3152,7 @@ TEST(state_changing_routes_without_a_key_answer_the_machine_only) { q.path = "/sessions"; q.query["label"] = "conv-1"; q.peer = peer; + q.raw_peer = peer; if (host) q.headers["Host"] = host; return s.router().dispatch(q).status; }; @@ -3156,6 +3161,7 @@ TEST(state_changing_routes_without_a_key_answer_the_machine_only) { q.method = "POST"; q.path = "/reset_prefix_cache"; q.peer = peer; + q.raw_peer = peer; if (host) q.headers["Host"] = host; return s.router().dispatch(q).status; }; @@ -4908,10 +4914,12 @@ TEST(the_control_vector_field_overrides_the_default_or_is_refused) { q.path = "/admin/control-vector"; q.body = R"({"enabled":true})"; q.peer = "192.168.1.20:50122"; + q.raw_peer = q.peer; q.headers["Host"] = "127.0.0.1:8080"; CHECK_EQ(f.srv->router().dispatch(q).status, 403); CHECK(!def); q.peer = "127.0.0.1:50122"; + q.raw_peer = q.peer; q.headers["Host"] = "localhost:8000"; CHECK_EQ(f.srv->router().dispatch(q).status, 200); CHECK(def); @@ -4930,6 +4938,7 @@ TEST(the_control_vector_field_overrides_the_default_or_is_refused) { x.path = "/admin/control-vector"; x.body = R"({"enabled":false})"; x.peer = "127.0.0.1:50122"; + x.raw_peer = x.peer; x.headers["Origin"] = "http://evil.test"; x.headers["Host"] = "127.0.0.1:8080"; CHECK_EQ(f.srv->router().dispatch(x).status, 403); @@ -4942,6 +4951,7 @@ TEST(the_control_vector_field_overrides_the_default_or_is_refused) { HttpRequest g2; g2.path = "/admin/control-vector"; g2.peer = "192.168.1.20:50122"; + g2.raw_peer = g2.peer; g2.headers["Host"] = "box.example:8000"; CHECK_EQ(f.srv->router().dispatch(g2).status, 403); HttpRequest g3; diff --git a/tests/transport_test.cpp b/tests/transport_test.cpp index 1c2e25db..12041c41 100644 --- a/tests/transport_test.cpp +++ b/tests/transport_test.cpp @@ -356,6 +356,98 @@ TEST(a_duplicated_security_header_is_refused) { CHECK_EQ(ask(get("/v1/models", "Authorization: Bearer k\r\nX-Api-Key: k\r\n")).status, 200); } +/* ================================================================== attribution */ + +/* What --trusted-proxy takes is a network, and ip_in_cidr is the one reader of it: an operator + * who typed 127.0.0.1 without a prefix was refused at startup (config_test); what reaches here + * is a CIDR, and a near-miss address must still miss. */ +TEST(a_vouched_network_covers_exactly_the_addresses_it_names) { + CHECK(cidr_valid("127.0.0.0/8")); + CHECK(cidr_valid("::1/128")); + CHECK(cidr_valid("0.0.0.0/0")); + CHECK(!cidr_valid("127.0.0.1")); /* no prefix */ + CHECK(!cidr_valid("127.0.0.0/33")); /* outside the family */ + CHECK(!cidr_valid("::1/129")); + CHECK(!cidr_valid("box.example/32")); /* names are not vouched, only numbers */ + CHECK(ip_in_cidr("127.0.0.1", "127.0.0.0/8")); + CHECK(ip_in_cidr("127.8.9.10", "127.0.0.0/8")); + CHECK(!ip_in_cidr("128.0.0.1", "127.0.0.0/8")); + CHECK(ip_in_cidr("::1", "::1/128")); + CHECK(ip_in_cidr("2001:db8::7", "2001:db8::/32")); + CHECK(!ip_in_cidr("2001:db9::7", "2001:db8::/32")); + CHECK(ip_in_cidr("8.8.8.8", "0.0.0.0/0")); + /* Families do not translate: an IPv4 socket is not inside an IPv6 network that embeds its + * bytes, and a vouched ::ffff:0:0/96 does not vouch for 1.2.3.4. An operator who means + * both writes both. */ + CHECK(!ip_in_cidr("1.2.3.4", "::ffff:1.2.3.4/128")); + CHECK(!ip_in_cidr("::1", "127.0.0.0/8")); +} + +/* X-Forwarded-For read the way a chain is actually appended to: our proxy's own entry is the + * last one, so the walk starts at the right and each vouched hop admits its neighbour to the + * left. The socket vouches for the header — a caller nobody vouched for names no one. */ +TEST(the_chain_is_walked_right_to_left_and_the_socket_vouches_for_it) { + const std::vector proxy{"10.0.0.0/8"}; + /* An unvouched socket carrying a confident header: the header is noise. */ + CHECK_EQ(attributed_client("198.51.100.9", "203.0.113.7", proxy), std::string("198.51.100.9")); + /* A vouched proxy naming an ordinary caller. */ + CHECK_EQ(attributed_client("10.0.0.1", "203.0.113.7", proxy), std::string("203.0.113.7")); + /* Two hops, the rightmost one unvouched: that is the caller our proxy saw, and the walk + * stops there — it never reads past a name it cannot vouch for, so an attacker who injects + * an extra left-hand hop is never believed. */ + CHECK_EQ(attributed_client("10.0.0.1", "203.0.113.7, 192.0.2.1", proxy), std::string("192.0.2.1")); + /* A chain of only vouched hops bottoms out at the leftmost: the client as the outermost + * proxy saw it. */ + CHECK_EQ(attributed_client("10.0.0.1", "10.0.0.9, 10.0.0.2", proxy), std::string("10.0.0.9")); + /* No header, or no vouched proxy: the socket, always as a fallback and always by default. */ + CHECK_EQ(attributed_client("10.0.0.1", "", proxy), std::string("10.0.0.1")); + CHECK_EQ(attributed_client("10.0.0.1", "203.0.113.7", {}), std::string("10.0.0.1")); + /* Garbage and empty entries: the chain is reported, not interpreted, and the log line + * owns the bytes. */ + CHECK_EQ(attributed_client("10.0.0.1", "garbage, 10.0.0.2", proxy), std::string("garbage")); + CHECK_EQ(attributed_client("10.0.0.1", ", , 203.0.113.7", proxy), std::string("203.0.113.7")); + CHECK_EQ(attributed_client("10.0.0.1", " , ", proxy), std::string("10.0.0.1")); + /* IPv6 chains. */ + const std::vector lo{"::1/128"}; + CHECK_EQ(attributed_client("::1", "2001:db8::5", lo), std::string("2001:db8::5")); +} + +/* A vouched proxy changes who the log talks about and nothing else. This is the whole attack + * the peer split exists for: with --trusted-proxy armed on its own loopback, a proxy that is + * told (or tricked) into forwarding X-Forwarded-For would otherwise hand the loopback guards — + * the keyless /diagnostics, the admin routes — to any caller it can carry. The guard reads the + * socket; the named address changes not one answer. */ +TEST(a_vouched_proxy_names_the_caller_without_becoming_the_authority) { + LiveServer s(4, 1, [](ServerOptions& o) { + o.diagnostics_json = [] { return std::string(R"({"findings":[]})"); }; + o.trusted_proxies = {"127.0.0.1/32"}; + }); + REQUIRE(s.srv->port() > 0); + /* The socket is loopback; the vouched proxy vouches for 203.0.113.7. The log carries the + * named address (checked at the unit level above); the guard still answers it as the + * socket it is. */ + CHECK_EQ(ask(s, "GET /diagnostics HTTP/1.1\r\nHost: localhost\r\n" + "X-Forwarded-For: 203.0.113.7\r\n\r\n") + .status, + 200); + /* And the default posture, once: no --trusted-proxy, an X-Forwarded-For from wherever is + * simply not read — the same request over the same socket reads the same. */ + LiveServer plain(4, 1, [](ServerOptions& o) { + o.diagnostics_json = [] { return std::string(R"({"findings":[]})"); }; + }); + REQUIRE(plain.srv->port() > 0); + CHECK_EQ(ask(plain, "GET /diagnostics HTTP/1.1\r\nHost: localhost\r\n" + "X-Forwarded-For: 203.0.113.7\r\n\r\n") + .status, + 200); + /* A cross-origin browser through the vouched proxy reads cross-origin exactly as it does + * without the header: attribution adds no Origin and removes no guard. */ + CHECK_EQ(ask(s, "GET /diagnostics HTTP/1.1\r\nHost: localhost\r\n" + "Origin: http://evil.test\r\nX-Forwarded-For: 203.0.113.7\r\n\r\n") + .status, + 403); +} + /* A 401 from the key gate ends the connection. The refused request's body was never read, and * keeping the socket alive makes those bytes somebody's problem: draining them hands the * refusing client a way to pace a worker — one byte per socket timeout, forever — and not