Explorar el Código

feat: resolve the caller's real address, and record it with the reason we refused

Three logs each held one half of the answer and none held two. nginx knows the
peer address and only the status code; our journal knows the structured slug and
not who was calling; the function run log knows the run and neither. So "who
hit this route, when, and what did we decide" was a join across two files on a
timestamp, which is work nobody does at the moment they need it.

WHAT IS HERE

- `resolveClientIp()` (client_ip.hpp, pure). The security property is one line:
  a header is believed ONLY when the request arrived from a trusted proxy.
  A header is text the client writes, so `X-Real-IP` from an arbitrary peer is
  a claim and not a measurement, and an allow-list built on an unverified claim
  is bypassable with one extra header while still reading as a working control.
  Deliberately falsified: deleting that arm turns exactly one test red
  (AHeaderFromAnUNTRUSTEDPeerIsIgnoredEntirely) and leaves the other ten green,
  so the test isolates the property rather than asserting something incidental.

  For a list-valued header the LAST element is taken, not the first, and this is
  the detail most implementations get backwards: nginx's
  `$proxy_add_x_forwarded_for` is "whatever the client sent, plus the real peer
  APPENDED", so the first element is entirely caller-controlled and the last is
  the only one the proxy vouched for.

  No new CIDR code: `parseCidr`/`cidrContains` already handle v4 and v6. Their
  "garbage is not a member" rule is the unsafe direction for a blocklist and the
  SAFE direction here, which is worth knowing before anyone reuses them again.

- The header NAME, its list-ness and the trusted-proxy ranges are SETTINGS, not
  constants, because the proxy is not ours to assume: dropping nginx, putting a
  CDN in front or moving to a load balancer that writes another name must all be
  a config change. An empty name means "no proxy, the peer IS the caller".
  CIDRs are validated at WRITE time (loud 422) and tolerated at read time (a bad
  entry is dropped): a typo refused at the door gets fixed now, while the same
  typo dropped silently would turn every line into the proxy's own address,
  which nobody notices because it still looks like an address.

- Our own access log, logfmt, one line per request, off unless an operator sets
  `access_log.path`. It carries the resolved address AND the slug, which is what
  makes it the right input for a ban tool: a jail can act on
  `code=unauthorized` rather than on every 401 the service ever emits.

  NOT added to the shipped config.json. That file is a dpkg conffile and adding
  one key to the template aborted a prod install mid-transaction in 0.18.1,
  leaving the service running the old binary while systemctl said it was fine.
  An optional key with a correct default does not belong in a conffile.

  Opening it FAILS CLOSED. An operator who configured an access log did so to
  watch something, and a service that came up healthy while writing no lines
  would make that monitor read as "no abuse" forever.

- Log injection is escaped, and it is not hypothetical: the path is
  caller-controlled, and a newline written through would let a caller forge a
  whole line including a plausible `ip=` for somebody else - turning a ban tool
  into a weapon pointed at a third party. `ip=` is also written BEFORE any
  caller-controlled field so a first-match regex finds the address we resolved.
  One test asserts the decoy SURVIVES, escaped and quoted, rather than
  pretending it is scrubbed, because that is what actually happens.

THE DEFECT THE END-TO-END CHECK FOUND, which no unit test would have

First version hooked the exception handler, and the unauthenticated 401 went out
with `code=-`: the pre-routing filter answers `sendJson` directly and never
throws, and several /fn refusals (404 not_found, 429 rate_limited, 503
runner_unavailable) bypass it the same way. The single most useful line for a
ban tool was the one missing its reason.

The slug is now recorded in `errorBody()`, the ONE function every refusal already
passes through, so a new refusal path cannot quietly stop being logged - the same
reasoning that made requireHonourableParams one idiom rather than two. That put
the trace in its own TU: `errors.cpp` is compiled standalone by narrow test
targets, and making error mapping depend on file I/O broke
test_project_secret_store, correctly, because deciding what a refusal is called
has nothing to do with writing a file.

Verified through a running server against a real file: `code=unauthorized` on the
401s, a trusted-peer header believed, a forged path escaped onto one line, and
`key=` carrying the stable id rather than the secret - checked against a known
secret ("dev") that does not appear.

Ops fragments under packaging/ops, shipped and not installed, because the log is
off by default: logrotate uses copytruncate since the server holds an O_APPEND fd
with no SIGHUP reopen, and the fail2ban note says how to prove the jail fires,
since a jail that never matches looks exactly like an absence of abuse.

Suite 1394/1394, 166.90 s, serial.

Still to do and deliberately not in here: the admin-only IP allow-list on the
function policy, and bounding RateLimiter before any per-IP throttle (its
windows_ map has no eviction, which is safe only while keys are API key ids).
fszontagh hace 1 semana
padre
commit
ac58a91b3e

+ 90 - 0
packaging/ops/fail2ban-smartbotic-vectorapi.md

@@ -0,0 +1,90 @@
+# Banning abusive callers from vectorapi's own access log
+
+Two facts decide the shape of this, and both are easy to get backwards.
+
+**Use OUR access log, not nginx's, when you want to ban on a REASON.** nginx's
+log has the caller's address and the status code and knows nothing about the
+decision we took: a 403 is a 403 whether the key was wrong, the scope was
+short, the `Origin` was absent, or the collection does not exist. A jail built
+on "401 against /fn" bans a caller who mistyped a token exactly as hard as one
+probing for one. Our log carries the structured slug in `code=`, so a jail can
+be specific.
+
+**Use NGINX's log when you want to ban traffic that never reached us.** If
+vectorapi is down, or a request is refused by nginx's own whitelist, there is no
+line in our log at all - absence here means "we did not answer", never "nothing
+happened". The two logs answer different questions and a serious setup watches
+both.
+
+## The line format
+
+logfmt, one line per request, fields always present in this order so a regex can
+be anchored:
+
+```
+ts=2026-11-18T16:25:48Z ip=203.0.113.77 method=GET path=/api/v1/projects status=401 dur_ms=3 code=unauthorized key=- project=- run=-
+```
+
+An empty field renders as `-`. `ip=` is written BEFORE any caller-controlled
+field on purpose: a path can contain almost anything, so a first-match
+`ip=(\S+)` must find the address we resolved rather than one a caller planted
+later in the line. Caller-controlled values are logfmt-quoted and control
+characters escaped, so a newline cannot forge a second line.
+
+**`ip=` is the address vectorapi RESOLVED, not whatever a header said.** It
+comes from the peer address unless the request arrived from a trusted proxy
+(`trusted_proxy_cidrs`), in which case `client_ip_header` is believed. Get that
+setting wrong and this field is the proxy's own address on every line, which
+reads as one very busy client - see the sanity check below.
+
+## Filter
+
+`/etc/fail2ban/filter.d/smartbotic-vectorapi.conf`:
+
+```ini
+[Definition]
+# Anchored on the slug, not merely on the status, which is the whole reason
+# for reading this file instead of nginx's.
+failregex = ^ts=\S+ ip=<HOST> .*code=(?:unauthorized|captcha_required)\b
+ignoreregex =
+datepattern = ^ts=%%Y-%%m-%%dT%%H:%%M:%%S
+```
+
+## Jail
+
+`/etc/fail2ban/jail.d/smartbotic-vectorapi.conf`:
+
+```ini
+[smartbotic-vectorapi]
+enabled  = true
+filter   = smartbotic-vectorapi
+logpath  = /var/log/smartbotic-vectorapi/access.log
+maxretry = 20
+findtime = 300
+bantime  = 3600
+```
+
+`maxretry` is deliberately not small. A public `/fn` route that checks its own
+token answers 401 to every ordinary mistake, and a tenant's own integration
+retrying a stale token would otherwise ban the tenant. Start loose, read
+`fail2ban-client status smartbotic-vectorapi`, and tighten once you know what
+normal looks like.
+
+## Prove the jail fires before trusting it
+
+A jail that never matches looks exactly like an absence of abuse, which is the
+most comfortable possible failure. Both checks are cheap:
+
+```sh
+# 1. Does the filter match the lines you actually have?
+fail2ban-regex /var/log/smartbotic-vectorapi/access.log \
+               /etc/fail2ban/filter.d/smartbotic-vectorapi.conf
+
+# 2. Is ip= a real variety of addresses, or one proxy repeated?
+awk '{for(i=1;i<=NF;i++) if($i ~ /^ip=/) print $i}' \
+    /var/log/smartbotic-vectorapi/access.log | sort | uniq -c | sort -rn | head
+```
+
+If (2) shows a single `ip=127.0.0.1` for everything, the trusted-proxy settings
+are wrong and **every ban would hit the proxy**, taking the whole site down
+rather than one caller. Fix that before enabling the jail, not after.

+ 37 - 0
packaging/ops/logrotate-smartbotic-vectorapi

@@ -0,0 +1,37 @@
+# Rotation for vectorapi's own access log (`access_log.path` in config.json).
+#
+# SHIPPED BUT NOT INSTALLED BY THE PACKAGE, because the log itself is off by
+# default: a package that starts rotating a file nobody asked for is the same
+# unrequested commitment as writing it. Copy to
+# /etc/logrotate.d/smartbotic-vectorapi when the log is turned on.
+#
+# WHY THIS MATTERS MORE THAN DISK. This file names callers, so an IP address is
+# personal data and retention is a legal question as much as a capacity one.
+# 14 days matches what nginx's own rotation keeps on prod, so the two logs a
+# diagnosis joins across do not disagree about how far back they go.
+#
+# AND THE CAUTIONARY TALE IS THIS BOX: logrotate was never installed on prod at
+# all, so nginx's access log ran unrotated from 2025-11-24 to 2026-10-22 and
+# reached 245 MB - which also made every "by hour" aggregate silently span
+# eleven months bucketed by hour-of-day, producing a clean plausible histogram
+# of the wrong thing. Verify `systemctl list-timers | grep logrotate` actually
+# shows a timer before believing any of this runs.
+/var/log/smartbotic-vectorapi/access.log {
+    daily
+    rotate 14
+    missingok
+    notifempty
+    compress
+    delaycompress
+    # COPYTRUNCATE deliberately. The server holds the file open on an O_APPEND
+    # fd and has no SIGHUP reopen, so `create` would leave it writing to the
+    # renamed inode forever and the new file would stay empty - the exact
+    # silent failure logrotate's postrotate hook exists to avoid for nginx.
+    # The cost is a small race in which lines written during the copy can be
+    # lost; for an access log that is the right trade against a log that
+    # silently stops.
+    copytruncate
+    # 0640 and adm, matching nginx's own rotated logs: readable by an operator
+    # in `adm` and by a monitor, not by everyone with a shell.
+    create 0640 root adm
+}

+ 3 - 0
src/CMakeLists.txt

@@ -6,6 +6,9 @@ add_library(vectorapi_core STATIC
     functions/header_fields.cpp
     json_http.cpp
     filters.cpp
+    client_ip.cpp
+    access_log.cpp
+    request_trace.cpp
     vector_search.cpp
     db_gateway.cpp
     settings.cpp

+ 110 - 0
src/access_log.cpp

@@ -0,0 +1,110 @@
+#include "access_log.hpp"
+#include "request_trace.hpp"
+#include <fcntl.h>
+#include <unistd.h>
+#include <cstdio>
+#include <ctime>
+#include <chrono>
+
+namespace svapi {
+
+std::string logfmtValue(const std::string& raw) {
+    if (raw.empty()) return "-";
+    std::string out;
+    out.reserve(raw.size() + 2);
+    bool needsQuotes = false;
+    for (const unsigned char c : raw)
+        if (c <= 0x20 || c == '"' || c == '\\' || c == '=' || c >= 0x7f) { needsQuotes = true; break; }
+    if (!needsQuotes) return raw;
+    out.push_back('"');
+    for (const unsigned char c : raw) {
+        switch (c) {
+            case '"':  out += "\\\""; break;
+            case '\\': out += "\\\\"; break;
+            case '\n': out += "\\n";  break;   // a forged line is the whole hazard
+            case '\r': out += "\\r";  break;
+            case '\t': out += "\\t";  break;
+            default:
+                if (c < 0x20 || c == 0x7f) {
+                    char buf[7];
+                    std::snprintf(buf, sizeof(buf), "\\x%02x", c);
+                    out += buf;
+                } else {
+                    out.push_back(static_cast<char>(c));
+                }
+        }
+    }
+    out.push_back('"');
+    return out;
+}
+
+std::string formatAccessLine(const std::string& isoUtc, const AccessLogEntry& e) {
+    // `ip=` comes first after the timestamp and is never quoted in practice,
+    // because it is always an address we parsed ourselves. A fail2ban regex can
+    // therefore anchor on `ip=<HOST> ` without tolerating quotes.
+    std::string out;
+    out += "ts=" + logfmtValue(isoUtc);
+    out += " ip=" + logfmtValue(e.clientIp);
+    out += " method=" + logfmtValue(e.method);
+    out += " path=" + logfmtValue(e.path);
+    out += " status=" + std::to_string(e.status);
+    out += " dur_ms=" + std::to_string(e.durationMs);
+    out += " code=" + logfmtValue(e.errorCode);
+    out += " key=" + logfmtValue(e.keyId);
+    out += " project=" + logfmtValue(e.project);
+    out += " run=" + logfmtValue(e.runId);
+    return out;
+}
+
+bool AccessLog::open(const std::string& path) {
+    std::lock_guard<std::mutex> lk(mu_);
+    if (fd_ >= 0) { ::close(fd_); fd_ = -1; }
+    path_ = path;
+    if (path_.empty()) return true;   // disabled, not a failure
+    // 0640: an access log naming callers is not world-readable. O_APPEND so
+    // concurrent writes from our request threads cannot interleave within a
+    // line, which is what lets the mutex only guard our own bookkeeping.
+    fd_ = ::open(path_.c_str(), O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0640);
+    return fd_ >= 0;
+}
+
+bool AccessLog::enabled() const {
+    std::lock_guard<std::mutex> lk(mu_);
+    return fd_ >= 0;
+}
+
+std::string AccessLog::path() const {
+    std::lock_guard<std::mutex> lk(mu_);
+    return path_;
+}
+
+bool AccessLog::reopen() {
+    std::string p;
+    { std::lock_guard<std::mutex> lk(mu_); p = path_; }
+    if (p.empty()) return true;
+    return open(p);
+}
+
+void AccessLog::write(const AccessLogEntry& entry) {
+    // The timestamp is taken here rather than by the caller so every line in
+    // one file comes from one clock in one format.
+    std::time_t now = std::time(nullptr);
+    std::tm tm{};
+    gmtime_r(&now, &tm);
+    char stamp[32];
+    std::snprintf(stamp, sizeof(stamp), "%04d-%02d-%02dT%02d:%02d:%02dZ", tm.tm_year + 1900,
+                  tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
+    const std::string line = formatAccessLine(stamp, entry) + "\n";
+    std::lock_guard<std::mutex> lk(mu_);
+    if (fd_ < 0) return;
+    // One write() of one line to an O_APPEND fd: no buffering, so a monitor
+    // sees a refusal immediately rather than whenever a buffer happened to
+    // fill. A short write is not retried - losing a tail is better than
+    // emitting a partial line twice and having a jail count it twice.
+    (void)!::write(fd_, line.data(), line.size());
+}
+
+AccessLog& accessLog() { static AccessLog inst; return inst; }
+
+
+} // namespace svapi

+ 78 - 0
src/access_log.hpp

@@ -0,0 +1,78 @@
+#pragma once
+#include "request_trace.hpp"
+#include <cstdint>
+#include <mutex>
+#include <string>
+
+/// Our own access log, on disk, one line per request, for a monitor to read.
+///
+/// WHY THIS EXISTS WHEN TWO LOGS ALREADY DO. nginx's access log has the real
+/// peer address and the status and NOTHING about the decision we took: a 403 is
+/// a 403 whether the key was wrong, the scope was short, the Origin was absent
+/// or the collection does not exist. Our own journal has the opposite half - it
+/// records the structured SLUG for every refusal (server.cpp's exception
+/// handler) and has no idea who was calling. Correlating them means joining on
+/// a timestamp and a path across two files, which is exactly the work nobody
+/// does at the moment they need it.
+///
+/// So this file carries BOTH, which is what makes it the right input for
+/// fail2ban: a jail can ban on `code=unauthorized` rather than on every 401 the
+/// service ever emits, and the address it bans is one we resolved deliberately
+/// (see client_ip.hpp) rather than whatever a header claimed.
+///
+/// LOG INJECTION IS THE HAZARD HERE AND IT IS NOT HYPOTHETICAL. The path, the
+/// method and the key id are caller-controlled, and a newline written straight
+/// through would let a caller forge a whole line - including a plausible
+/// `ip=` for somebody else, which turns a ban tool into a weapon pointed at a
+/// third party. Every field is escaped by `logfmtValue`, and that is the one
+/// function in here worth testing hardest.
+namespace svapi {
+
+/// A single request, already decided. Durations in milliseconds; empty strings
+/// render as `-` so every line has the same shape whether or not a field
+/// applied, which is what lets a monitor's regex be anchored.
+struct AccessLogEntry {
+    std::string clientIp;
+    std::string method;
+    std::string path;
+    int status = 0;
+    int64_t durationMs = 0;
+    std::string errorCode;   ///< the ApiError slug, when the request was refused
+    std::string keyId;       ///< the API key's stable id, never the secret
+    std::string project;
+    std::string runId;       ///< for a /fn dispatch, so a line joins to a run row
+};
+
+/// Escape a value for a logfmt field: control characters, quotes and
+/// backslashes. A newline MUST NOT survive this - see the class comment.
+std::string logfmtValue(const std::string& raw);
+
+/// Render one line, without the trailing newline.
+std::string formatAccessLine(const std::string& isoUtc, const AccessLogEntry& e);
+
+class AccessLog {
+public:
+    /// Open (append) the file at `path`. An empty path disables logging, which
+    /// is the default: a service that starts writing a new file on upgrade
+    /// without an operator asking is a disk commitment nobody signed up for.
+    /// Returns false when the path was given and could not be opened, so the
+    /// caller can refuse to start rather than run with a control that silently
+    /// does nothing.
+    bool open(const std::string& path);
+    bool enabled() const;
+    void write(const AccessLogEntry& entry);
+    /// Close and reopen the current path, for a log rotation that MOVES the
+    /// file. Safe to call when disabled.
+    bool reopen();
+    std::string path() const;
+
+private:
+    mutable std::mutex mu_;
+    std::string path_;
+    int fd_ = -1;
+};
+
+AccessLog& accessLog();  ///< process singleton
+
+
+} // namespace svapi

+ 78 - 0
src/client_ip.cpp

@@ -0,0 +1,78 @@
+#include "client_ip.hpp"
+#include <algorithm>
+
+namespace svapi {
+namespace {
+
+std::string trim(const std::string& s) {
+    const char* ws = " \t";
+    const auto b = s.find_first_not_of(ws);
+    if (b == std::string::npos) return {};
+    const auto e = s.find_last_not_of(ws);
+    return s.substr(b, e - b + 1);
+}
+
+/// The last non-empty element of a comma list, or the whole trimmed string when
+/// there is no comma.
+std::string lastElement(const std::string& list) {
+    std::size_t end = list.size();
+    while (end > 0) {
+        const std::size_t comma = list.rfind(',', end - 1);
+        const std::size_t from = (comma == std::string::npos) ? 0 : comma + 1;
+        std::string piece = trim(list.substr(from, end - from));
+        if (!piece.empty()) return piece;
+        if (comma == std::string::npos) return {};
+        end = comma;
+    }
+    return {};
+}
+
+} // namespace
+
+bool isPlainIpLiteral(const std::string& value) {
+    if (value.empty()) return false;
+    // A range is not a host. parseCidr would accept "10.0.0.0/8" and we would
+    // then record a network as if it were a caller.
+    if (value.find('/') != std::string::npos) return false;
+    std::string bare = value;
+    if (bare.size() >= 2 && bare.front() == '[' && bare.back() == ']')
+        bare = bare.substr(1, bare.size() - 2);
+    if (bare.empty()) return false;
+    // parseCidr treats a bare address as a host route, so it doubles as the
+    // validity check and keeps one implementation of address parsing.
+    return functions::parseCidr(bare).has_value();
+}
+
+ClientIpConfig clientIpConfigFrom(const std::string& header, bool headerIsList,
+                                  const std::vector<std::string>& trustedProxyCidrs) {
+    ClientIpConfig cfg;
+    cfg.header = trim(header);
+    cfg.headerIsList = headerIsList;
+    for (const std::string& entry : trustedProxyCidrs) {
+        if (auto range = functions::parseCidr(trim(entry))) cfg.trustedProxies.push_back(*range);
+    }
+    return cfg;
+}
+
+std::string resolveClientIp(const std::string& peer, const std::string& headerValue,
+                            const ClientIpConfig& cfg) {
+    if (cfg.header.empty()) return peer;          // no proxy in front of us
+    if (cfg.trustedProxies.empty()) return peer;  // trust nobody rather than anybody
+
+    const bool fromTrustedProxy =
+        std::any_of(cfg.trustedProxies.begin(), cfg.trustedProxies.end(),
+                    [&peer](const functions::CidrRange& r) {
+                        return functions::cidrContains(r, peer);
+                    });
+    // THE LOAD-BEARING LINE. Without it the header is believed whoever sent it.
+    if (!fromTrustedProxy) return peer;
+
+    const std::string candidate =
+        cfg.headerIsList ? lastElement(headerValue) : trim(headerValue);
+    if (!isPlainIpLiteral(candidate)) return peer;
+    if (candidate.size() >= 2 && candidate.front() == '[' && candidate.back() == ']')
+        return candidate.substr(1, candidate.size() - 2);
+    return candidate;
+}
+
+} // namespace svapi

+ 76 - 0
src/client_ip.hpp

@@ -0,0 +1,76 @@
+#pragma once
+#include "functions/net_guard.hpp"
+#include <string>
+#include <vector>
+
+/// Who is calling, from behind a reverse proxy, without letting the caller
+/// decide the answer.
+///
+/// THE WHOLE SECURITY PROPERTY IS IN ONE RULE: a header is only believed when
+/// the request actually arrived FROM a trusted proxy. An HTTP header is text
+/// the client writes, so `X-Real-IP` from an arbitrary peer is a claim, not a
+/// measurement - and an allow-list built on an unverified claim is bypassable
+/// with one extra header while still reading as a working control. Verified on
+/// prod 2026-11-18 before any of this was written: vectorapi binds
+/// 127.0.0.1:8080, so the only peer that can reach it is nginx on the same box,
+/// which is what makes the trusted-proxy set meaningful here rather than
+/// decorative.
+///
+/// The header NAME is configuration rather than a constant because the proxy is
+/// not ours to assume: removing nginx, putting Cloudflare in front, or moving to
+/// a load balancer that writes a different name must all be a settings change.
+/// An empty name means "there is no proxy, use the peer address", which is the
+/// correct answer for a deployment that exposes the port directly.
+namespace svapi {
+
+struct ClientIpConfig {
+    /// Header carrying the caller's address. EMPTY means never read a header,
+    /// which is the no-proxy deployment and the safe default when in doubt.
+    std::string header;
+    /// True for an X-Forwarded-For style comma list, where the LAST element is
+    /// the one our own proxy appended. See resolveClientIp for why that matters.
+    bool headerIsList = false;
+    /// Peers whose header may be believed. EMPTY means believe nobody, so a
+    /// misconfiguration degrades to the peer address rather than to trusting
+    /// whatever arrives.
+    std::vector<functions::CidrRange> trustedProxies;
+};
+
+/// Build a config from the stored settings, dropping any CIDR that does not
+/// parse. A malformed entry is dropped rather than failing the whole list,
+/// because the alternative - one typo disabling proxy trust service-wide -
+/// turns every request into the peer address silently, which is the direction
+/// nobody would notice.
+ClientIpConfig clientIpConfigFrom(const std::string& header, bool headerIsList,
+                                  const std::vector<std::string>& trustedProxyCidrs);
+
+/// The caller's address, or `peer` whenever a header cannot be trusted or read.
+///
+/// NEVER returns a value the caller chose unless `peer` is in
+/// `cfg.trustedProxies`. The order of the checks is the contract:
+///   1. no header configured            -> peer
+///   2. peer is not a trusted proxy     -> peer, and the header is not even read
+///   3. header absent or unusable       -> peer
+///   4. otherwise                       -> the address from the header
+///
+/// FOR A LIST, THE LAST ELEMENT IS TAKEN, NOT THE FIRST, and this is the one
+/// detail most implementations get backwards. nginx's
+/// `$proxy_add_x_forwarded_for` is "whatever the client sent, plus the real peer
+/// APPENDED". So a caller who sends `X-Forwarded-For: 1.2.3.4` produces
+/// `1.2.3.4, <their real address>`: the first element is entirely
+/// caller-controlled and the last is the only one our proxy vouched for.
+/// Reading the first would hand the caller the answer, which is precisely the
+/// bypass this function exists to prevent.
+///
+/// A value carrying a '/' is refused rather than parsed: `parseCidr` would
+/// happily accept "10.0.0.0/8" as a range, and a header must name one host.
+std::string resolveClientIp(const std::string& peer, const std::string& headerValue,
+                            const ClientIpConfig& cfg);
+
+/// Is this a single IP literal we are willing to record and match on?
+/// Brackets around an IPv6 literal are tolerated and stripped; a port is not,
+/// because nginx writes bare addresses and guessing at `host:port` splitting
+/// would mis-parse an IPv6 address on every colon.
+bool isPlainIpLiteral(const std::string& value);
+
+} // namespace svapi

+ 2 - 0
src/config.cpp

@@ -13,6 +13,8 @@ Config Config::fromJson(const nlohmann::json& j) {
         c.httpPort = h.value("port", c.httpPort);
         c.httpThreadPoolSize = h.value("thread_pool_size", c.httpThreadPoolSize);
     }
+    if (j.contains("access_log") && j["access_log"].is_object())
+        c.accessLogPath = j["access_log"].value("path", c.accessLogPath);
     if (j.contains("database") && j["database"].is_object()) {
         c.dbAddress = j["database"].value("address", c.dbAddress);
         c.dbTimeoutMs = j["database"].value("timeout_ms", c.dbTimeoutMs);

+ 19 - 0
src/config.hpp

@@ -38,6 +38,25 @@ struct Config {
     /// future httplib that sized its pool better would be silently overridden
     /// by a stale copy of the old behaviour.
     uint32_t    httpThreadPoolSize = 0;
+    /// Path to OUR OWN access log, or empty for none (the default).
+    ///
+    /// NOT in the shipped `config/config.json`, deliberately and at a cost
+    /// already paid once: that file is a dpkg CONFFILE, every real deployment
+    /// has customised it, and adding a single key to the template aborted a
+    /// prod install mid-transaction in 0.18.1 - dpkg found a genuine three-way
+    /// conflict, asked which version to keep, found no tty and exited 1 after
+    /// unpacking and before configuring, leaving the service running the OLD
+    /// binary while `systemctl is-active` said everything was fine. An optional
+    /// key with a correct default does not belong in a conffile. Read here if
+    /// an operator puts it there, never shipped there.
+    ///
+    /// Empty by default because a service that starts writing a new file on
+    /// upgrade is a disk commitment nobody asked for - and this one names
+    /// callers, so it is also a personal-data commitment. Turning it on means
+    /// shipping a logrotate fragment with it: an unrotated log is how nginx's
+    /// reached 245 MB over eleven months here and made every by-hour aggregate
+    /// silently span a year.
+    std::string accessLogPath;
     std::string dbAddress = "localhost:9004";
     /// Per-call gRPC deadline for EVERY database call, in milliseconds.
     ///

+ 5 - 0
src/errors.cpp

@@ -1,4 +1,5 @@
 #include "errors.hpp"
+#include "request_trace.hpp"
 
 namespace svapi {
 
@@ -41,6 +42,10 @@ int retryAfterSeconds(const ApiError& e) {
 
 nlohmann::json errorBody(const std::string& code, const std::string& message,
                          const nlohmann::json& details) {
+    // EVERY refusal passes through here, which is why the access log's slug is
+    // recorded at this one point rather than at the exception handler alone.
+    // See access_log.hpp for what that fixed.
+    noteRequestErrorCode(code);
     nlohmann::json err{{"code", code}, {"message", message}};
     if (!details.is_null() && !details.empty()) err["details"] = details;
     return nlohmann::json{{"error", err}};

+ 40 - 0
src/handlers/settings.cpp

@@ -60,6 +60,46 @@ void registerSettingsRoutes(ApiServer& s) {
             updated.captchaConnectTimeoutSec = body["captcha_connect_timeout_sec"].get<uint32_t>();
         if (body.contains("captcha_read_timeout_sec"))
             updated.captchaReadTimeoutSec = body["captcha_read_timeout_sec"].get<uint32_t>();
+        if (body.contains("client_ip_header")) {
+            if (!body["client_ip_header"].is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "client_ip_header must be a string; \"\" means read no header "
+                               "and treat the peer address as the caller");
+            updated.clientIpHeader = body["client_ip_header"].get<std::string>();
+        }
+        if (body.contains("client_ip_header_is_list")) {
+            if (!body["client_ip_header_is_list"].is_boolean())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "client_ip_header_is_list must be a boolean");
+            updated.clientIpHeaderIsList = body["client_ip_header_is_list"].get<bool>();
+        }
+        if (body.contains("trusted_proxy_cidrs")) {
+            // VALIDATED HERE AND TOLERATED AT RUNTIME, deliberately in both
+            // directions. A typo refused at the door is one an operator fixes
+            // now; the same typo dropped silently would turn every request into
+            // the peer address, which nobody would notice because it still
+            // answers an address. Conversely `clientIpConfigFrom` drops a bad
+            // entry rather than failing the whole list, so a value that somehow
+            // reached storage cannot disable proxy trust service-wide.
+            if (!body["trusted_proxy_cidrs"].is_array())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "trusted_proxy_cidrs must be an array of CIDR strings; "
+                               "an empty array means trust no proxy");
+            std::vector<std::string> cidrs;
+            for (const auto& v : body["trusted_proxy_cidrs"]) {
+                if (!v.is_string())
+                    throw ApiError(ErrCode::Unprocessable, "validation",
+                                   "every trusted_proxy_cidrs entry must be a string");
+                const std::string entry = v.get<std::string>();
+                if (!svapi::functions::parseCidr(entry))
+                    throw ApiError(ErrCode::Unprocessable, "validation",
+                                   "trusted_proxy_cidrs entry '" + entry +
+                                       "' is not a CIDR range or bare address",
+                                   {{"entry", entry}});
+                cidrs.push_back(entry);
+            }
+            updated.trustedProxyCidrs = cidrs;
+        }
         if (body.contains("embedding_cache_size"))
             updated.embeddingCacheSize = body["embedding_cache_size"].get<uint32_t>();
         if (body.contains("embedding_cache_ttl_sec"))

+ 15 - 0
src/main.cpp

@@ -2,6 +2,7 @@
 #include "collection_registry.hpp"
 #include "db_await.hpp"
 #include "config.hpp"
+#include "access_log.hpp"
 #include "function_events.hpp"
 #include "function_jobs.hpp"
 #include "function_scheduler.hpp"
@@ -52,6 +53,20 @@ int main(int argc, char** argv) {
     spdlog::set_level(spdlog::level::from_str(cfg.logLevel));
     if (!webuiDirOverride.empty()) cfg.webuiDir = webuiDirOverride;
 
+    // REFUSE TO START rather than run with a logging control that silently does
+    // nothing. An operator who configured an access log did so to watch
+    // something - most likely to point a ban tool at it - and a service that
+    // came up healthy while writing no lines would make that monitor read as
+    // "no abuse" forever. This repo already records what that costs: a control
+    // nobody has seen fire is not a control.
+    if (!svapi::accessLog().open(cfg.accessLogPath)) {
+        std::cerr << "config error: access_log.path '" << cfg.accessLogPath
+                  << "' could not be opened for append\n";
+        return 1;
+    }
+    if (svapi::accessLog().enabled())
+        spdlog::info("access log: {}", svapi::accessLog().path());
+
     std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN);
 
     svapi::DbGateway db(cfg.dbAddress, cfg.dbTimeoutMs);

+ 31 - 0
src/request_trace.cpp

@@ -0,0 +1,31 @@
+#include "request_trace.hpp"
+#include <chrono>
+
+namespace svapi {
+namespace {
+struct RequestTrace {
+    std::chrono::steady_clock::time_point started;
+    std::string code;
+    bool active = false;
+};
+thread_local RequestTrace g_trace;
+} // namespace
+
+void beginRequestTrace() {
+    g_trace.started = std::chrono::steady_clock::now();
+    g_trace.code.clear();
+    g_trace.active = true;
+}
+
+void noteRequestErrorCode(const std::string& code) { g_trace.code = code; }
+
+std::string requestErrorCode() { return g_trace.code; }
+
+int64_t requestElapsedMs() {
+    if (!g_trace.active) return 0;
+    return std::chrono::duration_cast<std::chrono::milliseconds>(
+               std::chrono::steady_clock::now() - g_trace.started)
+        .count();
+}
+
+} // namespace svapi

+ 42 - 0
src/request_trace.hpp

@@ -0,0 +1,42 @@
+#pragma once
+#include <cstdint>
+#include <string>
+
+/// The small amount of per-request state the access log needs and the response
+/// object cannot carry.
+///
+/// ITS OWN TRANSLATION UNIT ON PURPOSE. `errorBody` in errors.cpp records the
+/// slug here, and errors.cpp is compiled STANDALONE by narrow test targets that
+/// link a fake database and nothing else. Putting these three functions in
+/// access_log.cpp made error mapping depend on file I/O, and
+/// `test_project_secret_store` stopped linking - correctly, because that
+/// dependency was wrong rather than merely inconvenient: deciding what a
+/// refusal is called has nothing to do with writing a file.
+///
+/// httplib handles one request start-to-finish on one thread, so the state is
+/// thread_local and request-scoped.
+namespace svapi {
+
+/// Start a request's trace: zero the elapsed clock and FORGET any slug left
+/// behind by the previous request on this thread.
+///
+/// CLEARED AT START, never after the line is written. The two look equivalent
+/// and are not: clear afterwards and a request that never refuses inherits a
+/// stranger's slug from whatever ran before it on that thread, which mislabels
+/// a 200 and is invisible once wrong.
+void beginRequestTrace();
+
+/// Record the slug of the refusal being sent. Last call wins.
+///
+/// Called from `errorBody`, which is the ONE function every refusal passes
+/// through - the exception handler's sender AND every handler that answers
+/// `sendJson(res, N, errorBody(...))` directly. Hooking only the exception
+/// handler was the first attempt and measured as a defect at once: the
+/// unauthenticated 401 comes from the pre-routing filter, which never throws,
+/// so the single most useful line for a ban tool went out with `code=-`.
+void noteRequestErrorCode(const std::string& code);
+
+std::string requestErrorCode();   ///< the slug recorded for this request, or empty
+int64_t requestElapsedMs();       ///< ms since beginRequestTrace(), or 0 if never called
+
+} // namespace svapi

+ 35 - 0
src/server.cpp

@@ -5,6 +5,8 @@
 #include "errors.hpp"
 #include "json_http.hpp"
 #include "rate_limiter.hpp"
+#include "access_log.hpp"
+#include "client_ip.hpp"
 #include <spdlog/spdlog.h>
 
 #include <chrono>
@@ -212,6 +214,9 @@ void ApiServer::registerRoutes() {
 
     // Authenticate /api/* (authorization is per-handler).
     svr_.set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
+        // START of the request: zero the clock and forget the previous
+        // request's slug. See access_log.hpp on why that ordering matters.
+        beginRequestTrace();
         if (req.method != "OPTIONS" && req.path.rfind("/api/", 0) == 0) {
             if (!resolveKey(d_, req)) {
                 sendJson(res, 401, errorBody("unauthorized", "missing or invalid credentials"));
@@ -221,6 +226,36 @@ void ApiServer::registerRoutes() {
         return httplib::Server::HandlerResponse::Unhandled;
     });
 
+    // OUR OWN ACCESS LOG. Off unless an operator set a path.
+    //
+    // It carries the two halves that live in different files today: the
+    // resolved caller address, which only nginx knows, and the error SLUG,
+    // which only our journal knows. A fail2ban jail can therefore ban on
+    // `code=unauthorized` rather than on every 401 the service emits, and the
+    // address it acts on is one we resolved under the trusted-proxy rule rather
+    // than whatever a header claimed.
+    svr_.set_logger([this](const httplib::Request& req, const httplib::Response& res) {
+        if (!accessLog().enabled()) return;
+        auto snap = d_.settings.snapshot();
+        AccessLogEntry e;
+        e.clientIp = resolveClientIp(
+            req.remote_addr,
+            snap->clientIpHeader.empty() ? std::string()
+                                         : req.get_header_value(snap->clientIpHeader.c_str()),
+            clientIpConfigFrom(snap->clientIpHeader, snap->clientIpHeaderIsList,
+                               snap->trustedProxyCidrs));
+        e.method = req.method;
+        e.path = req.path;
+        e.status = res.status;
+        e.errorCode = requestErrorCode();
+        e.durationMs = requestElapsedMs();
+        // The key is referenced by its stable id, NEVER the secret - the same
+        // rule the rest of the service follows. An unauthenticated request
+        // leaves it empty, which renders as `-`.
+        if (auto key = resolveKey(d_, req)) e.keyId = key->id;
+        accessLog().write(e);
+    });
+
     svr_.set_post_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
         auto snap = d_.settings.snapshot();
         std::string responseOrigin;

+ 11 - 0
src/settings.cpp

@@ -18,6 +18,14 @@ Settings Settings::fromJson(const nlohmann::json& j) {
     s.vectorFilterScanCap        = j.value("vector_filter_scan_cap",      s.vectorFilterScanCap);
     s.captchaConnectTimeoutSec   = j.value("captcha_connect_timeout_sec",  s.captchaConnectTimeoutSec);
     s.captchaReadTimeoutSec      = j.value("captcha_read_timeout_sec",     s.captchaReadTimeoutSec);
+    s.clientIpHeader             = j.value("client_ip_header",             s.clientIpHeader);
+    s.clientIpHeaderIsList       = j.value("client_ip_header_is_list",     s.clientIpHeaderIsList);
+    if (j.contains("trusted_proxy_cidrs") && j["trusted_proxy_cidrs"].is_array()) {
+        std::vector<std::string> out;
+        for (const auto& v : j["trusted_proxy_cidrs"])
+            if (v.is_string()) out.push_back(v.get<std::string>());
+        s.trustedProxyCidrs = out;   // an explicit empty array means "trust nobody"
+    }
     s.embeddingCacheSize         = j.value("embedding_cache_size",        s.embeddingCacheSize);
     s.embeddingCacheTtlSec       = j.value("embedding_cache_ttl_sec",     s.embeddingCacheTtlSec);
     s.embeddingCacheMaxBytes     = j.value("embedding_cache_max_bytes",   s.embeddingCacheMaxBytes);
@@ -51,6 +59,9 @@ nlohmann::json Settings::toJson() const {
             {"vector_filter_scan_cap",     vectorFilterScanCap},
             {"captcha_connect_timeout_sec", captchaConnectTimeoutSec},
             {"captcha_read_timeout_sec",   captchaReadTimeoutSec},
+            {"client_ip_header",           clientIpHeader},
+            {"client_ip_header_is_list",   clientIpHeaderIsList},
+            {"trusted_proxy_cidrs",        trustedProxyCidrs},
             {"embedding_cache_size",        embeddingCacheSize},
             {"embedding_cache_ttl_sec",     embeddingCacheTtlSec},
             {"embedding_cache_max_bytes",   embeddingCacheMaxBytes},

+ 21 - 0
src/settings.hpp

@@ -48,6 +48,27 @@ struct Settings {
     /// box where those are scarce.
     uint32_t    captchaConnectTimeoutSec   = 5;
     uint32_t    captchaReadTimeoutSec      = 10;
+    /// WHO IS CALLING, from behind a reverse proxy.
+    ///
+    /// The header NAME is configuration and not a constant, because the proxy
+    /// is not ours to assume: dropping nginx, putting a CDN in front, or moving
+    /// to a load balancer that writes a different name must all be a settings
+    /// change rather than a rebuild. EMPTY means "read no header, the peer
+    /// address IS the caller", which is correct for a directly exposed port and
+    /// is the safe answer whenever the deployment is unknown.
+    std::string clientIpHeader             = "X-Real-IP";
+    /// True for an X-Forwarded-For style comma list. Explicit rather than
+    /// inferred from the header's name, because the two differ in WHICH element
+    /// is trustworthy and guessing that from a string would be a silent
+    /// security decision: see resolveClientIp on why the LAST element is ours.
+    bool        clientIpHeaderIsList       = false;
+    /// Peers whose `clientIpHeader` may be believed. A header is text the
+    /// client writes, so it is a claim rather than a measurement unless the
+    /// request demonstrably came from our own proxy. EMPTY trusts nobody and
+    /// degrades to the peer address, which is the direction a typo should fail
+    /// in. Defaults to loopback because prod's vectorapi binds 127.0.0.1 and
+    /// nginx on the same box is the only peer that can reach it.
+    std::vector<std::string> trustedProxyCidrs { "127.0.0.0/8", "::1/128" };
     uint32_t    embeddingCacheSize         = 4096;       // max entries
     uint32_t    embeddingCacheTtlSec       = 86400;      // 0 = no expiry
     uint64_t    embeddingCacheMaxBytes     = 268435456;  // 256 MB

+ 12 - 1
tests/CMakeLists.txt

@@ -25,6 +25,14 @@ add_executable(test_errors test_errors.cpp)
 target_link_libraries(test_errors PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_errors)
 
+add_executable(test_access_log test_access_log.cpp)
+target_link_libraries(test_access_log PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_access_log)
+
+add_executable(test_client_ip test_client_ip.cpp)
+target_link_libraries(test_client_ip PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_client_ip)
+
 add_executable(test_filters test_filters.cpp)
 target_link_libraries(test_filters PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_filters)
@@ -230,7 +238,10 @@ add_executable(test_project_secret_store
     # conflating it with absence, so the error mapping comes along. It is pure
     # apart from Client::errorDetail, which the file's link-time fake provides.
     ${CMAKE_SOURCE_DIR}/src/db_errors.cpp
-    ${CMAKE_SOURCE_DIR}/src/errors.cpp)
+    ${CMAKE_SOURCE_DIR}/src/errors.cpp
+    # errorBody records the refusal's slug for the access log; the trace is its
+    # own TU precisely so this target does not have to link file I/O.
+    ${CMAKE_SOURCE_DIR}/src/request_trace.cpp)
 target_include_directories(test_project_secret_store PRIVATE
     ${CMAKE_SOURCE_DIR}/src
     $<TARGET_PROPERTY:smartbotic::db-client,INTERFACE_INCLUDE_DIRECTORIES>)

+ 136 - 0
tests/test_access_log.cpp

@@ -0,0 +1,136 @@
+#include "access_log.hpp"
+#include <gtest/gtest.h>
+#include <algorithm>
+#include <cstdio>
+#include <unistd.h>
+
+using namespace svapi;
+
+// --- log injection, which is the reason this file is escaped at all ----------
+
+TEST(AccessLog, ANewlineInACallerControlledFieldCannotForgeALine) {
+    // A path is caller-controlled. Written raw, this would end the line and
+    // start a second one that looks like a request from somebody else - and a
+    // ban tool reading it would ban that third party.
+    const std::string evil = "/x\nts=2026-01-01T00:00:00Z ip=198.51.100.7 status=401";
+    const std::string rendered = logfmtValue(evil);
+    EXPECT_EQ(rendered.find('\n'), std::string::npos);
+    EXPECT_NE(rendered.find("\\n"), std::string::npos);
+
+    AccessLogEntry e;
+    e.clientIp = "203.0.113.9";
+    e.path = evil;
+    e.method = "GET";
+    e.status = 404;
+    const std::string line = formatAccessLine("2026-11-18T20:00:00Z", e);
+    // ONE line is the security property: a forged second line is what would
+    // make a ban tool act on an address the caller chose.
+    EXPECT_EQ(line.find('\n'), std::string::npos);
+    // The forged text itself SURVIVES, escaped, inside a quoted value - and
+    // that is fine rather than a gap, so it is asserted rather than wished
+    // away. What protects a monitor is that the address WE resolved is written
+    // before any caller-controlled field, so a first-match `ip=(\S+)` regex
+    // reads the truth and never reaches the decoy.
+    EXPECT_LT(line.find(" ip=203.0.113.9 "), line.find("path="));
+    EXPECT_LT(line.find(" ip=203.0.113.9 "), line.find("198.51.100.7"));
+    // And the decoy is inside quotes, so a parser that honours logfmt quoting
+    // sees one value rather than new fields.
+    EXPECT_NE(line.find("path=\""), std::string::npos);
+}
+
+TEST(AccessLog, CarriageReturnsTabsAndControlBytesAreAllEscaped) {
+    EXPECT_EQ(logfmtValue("a\rb").find('\r'), std::string::npos);
+    EXPECT_EQ(logfmtValue("a\tb").find('\t'), std::string::npos);
+    const std::string nul = logfmtValue(std::string("a\x01" "b"));
+    EXPECT_NE(nul.find("\\x01"), std::string::npos);
+}
+
+TEST(AccessLog, AQuoteOrBackslashCannotBreakOutOfAQuotedValue) {
+    const std::string out = logfmtValue("he said \"hi\" c:\\x");
+    EXPECT_EQ(out.front(), '"');
+    EXPECT_EQ(out.back(), '"');
+    // Every interior quote is escaped, so the value has no unescaped quote
+    // before its own terminator.
+    for (std::size_t i = 1; i + 1 < out.size(); ++i)
+        if (out[i] == '"') EXPECT_EQ(out[i - 1], '\\');
+}
+
+// --- the shape a monitor's regex depends on ---------------------------------
+
+TEST(AccessLog, AnOrdinaryLineLeavesTheAddressUNQUOTEDSoAJailCanAnchorOnIt) {
+    AccessLogEntry e;
+    e.clientIp = "203.0.113.9";
+    e.method = "POST";
+    e.path = "/fn/toloajto/stats";
+    e.status = 401;
+    e.durationMs = 12;
+    e.errorCode = "unauthorized";
+    e.project = "toloajto";
+    const std::string line = formatAccessLine("2026-11-18T20:00:00Z", e);
+    EXPECT_NE(line.find(" ip=203.0.113.9 "), std::string::npos);
+    EXPECT_NE(line.find("status=401"), std::string::npos);
+    EXPECT_NE(line.find("code=unauthorized"), std::string::npos);
+    EXPECT_NE(line.find("project=toloajto"), std::string::npos);
+}
+
+TEST(AccessLog, AnEmptyFieldRendersAsADashSoEveryLineHasTheSameShape) {
+    AccessLogEntry e;
+    e.clientIp = "203.0.113.9";
+    e.method = "GET";
+    e.path = "/healthz";
+    e.status = 200;
+    const std::string line = formatAccessLine("2026-11-18T20:00:00Z", e);
+    EXPECT_NE(line.find("code=-"), std::string::npos);
+    EXPECT_NE(line.find("key=-"), std::string::npos);
+    EXPECT_NE(line.find("run=-"), std::string::npos);
+}
+
+// --- the file itself --------------------------------------------------------
+
+TEST(AccessLog, AnEmptyPathDisablesTheLogWithoutFailing) {
+    AccessLog log;
+    EXPECT_TRUE(log.open(""));
+    EXPECT_FALSE(log.enabled());
+    AccessLogEntry e;
+    e.clientIp = "203.0.113.9";
+    log.write(e);   // must not crash when disabled
+}
+
+TEST(AccessLog, AnUnopenablePathIsReportedRatherThanSwallowed) {
+    AccessLog log;
+    // A control that silently does nothing is worse than one that refuses.
+    EXPECT_FALSE(log.open("/proc/definitely/not/writable/access.log"));
+    EXPECT_FALSE(log.enabled());
+}
+
+TEST(AccessLog, LinesAreAppendedAndVisibleImmediately) {
+    const std::string path = std::string(::getenv("TMPDIR") ? ::getenv("TMPDIR") : "/tmp") +
+                             "/svapi_access_test.log";
+    ::unlink(path.c_str());
+    AccessLog log;
+    ASSERT_TRUE(log.open(path));
+    ASSERT_TRUE(log.enabled());
+    AccessLogEntry e;
+    e.clientIp = "203.0.113.9";
+    e.method = "GET";
+    e.path = "/healthz";
+    e.status = 200;
+    log.write(e);
+    e.status = 401;
+    e.errorCode = "unauthorized";
+    log.write(e);
+
+    // Read it back without closing: a monitor tails this file live, so an
+    // unflushed buffer would make the control useless exactly when it matters.
+    FILE* f = ::fopen(path.c_str(), "r");
+    ASSERT_NE(f, nullptr);
+    std::string contents;
+    char buf[512];
+    while (std::fgets(buf, sizeof(buf), f)) contents += buf;
+    ::fclose(f);
+    ::unlink(path.c_str());
+
+    EXPECT_NE(contents.find("status=200"), std::string::npos);
+    EXPECT_NE(contents.find("code=unauthorized"), std::string::npos);
+    EXPECT_EQ(std::count(contents.begin(), contents.end(), '\n'), 2);
+}

+ 102 - 0
tests/test_client_ip.cpp

@@ -0,0 +1,102 @@
+#include "client_ip.hpp"
+#include <gtest/gtest.h>
+
+using namespace svapi;
+
+namespace {
+
+ClientIpConfig loopbackTrust(const std::string& header = "X-Real-IP", bool isList = false) {
+    return clientIpConfigFrom(header, isList, {"127.0.0.0/8", "::1/128"});
+}
+
+} // namespace
+
+// --- the security property ---------------------------------------------------
+//
+// These two are the whole point of the file. If `resolveClientIp`'s
+// trusted-proxy arm is deleted, the first goes red; nothing else here would.
+
+TEST(ClientIp, AHeaderFromAnUNTRUSTEDPeerIsIgnoredEntirely) {
+    const auto cfg = loopbackTrust();
+    // A caller reaching us directly and claiming to be someone else.
+    EXPECT_EQ(resolveClientIp("203.0.113.9", "198.51.100.1", cfg), "203.0.113.9");
+    // Claiming to be the proxy itself buys nothing either.
+    EXPECT_EQ(resolveClientIp("203.0.113.9", "127.0.0.1", cfg), "203.0.113.9");
+}
+
+TEST(ClientIp, AHeaderFromATrustedProxyIsBelieved) {
+    const auto cfg = loopbackTrust();
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "198.51.100.1", cfg), "198.51.100.1");
+    EXPECT_EQ(resolveClientIp("::1", "2001:db8::5", cfg), "2001:db8::5");
+}
+
+// --- the list form, and the element nobody picks correctly -------------------
+
+TEST(ClientIp, TheLASTElementOfAForwardedForListIsTaken) {
+    const auto cfg = loopbackTrust("X-Forwarded-For", /*isList=*/true);
+    // nginx's $proxy_add_x_forwarded_for is "what the client sent, plus the
+    // real peer appended". The caller forged the first element; the last is
+    // the only one the proxy vouched for.
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "198.51.100.1, 203.0.113.9", cfg), "203.0.113.9");
+    // Taking the FIRST would return the forged 198.51.100.1 here, which is the
+    // bypass. Spelled out so a later "simplification" has to delete an
+    // assertion that says why.
+    EXPECT_NE(resolveClientIp("127.0.0.1", "198.51.100.1, 203.0.113.9", cfg), "198.51.100.1");
+}
+
+TEST(ClientIp, AListWithTrailingSeparatorsOrSpacesStillYieldsTheLastRealElement) {
+    const auto cfg = loopbackTrust("X-Forwarded-For", true);
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "198.51.100.1,  203.0.113.9  ,", cfg), "203.0.113.9");
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "  203.0.113.9", cfg), "203.0.113.9");
+}
+
+// --- degrading to the peer, in every direction ------------------------------
+
+TEST(ClientIp, NoHeaderConfiguredMeansThePeerIsTheAnswer) {
+    const auto cfg = loopbackTrust("");
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "198.51.100.1", cfg), "127.0.0.1");
+}
+
+TEST(ClientIp, AnEmptyTrustedProxyListTrustsNOBODYRatherThanEverybody) {
+    const auto cfg = clientIpConfigFrom("X-Real-IP", false, {});
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "198.51.100.1", cfg), "127.0.0.1");
+}
+
+TEST(ClientIp, AnAbsentOrUnusableHeaderValueFallsBackToThePeer) {
+    const auto cfg = loopbackTrust();
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "", cfg), "127.0.0.1");
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "not-an-address", cfg), "127.0.0.1");
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "unknown", cfg), "127.0.0.1");
+}
+
+TEST(ClientIp, ARANGEInTheHeaderIsRefusedBecauseAHeaderMustNameOneHost) {
+    const auto cfg = loopbackTrust();
+    // parseCidr would accept this as a /8; recording it as a caller would be
+    // nonsense and matching an allow-list against it would be worse.
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "10.0.0.0/8", cfg), "127.0.0.1");
+}
+
+TEST(ClientIp, ABracketedIPv6LiteralIsAcceptedAndUnwrapped) {
+    const auto cfg = loopbackTrust();
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "[2001:db8::5]", cfg), "2001:db8::5");
+}
+
+// --- config assembly --------------------------------------------------------
+
+TEST(ClientIp, AMalformedTrustedCidrIsDroppedWithoutDisablingTheRest) {
+    // One typo must not silently turn every request into the peer address.
+    const auto cfg = clientIpConfigFrom("X-Real-IP", false,
+                                        {"not-a-cidr", "127.0.0.0/8", "999.1.1.1/8"});
+    EXPECT_EQ(cfg.trustedProxies.size(), 1u);
+    EXPECT_EQ(resolveClientIp("127.0.0.1", "198.51.100.1", cfg), "198.51.100.1");
+}
+
+TEST(ClientIp, IsPlainIpLiteralAcceptsHostsAndRejectsEverythingElse) {
+    EXPECT_TRUE(isPlainIpLiteral("198.51.100.1"));
+    EXPECT_TRUE(isPlainIpLiteral("2001:db8::5"));
+    EXPECT_TRUE(isPlainIpLiteral("[2001:db8::5]"));
+    EXPECT_FALSE(isPlainIpLiteral(""));
+    EXPECT_FALSE(isPlainIpLiteral("10.0.0.0/8"));
+    EXPECT_FALSE(isPlainIpLiteral("example.com"));
+    EXPECT_FALSE(isPlainIpLiteral("[]"));
+}