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.
This commit is contained in:
fl0l0u authored and StillDeadcode committed 2026-10-31 07:50:43 +01:00
1 parent 40e1b3073b
commit b6acbd69e4
11 files changed
+352 -22

No files matched your search

+153 -20
View File
@@ -13,6 +13,8 @@
#include <cctype>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <list>
#include <mutex>
#include <system_error>
@@ -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<std::string>& 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<std::string> 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<std::string> 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<FormPart> 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::nanoseconds>(
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"),