Jelajahi Sumber

feat: client IP resolution, access log, IP allow-list, and the filtered match total

Merges SV-126 (resolve and record the real client IP: configurable header,
trusted proxies, our own access log, policy allow-list, bounded limiter) and
SV-127 (report the has_more and total the server already computes).
fszontagh 6 hari lalu
induk
melakukan
d09ec049b8

+ 21 - 3
api/llms.txt

@@ -44,6 +44,7 @@ A non-admin key may carry a `scope` object that restricts what it can do. Scoped
 
 **The Origin allow-list now covers the collections LISTING too** (0.15.0+). It always covered document and vector operations; the listing authorized through the project grant plus the scope filter and never consulted the list, so a key with an allow-list could enumerate a project's collection names, document counts and sizes from ANY origin while being refused every document in them. That mattered because a browser-publishable key is, by definition, a key anyone can read. Now `GET /projects/{p}/collections` answers **403** `forbidden` for an origin outside the list, exactly as a document read does.
 - **A key with NO `origins` is unaffected** - an empty list means any origin, which is what a server-side key should use.
+- `ip_allow` on a KEY scope is **refused with 422 `unsupported_option`**, not stored. Nothing checks it for an API key, and a control that reads back from the server while never being applied is worse than one that is absent - an operator would believe a key was pinned to their office address. It is a **function policy** field only (see the policy route). For a browser key, `origins` is the control that works; a server-side key has none today, because a non-browser client sends no `Origin` header.
 - **An ABSENT `Origin` header is refused when a list IS set**, on the listing and on every other capability-checked route alike. This is long-standing behaviour rather than new, and it is why **a key intended for server-side use must not carry an allow-list at all**: a non-browser client sends no Origin, so it can never satisfy one. A test pins the two routes to the same answer so they cannot drift apart again.
 
 **A scope refusal names what it refused and what you hold** (0.15.0+). A 403 `forbidden` from a scoped key carries a message naming the collection and the operation asked, plus the collections the key IS granted, and `error.details` with `collection`, `operation` and `granted` (each `{collection, ops}`). **The status is 403 whether the collection is outside your scope OR does not exist, and that is deliberate** - answering 404 for an absent collection would let a scoped key discover which collections exist in its project outside its own scope. So the message says as much: only you can tell a misspelled name from one nobody provisioned, and the answer will not tell you. Before 0.15.0 the message was just "scope does not permit this operation", which named neither and sent people to re-verify their key rather than the string.
@@ -133,7 +134,12 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
   **It requires the document to exist** (**404** otherwise) and never creates one: the starting document is yours to describe. The idiom for a counter that may not exist yet is: increment; on **404** `POST .../documents` the document under a fixed `id` with its starting values; on **409** `duplicate_values` (someone else just created it) increment again.
 - `DELETE /api/v1/projects/{project}/collections/{name}/documents/{id}` - Delete a document. Returns **409** `relation_restricted` (with `error.details.impacts`) if a restrict relation has children referencing it; see delete-impact below to preview this first.
-- `GET   /api/v1/projects/{project}/collections/{name}/documents` - Find documents. Every row carries the same `_id`/`_version` metadata a single GET returns, so a filtered listing is a usable starting point for a conditional write without a second request per row.
+- `GET   /api/v1/projects/{project}/collections/{name}/documents` - Find documents. Returns `{documents, count, has_more, total}`. Every row carries the same `_id`/`_version` metadata a single GET returns, so a filtered listing is a usable starting point for a conditional write without a second request per row.
+  **`count` is the PAGE size; `total` is the exact number of rows matching your filters.** Both `has_more` and `total` are new in 0.18.2 and are emitted unconditionally, so an absent field means an older server and never "nothing to report". `total` is computed by the database before pagination and is exact rather than an estimate - it is not capped by `limit`, and it answers a multi-field filter, which nothing else here can: `indexes/{field}/values` counts ONE field over the whole collection. Before 0.18.2 the only way to get this number was to page the entire matching set, and one consumer measured that as a full scan plus 1750 documents of encoding to obtain a single integer, which is why their review portal shipped without a result count.
+  **`limit` DOES NOT BOUND THE SERVER'S WORK, and the natural assumption is the opposite.** The database builds the whole match set, sorts it, and only then applies `offset`/`limit`, so `limit=20` and `limit=1000` scan identically. What `limit` saves is materialising and encoding the rows you did not ask for - which is real and is usually the whole cost (one consumer's queue screen went from 2.9 s to 453 ms by stopping at a page), but it means a narrow filter does not make a read cheaper and a small page is not a cheap query. Measured 2026-11-20 against a 13,093-row collection: the same predicate at `limit=1` and at `limit=1000` costs the same server-side.
+  **Omitting `limit` gives you 100 rows, not every row.** A sweep written without one stops at 100 and returns a clean short page, which is indistinguishable from a set that really holds 100 rows - so pass `limit` explicitly, and use `has_more` rather than a short page to decide whether to continue.
+  **A filter is index-accelerated only when it is genuinely selective, and "selective" means under ~10% of the collection.** Declaring an index does not make a filter on it cheap. The database picks, per VALUE rather than per field, the most selective indexed equality whose match count is under `rows/10`, and otherwise scans - because reading an index candidate costs a full document decode where a scan costs one parse, measured upstream at a ratio of ~8.6x, so a broad index plan is slower than scanning. It can also intersect two equalities, but only if the INTERSECTION clears the same bar. Worked example from prod: on 13,093 rows, `channel:eq:audio` matches 6,836 (52%) and `departmentKey:eq:ber` matches 3,520 (27%), so each is declined alone; together they match 1,750 (13.4%), which misses the 1,309-row threshold and is declined too, after paying to read and intersect 10,356 index entries. Filter ORDER is irrelevant - the planner measures each candidate's exact size first and takes the smallest - so there is nothing to tune by reordering. A field with few distinct values (a status, a boolean, a channel) will essentially never be index-served on its common values, only on its rare ones.
+  **`sort` sorts the entire match set, not your page.** Sorting a filter that matches 13,000 rows to show 20 of them is a 13,000-element sort on every request.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}/delete-impact` - Preview what deleting this document would affect, without deleting it: `{would_be_blocked, impacts:[{relation, child_collection, child_field, on_delete, child_count, sample_child_ids, blocks}]}`. Read-only; follows the collection's read grant (a scoped key with a read rule may call it).
 
 **Filter grammar**: `field:op:value`, repeatable and ANDed. On documents it is the `?filter=` query param; on vector search it is the `filters` body array. The same grammar, operators and semantics apply to both, because the database evaluates them.
@@ -227,7 +233,13 @@ Requires a `kind=vector` collection. Vectors are stored with cosine-similarity i
 All settings endpoints require an admin key.
 
 - `GET  /api/v1/settings` - Return current settings as JSON. `openai_api_key` is masked: the field is absent and `openai_api_key_set` (bool) indicates whether a key is configured.
-- `PUT  /api/v1/settings` `{openai_api_base?, openai_api_key?, default_embedding_model?, cors_origins?, session_ttl_minutes?, webui_enabled?, default_project?, embedding_connect_timeout_sec?, embedding_read_timeout_sec?, embedding_cache_size?, embedding_cache_ttl_sec?, embedding_cache_max_bytes?, embedding_cache_normalize?, embedding_client_pool_size?, captcha_provider?, captcha_secret?, captcha_verify_url?}` - Merge the supplied fields into the current settings and persist. Omit `openai_api_key` or `captcha_secret` (or pass an empty string) to keep the existing secret. Changes are hot-reloaded immediately; cache settings are applied instantly via `reconfigure()`.
+- `PUT  /api/v1/settings` `{openai_api_base?, openai_api_key?, default_embedding_model?, cors_origins?, session_ttl_minutes?, webui_enabled?, default_project?, embedding_connect_timeout_sec?, embedding_read_timeout_sec?, embedding_cache_size?, embedding_cache_ttl_sec?, embedding_cache_max_bytes?, embedding_cache_normalize?, embedding_client_pool_size?, captcha_provider?, captcha_secret?, captcha_verify_url?, client_ip_header?, client_ip_header_is_list?, trusted_proxy_cidrs?}` - Merge the supplied fields into the current settings and persist. Omit `openai_api_key` or `captcha_secret` (or pass an empty string) to keep the existing secret. Changes are hot-reloaded immediately; cache settings are applied instantly via `reconfigure()`.
+
+**Who the server thinks is calling** (`client_ip_header`, `client_ip_header_is_list`, `trusted_proxy_cidrs`). These decide the address a function policy's `ip_allow` is matched against, and the address written to the server's own access log. The rule that matters: a header is believed **only when the request arrived from an address in `trusted_proxy_cidrs`** - a header is text the client writes, so otherwise the caller would choose its own answer. Defaults are `X-Real-IP`, not-a-list, and loopback, which is what nginx in front of a loopback-bound vectorapi produces.
+- `client_ip_header: ""` reads no header at all and treats the peer address as the caller. That is the correct setting when nothing proxies the port.
+- `client_ip_header_is_list: true` for an `X-Forwarded-For` style header. The **last** element is used, not the first: nginx's `$proxy_add_x_forwarded_for` is "whatever the client sent, plus the real peer appended", so the first element is caller-controlled and only the last was vouched for by the proxy.
+- A `trusted_proxy_cidrs` entry that is not a CIDR range or bare address is refused with **422 `validation`** naming the entry, rather than dropped silently: a typo that disabled proxy trust would make every request appear to come from the proxy, which still looks like an address and so goes unnoticed.
+- **Getting these wrong refuses every caller of a function that uses `ip_allow`, not merely the wrong ones.** That is the deliberate fail-closed direction.
 
 ## Project embedding settings
 
@@ -376,7 +388,8 @@ export default async function (ctx) {
 - `GET  /api/v1/projects/{project}/functions/{id}` - Get one function, **including** `source`.
 - `PUT  /api/v1/projects/{project}/functions/{id}` `{source, path?}` - Push code. The id the script declares must equal the id in the URL; a mismatch is **422** `id_mismatch` (with `error.details.declared` and `error.details.url`) rather than a rename, because the URL would otherwise move code onto another function's policy. A PUT to an unused id registers it (**201**).
 - `DELETE /api/v1/projects/{project}/functions/{id}` - Delete the function, its code and its policy.
-- `PUT  /api/v1/projects/{project}/functions/{id}/policy` `{policy:{rules, origins?, rate_limit_per_min?, expires_at?}}` **(admin)** - Replace what the function may touch. Same vocabulary as a key scope (`rules` of `{collection, ops}` over `read`/`list`/`search`/`insert`/`update`/`delete`), with one difference: an **empty** rule set is legal and means the function reaches nothing. This is the only route that changes a policy.
+- `PUT  /api/v1/projects/{project}/functions/{id}/policy` `{policy:{rules, origins?, ip_allow?, rate_limit_per_min?, expires_at?}}` **(admin)** - Replace what the function may touch. Same vocabulary as a key scope (`rules` of `{collection, ops}` over `read`/`list`/`search`/`insert`/`update`/`delete`), with one difference: an **empty** rule set is legal and means the function reaches nothing. This is the only route that changes a policy.
+  - `ip_allow` (array of CIDR ranges or bare addresses, default empty = no restriction) pins the function to caller addresses. **It fails closed**: a non-empty list refuses any request whose address the server could not establish, so a wrong `trusted_proxy_cidrs` refuses everyone rather than the wrong ones. A malformed entry is refused at write time with 422 `validation`; one that somehow reached storage removes only itself and never widens the list. Checked **before** authentication and before the rate limit, so a refused caller cannot spend the function's minute budget - and the refusal writes **no run-log row**, because nothing ran.
 - `PUT  /api/v1/projects/{project}/functions/{id}/enabled` `{enabled}` - Enable or disable a function.
 - `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method.
   **THE BODY IS AN ENVELOPE DESCRIBING THE REQUEST TO SYNTHESISE, NOT THE FUNCTION'S PAYLOAD - and getting that wrong used to answer 200.** A payload goes under `body`:
@@ -398,6 +411,11 @@ export default async function (ctx) {
   - The key is used for the gate and is **not** forwarded to the function - `Authorization` has always been stripped - so a function cannot see, log or reuse the caller's credential.
 - **A key-gated function (`auth: 'key'`) AUTHENTICATES the caller and grants them NOTHING - so send your LEAST privileged key, not one scoped to the collections the function reads.** The function still reads and writes under its own stored policy, exactly as it does when public; the key only answers "may this caller invoke the route at all". A key with an empty rule set works and is the right choice. Worth stating because the natural guess is the opposite - that a function reading `kb_facts` needs a caller key carrying `search` on `kb_facts` - and guessing that way over-grants a credential that is, by design, going into a third-party tool configuration. Reported by a consumer who used a least-privileged key, found it worked, and pointed out that nothing said so.
   **Order the rollout header-first.** Put the `Authorization` header into the calling tool, confirm it works against the still-ungated route, and only then set `auth: 'key'`. Reversed, the route answers 401 for however long it takes someone to notice - and in front of an assistant or voice agent that presents as "it does not know anything" rather than as an auth failure.
+- **A function policy may pin the route to caller ADDRESSES** (`ip_allow`, 0.18.2+). Outside the list is **403** `ip_not_allowed`. Four properties, none of them guessable:
+  - **It is checked FIRST**, ahead of the `auth: 'key'` gate and ahead of the rate limit. So a caller who is not permitted to be here cannot spend the function's minute budget, and cannot have a token checked.
+  - **The refusal writes NO run-log row**, because nothing ran. That matters if you currently gate a public function with a token compared inside the script: a script-side check RUNS the function first, so every wrong-token request appends a row to your own run log, and a sustained flood evicts your real runs. An address gate refuses before the runner is involved.
+  - **It fails closed.** A non-empty list refuses any request whose address the server could not establish, so a wrong `trusted_proxy_cidrs` in global settings refuses *everyone* rather than the wrong ones.
+  - **The message does not echo your address back.** It is in the server's own access log for an operator to read; reflecting it would hand a prober a free "what do you think my address is" oracle. Ask an operator rather than guessing from the response.
 - **The function's `rate_limit_per_min` policy now applies to CALLS on this route** (since 0.15.0), not only to the function's data access. `0` means unlimited, as everywhere else. Over the ceiling is **429** `rate_limited` with `Retry-After: 60`. Three things worth knowing:
   - **The two ceilings are counted SEPARATELY against the same number.** A limit of 60 means up to 60 calls a minute AND up to 60 data operations a minute; it does not mean a function doing three reads per call gets 15 calls. Adding a read to a script therefore cannot lower its own request ceiling.
   - **The ceiling is per FUNCTION, not per caller.** It bounds the DAMAGE - mail sent, paid API calls made, on the tenant's quota and sender reputation - rather than the denial: one abusive caller can still exhaust a public function's minute and shut out legitimate ones. Per-caller limiting needs an identity, which is what `auth: 'key'` gives you and an anonymous request does not have.

+ 71 - 1
api/openapi.json

@@ -257,6 +257,17 @@
           "expires_at": {
             "type": "integer",
             "description": "Unix epoch seconds after which the policy is treated as expired. 0 means never."
+          },
+          "ip_allow": {
+            "type": "array",
+            "items": {
+              "type": "string"
+            },
+            "description": "CIDR ranges or bare addresses the caller must come from. Empty (the default) means no address restriction. FAILS CLOSED: a non-empty list refuses any request whose address the server could not establish, so a wrong `trusted_proxy_cidrs` in global settings refuses every caller rather than the wrong ones. Checked BEFORE the auth gate and before the rate limit, so a refused caller cannot spend the function's minute budget; the refusal writes no run-log row because nothing ran. Outside the list is 403 `ip_not_allowed`, and the message deliberately does not echo the caller's address back. A malformed entry is refused at write time with 422 `validation`; one already in storage removes only itself and never widens the list.",
+            "example": [
+              "203.0.113.0/24",
+              "198.51.100.7"
+            ]
           }
         }
       },
@@ -608,6 +619,14 @@
           "expires_at": {
             "type": "integer",
             "description": "Unix epoch seconds after which the key is treated as expired (auth returns 401). 0 means the key never expires."
+          },
+          "ip_allow": {
+            "type": "array",
+            "items": {
+              "type": "string"
+            },
+            "readOnly": true,
+            "description": "NOT SUPPORTED ON A KEY and refused with 422 `unsupported_option` rather than stored. Nothing checks it for an API key, and a security control that reads back from the server while never being applied is worse than an absent one. It is a FUNCTION POLICY field (PUT /api/v1/projects/{project}/functions/{id}/policy). For a browser key use `origins`; a server-side key has no address control today, because a non-browser client sends no Origin."
           }
         },
         "required": [
@@ -1428,7 +1447,16 @@
                       }
                     },
                     "count": {
-                      "type": "integer"
+                      "type": "integer",
+                      "description": "The number of rows in THIS PAGE, not the number matching the filters. See `total` for that. Kept with its original meaning rather than redefined, so existing callers are unaffected."
+                    },
+                    "has_more": {
+                      "type": "boolean",
+                      "description": "Whether rows matching the filters remain beyond this page. Emitted unconditionally, true or false, so an absent field means exactly one thing - a server older than 0.18.2 - and never \"nothing worth reporting\". Prefer this over a short page to decide whether to continue: omitting `limit` yields 100 rows, which is indistinguishable from a set that really holds 100."
+                    },
+                    "total": {
+                      "type": "integer",
+                      "description": "Exact number of rows matching the filters, computed by the database before pagination and NOT capped by `limit`. Nothing else here answers a multi-field filter: indexes/{field}/values counts one field over the whole collection. New in 0.18.2; before it, callers had to page an entire matching set to learn its size. Note `limit` does not bound the server's work - the whole match set is built and sorted before pagination - so this number is free, while a narrow filter does not make the read cheaper."
                     }
                   }
                 }
@@ -4180,6 +4208,27 @@
                     },
                     "captcha_verify_url": {
                       "type": "string"
+                    },
+                    "client_ip_header": {
+                      "type": "string",
+                      "description": "Header carrying the caller's address, believed ONLY when the request arrived from an address in `trusted_proxy_cidrs`. Default `X-Real-IP`. Empty string means read no header and treat the peer address as the caller, which is correct when nothing proxies the port.",
+                      "example": "X-Real-IP"
+                    },
+                    "client_ip_header_is_list": {
+                      "type": "boolean",
+                      "description": "True for an X-Forwarded-For style comma list. The LAST element is used, not the first: nginx's $proxy_add_x_forwarded_for is the client's own header with the real peer appended, so the first element is caller-controlled and only the last was vouched for by the proxy.",
+                      "example": false
+                    },
+                    "trusted_proxy_cidrs": {
+                      "type": "array",
+                      "items": {
+                        "type": "string"
+                      },
+                      "description": "Peers whose `client_ip_header` may be believed. Defaults to loopback. An empty array trusts no proxy and degrades to the peer address. An entry that is not a CIDR range or bare address is refused with 422 `validation` naming the entry rather than dropped silently.",
+                      "example": [
+                        "127.0.0.0/8",
+                        "::1/128"
+                      ]
                     }
                   }
                 }
@@ -4275,6 +4324,27 @@
                   "captcha_verify_url": {
                     "type": "string",
                     "description": "Full URL of the CAPTCHA verify endpoint (e.g. https://challenges.cloudflare.com/turnstile/v0/siteverify)"
+                  },
+                  "client_ip_header": {
+                    "type": "string",
+                    "description": "Header carrying the caller's address, believed ONLY when the request arrived from an address in `trusted_proxy_cidrs`. Default `X-Real-IP`. Empty string means read no header and treat the peer address as the caller, which is correct when nothing proxies the port.",
+                    "example": "X-Real-IP"
+                  },
+                  "client_ip_header_is_list": {
+                    "type": "boolean",
+                    "description": "True for an X-Forwarded-For style comma list. The LAST element is used, not the first: nginx's $proxy_add_x_forwarded_for is the client's own header with the real peer appended, so the first element is caller-controlled and only the last was vouched for by the proxy.",
+                    "example": false
+                  },
+                  "trusted_proxy_cidrs": {
+                    "type": "array",
+                    "items": {
+                      "type": "string"
+                    },
+                    "description": "Peers whose `client_ip_header` may be believed. Defaults to loopback. An empty array trusts no proxy and degrades to the peer address. An entry that is not a CIDR range or bare address is refused with 422 `validation` naming the entry rather than dropped silently.",
+                    "example": [
+                      "127.0.0.0/8",
+                      "::1/128"
+                    ]
                   }
                 }
               }

+ 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

+ 7 - 1
src/apikey.cpp

@@ -97,6 +97,8 @@ KeyScope KeyScope::fromJson(const nlohmann::json& j) {
     }
     if (j.contains("origins") && j["origins"].is_array())
         s.origins = j["origins"].get<std::vector<std::string>>();
+    if (j.contains("ip_allow") && j["ip_allow"].is_array())
+        s.ipAllow = j["ip_allow"].get<std::vector<std::string>>();
     s.rateLimitPerMin = j.value("rate_limit_per_min", 0u);
     s.expiresAt       = j.value("expires_at", 0ull);
     return s;
@@ -110,7 +112,11 @@ nlohmann::json KeyScope::toJson() const {
         rules_j.push_back({{"collection", r.collection}, {"ops", ops_j},
                            {"require_human_token", r.requireHumanToken}});
     }
-    return {{"rules", rules_j}, {"origins", origins},
+    // ip_allow is emitted ALWAYS, including as an empty array. Omitting it when
+    // empty would make "no restriction" and "this server does not know the
+    // field" indistinguishable, which is this codebase's most repeated trap -
+    // the same reason `scope_filtered` is sent unconditionally.
+    return {{"rules", rules_j}, {"origins", origins}, {"ip_allow", ipAllow},
             {"rate_limit_per_min", rateLimitPerMin}, {"expires_at", expiresAt}};
 }
 

+ 24 - 0
src/apikey.hpp

@@ -20,6 +20,30 @@ struct KeyScopeRule {
 struct KeyScope {
     std::vector<KeyScopeRule> rules;
     std::vector<std::string> origins;  // empty = any origin allowed
+    /// CIDR ranges (or bare addresses) the caller must come from. EMPTY = any.
+    ///
+    /// ENFORCED ON FUNCTION POLICIES ONLY, and the key route REFUSES it rather
+    /// than storing it, because a security control that is accepted and
+    /// silently not applied is the worst thing in this file's vocabulary. The
+    /// "refuse what you cannot honour" rule, applied to ourselves.
+    ///
+    /// It is the server-side sibling of `origins`, and it closes a gap that one
+    /// cannot: an Origin header is sent by browsers, so a key meant for
+    /// server-to-server use can never satisfy an origin allow-list and must
+    /// carry none - which leaves exactly the keys with the widest blast radius
+    /// with no network restriction available to them. An address can be
+    /// checked for any caller.
+    ///
+    /// FAILS CLOSED: a non-empty list with no trustworthy client address
+    /// refuses, which mirrors `originAllowed("")` being false for a non-empty
+    /// origin list. The cost is stated rather than discovered - misconfigure
+    /// `trusted_proxy_cidrs` and every caller is refused rather than the wrong
+    /// ones - and the owner accepted that trade deliberately on 2026-11-19.
+    ///
+    /// The MEMBERSHIP TEST is `functions::addressAllowedBy`, not a method here:
+    /// this struct is pure data compiled standalone by several narrow test
+    /// targets, and giving it CIDR parsing broke four of them.
+    std::vector<std::string> ipAllow;
     uint32_t rateLimitPerMin = 0;      // 0 = unlimited
     uint64_t expiresAt       = 0;      // epoch seconds; 0 = never
     const KeyScopeRule* findRule(const std::string& collection, KeyOp op) const;

+ 90 - 0
src/client_ip.cpp

@@ -0,0 +1,90 @@
+#include "client_ip.hpp"
+#include "server.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;
+}
+
+std::string clientIpFor(const httplib::Request& req, const Settings& settings) {
+    const std::string headerValue =
+        settings.clientIpHeader.empty()
+            ? std::string()
+            : req.get_header_value(settings.clientIpHeader.c_str());
+    return resolveClientIp(req.remote_addr, headerValue,
+                           clientIpConfigFrom(settings.clientIpHeader,
+                                              settings.clientIpHeaderIsList,
+                                              settings.trustedProxyCidrs));
+}
+
+} // 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}};

+ 12 - 0
src/functions/net_guard.cpp

@@ -257,6 +257,18 @@ bool cidrContains(const CidrRange& range, const std::string& ip) {
     return rangeContainsRaw(range, *addr);
 }
 
+bool addressAllowedBy(const std::vector<std::string>& cidrs, const std::string& ip) {
+    if (cidrs.empty()) return true;   // no restriction asked for
+    if (ip.empty()) return false;     // a restriction with no caller: fail closed
+    for (const auto& entry : cidrs) {
+        // A bad entry removes ITSELF. Treating the whole list as unusable would
+        // turn one typo into "allow everyone".
+        if (auto range = parseCidr(entry))
+            if (cidrContains(*range, ip)) return true;
+    }
+    return false;
+}
+
 // --- SsrfPolicy ------------------------------------------------------------
 
 const std::vector<std::string>& SsrfPolicy::defaultBlockedCidrs() {

+ 17 - 0
src/functions/net_guard.hpp

@@ -81,6 +81,23 @@ std::optional<CidrRange> parseCidr(const std::string& cidr);
 /// job, which is the function callers are supposed to use.
 bool cidrContains(const CidrRange& range, const std::string& ip);
 
+/// Allow-list membership: is `ip` inside ANY of these CIDR ranges?
+///
+/// Lives here rather than on `KeyScope` because that struct is pure data
+/// compiled standalone by several narrow test targets, and putting CIDR
+/// parsing on it made four of them fail to link - correctly, because an API key
+/// is not the place that knows how to parse a network range.
+///
+/// ALLOW-LIST SEMANTICS, which are the inverse of the blocklist above and the
+/// reason this is its own function rather than a loop at each call site:
+///   - an EMPTY list allows everything (no restriction was asked for);
+///   - a NON-EMPTY list refuses an empty or unparseable `ip` - FAILS CLOSED,
+///     because if a restriction was asked for and we cannot say who is
+///     calling, the honest answer is no;
+///   - a malformed ENTRY removes only itself and never widens the list, which
+///     is the one direction a security control must not fail in.
+bool addressAllowedBy(const std::vector<std::string>& cidrs, const std::string& ip);
+
 /// A set of blocked CIDR ranges plus the classification rules around it.
 class SsrfPolicy {
 public:

+ 41 - 2
src/handlers/documents.cpp

@@ -269,8 +269,47 @@ void registerDocumentRoutes(ApiServer& s) {
         // Each listed document carries the same `_id`/`_version` metadata a
         // single GET returns, so a filtered listing is a usable starting point
         // for a conditional write without a second round trip per row.
-        auto docs = d->db.client().find(t.qualified, opts);
-        sendJson(res, 200, {{"documents", docs}, {"count", docs.size()}});
+        //
+        // `findWithMetrics` RATHER THAN `find`, AND IT COSTS NOTHING. Both
+        // issue the identical single `Find` RPC with a byte-identical request
+        // (client.cpp:964 against :1033 at the 2.20.0 pin); `find` simply drops
+        // two fields of the response on the floor. The server computes both
+        // BEFORE pagination, so `total` is the exact number of rows matching
+        // the filters, not an estimate and not a page count.
+        //
+        // WHY IT MATTERS, measured with a consumer 2026-11-20: the only way to
+        // learn that number was to page the whole matching set, and for one
+        // real filter on a 13,093-row collection that is a full scan plus 1750
+        // documents of encoding to obtain one integer. A customer-facing review
+        // portal had just dropped its result count as unaffordable - for a
+        // number that was arriving in every response it already made and being
+        // discarded one frame short of the caller.
+        //
+        // `has_more` and `total`, matching the FILES listing (files.cpp) rather
+        // than the database's own `total_count` wire name. Two spellings for one
+        // concept across two of our own listing routes is exactly how the next
+        // drift starts, and this file already records what it costs when a
+        // caller learns a parameter's name on a sibling route.
+        //
+        // `count` is UNCHANGED and still the page size. Keeping it is the
+        // additive discipline `details.unsupported` kept: callers parse it
+        // today, and redefining a field in place is worse than adding two.
+        //
+        // Emitted UNCONDITIONALLY - unfiltered, empty, and on the last page -
+        // so an absent field means exactly one thing, a server older than this
+        // release. A flag present only when interesting is this codebase's most
+        // repeated trap.
+        //
+        // One asymmetry worth knowing before anyone extends this route:
+        // `findWithMetrics` has no `include_vector` parameter, where `find`
+        // grew one in 2.13.0. Behaviour is identical today because the 2-arg
+        // `find` defaults it to false and this listing never returned vectors,
+        // but "also return the vectors" cannot be built on this overload.
+        const auto page = d->db.client().findWithMetrics(t.qualified, opts);
+        sendJson(res, 200, {{"documents", page.documents},
+                            {"count", page.documents.size()},
+                            {"has_more", page.hasMore},
+                            {"total", page.totalCount}});
     });
 
     svr.Patch(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {

+ 43 - 2
src/handlers/function_dispatch.cpp

@@ -9,6 +9,7 @@
 // Because it is public, everything below treats the request path as hostile.
 #include "auth.hpp"
 #include "errors.hpp"
+#include "client_ip.hpp"
 #include "functions/trigger_body.hpp"
 #include "functions/descriptor.hpp"
 #include "function_error_dispatch.hpp"
@@ -292,6 +293,45 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
     // being refused. Authenticating first rejects that flood without charging
     // anything to the bucket the legitimate caller shares.
     const functions::FunctionDescriptor& desc = *match.descriptor;
+
+    // THE ADDRESS GATE RUNS FIRST, ahead of authentication and the throttle.
+    //
+    // Ordering is the same argument as authenticate-before-throttle, one step
+    // earlier: a caller who is not permitted to be here at all should not be
+    // able to spend the function's minute budget, nor to have its token
+    // checked. Refusing on the address costs a CIDR comparison and no lookup.
+    //
+    // It also means a refusal here writes NO run-log row, because nothing ran.
+    // That is the cheap refusal a tenant asked for: a function that checks its
+    // own token in script RUNS first, so every wrong-token request appends a
+    // row to that tenant's run log, and an address gate refuses before the
+    // runner is ever involved.
+    //
+    // FAILS CLOSED. A non-empty list with no trustworthy client address
+    // refuses - see KeyScope::ipAllowed. The consequence was accepted
+    // deliberately: get `trusted_proxy_cidrs` wrong and every caller is
+    // refused rather than the wrong ones.
+    //
+    // 403 and not 404: the route's existence is not the secret here, and a 404
+    // would be indistinguishable from a misspelled path for an operator
+    // debugging their own allow-list. The message deliberately does NOT echo
+    // the caller's address back - it is in our access log where an operator can
+    // read it, and reflecting it would hand a prober a free "what do you think
+    // my address is" oracle.
+    if (!policies[idx]->ipAllow.empty()) {
+        auto snap = d.settings.snapshot();
+        // The SAME resolution the access log uses, so the line an operator
+        // reads names the address this gate actually acted on.
+        const std::string clientIp = clientIpFor(req, *snap);
+        if (!functions::addressAllowedBy(policies[idx]->ipAllow, clientIp)) {
+            sendJson(res, 403,
+                     errorBody("ip_not_allowed",
+                               "this function is restricted to an address allow-list and the "
+                               "caller's address is not on it"));
+            return;
+        }
+    }
+
     if (desc.auth == functions::FnAuth::Key) {
         functions::FnAuthFacts facts;
         std::string token;
@@ -314,8 +354,9 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
             // logging a refusal would let an unauthenticated caller append a
             // row per request - turning a public URL into a write amplifier
             // against the tenant's own storage. Nothing ran, so there is no
-            // run to record. The refusal is observable in the access log,
-            // which is nginx's job and costs us no writes.
+            // run to record. The refusal is observable in the access log -
+            // ours as well as nginx's since 0.18.2, where it carries the slug
+            // beside the resolved caller address - and costs us no writes.
             const int status =
                 gate.outcome == functions::FnGateOutcome::Unauthenticated ? 401 : 403;
             if (status == 401) res.set_header("WWW-Authenticate", "Bearer");

+ 22 - 0
src/handlers/functions.cpp

@@ -1,4 +1,5 @@
 #include "errors.hpp"
+#include "functions/net_guard.hpp"
 #include "function_error_dispatch.hpp"
 #include "function_record.hpp"
 #include "functions/invoke_envelope.hpp"
@@ -115,6 +116,27 @@ KeyScope parsePolicy(const nlohmann::json& body) {
                     throw ApiError(ErrCode::Unprocessable, "validation", "unknown op in policy");
         }
     }
+    if (p.contains("ip_allow")) {
+        // Validated HERE and tolerated at read time, the same split as
+        // trusted_proxy_cidrs: a typo refused at the door gets fixed now, while
+        // a bad entry that somehow reached storage removes only itself rather
+        // than widening the list to everyone.
+        if (!p["ip_allow"].is_array())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "policy.ip_allow must be an array of CIDR ranges or bare addresses; "
+                           "an empty array means no address restriction");
+        for (const auto& entry : p["ip_allow"]) {
+            if (!entry.is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "every policy.ip_allow entry must be a string");
+            const std::string text = entry.get<std::string>();
+            if (!svapi::functions::parseCidr(text))
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "policy.ip_allow entry '" + text +
+                                   "' is not a CIDR range or bare address",
+                               {{"entry", text}});
+        }
+    }
     return KeyScope::fromJson(p);
 }
 

+ 14 - 0
src/handlers/keys.cpp

@@ -22,6 +22,20 @@ static std::optional<KeyScope> parseScope(const nlohmann::json& body, bool admin
             if (!o.is_string() || !keyOpFromString(o.get<std::string>()))
                 throw ApiError(ErrCode::Unprocessable, "validation", "unknown op in scope");
     }
+    // REFUSED RATHER THAN IGNORED. `ip_allow` is enforced on FUNCTION policies
+    // and nothing checks it for an API key, so storing one here would create
+    // exactly the defect this codebase keeps meeting: a security control that
+    // is accepted, visible on a read-back, and silently never applied. An
+    // operator would believe a key was restricted to their office address.
+    // "Refuse what you cannot honour" - the rule we already applied to query
+    // parameters, turned on ourselves.
+    if (sj.contains("ip_allow") && !(sj["ip_allow"].is_array() && sj["ip_allow"].empty()))
+        throw ApiError(ErrCode::Unprocessable, "unsupported_option",
+                       "scope.ip_allow is not enforced for API keys and is therefore refused "
+                       "rather than stored; it applies to function policies "
+                       "(PUT /api/v1/projects/{p}/functions/{id}/policy). For a browser key use "
+                       "scope.origins.",
+                       {{"instead", "scope.origins"}});
     return KeyScope::fromJson(sj);
 }
 

+ 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);

+ 36 - 1
src/rate_limiter.cpp

@@ -1,14 +1,43 @@
 #include "rate_limiter.hpp"
 #include <chrono>
+#include <spdlog/spdlog.h>
 namespace svapi {
 RateLimiter::RateLimiter()
     : now_([]{ return std::chrono::duration_cast<std::chrono::seconds>(
           std::chrono::system_clock::now().time_since_epoch()).count(); }) {}
+
+void RateLimiter::sweepLocked(int64_t minute) {
+    // Every entry from a past minute is logically empty already - its count is
+    // reset on next use - so dropping it loses nothing and is what keeps the
+    // table proportional to callers PER MINUTE instead of callers ever seen.
+    for (auto it = windows_.begin(); it != windows_.end();)
+        it = (it->second.minute != minute) ? windows_.erase(it) : std::next(it);
+    if (overCapacity_ && windows_.size() < kMaxWindows) overCapacity_ = false;
+}
+
 bool RateLimiter::allow(const std::string& keyId, uint32_t limitPerMin) {
     if (limitPerMin == 0) return true;
     std::lock_guard<std::mutex> lk(mu_);
     int64_t minute = now_() / 60;
-    auto& w = windows_[keyId];
+    if (minute != lastSweptMinute_) {
+        sweepLocked(minute);
+        lastSweptMinute_ = minute;
+    }
+    auto it = windows_.find(keyId);
+    if (it == windows_.end()) {
+        if (windows_.size() >= kMaxWindows) {
+            // FAIL OPEN. See the header: refusing here would hand an attacker a
+            // way to lock out everyone else by filling the table.
+            if (!overCapacity_)
+                spdlog::warn("rate limiter at capacity ({} keys): new callers are "
+                             "untracked and therefore unlimited until the next minute",
+                             windows_.size());
+            overCapacity_ = true;
+            return true;
+        }
+        it = windows_.emplace(keyId, Window{}).first;
+    }
+    auto& w = it->second;
     if (w.minute != minute) { w.minute = minute; w.count = 0; }
     if (w.count >= limitPerMin) return false;
     ++w.count;
@@ -17,5 +46,11 @@ bool RateLimiter::allow(const std::string& keyId, uint32_t limitPerMin) {
 void RateLimiter::setClockForTesting(std::function<int64_t()> fn) {
     std::lock_guard<std::mutex> lk(mu_); now_ = std::move(fn);
 }
+std::size_t RateLimiter::trackedKeys() const {
+    std::lock_guard<std::mutex> lk(mu_); return windows_.size();
+}
+bool RateLimiter::overCapacity() const {
+    std::lock_guard<std::mutex> lk(mu_); return overCapacity_;
+}
 RateLimiter& rateLimiter() { static RateLimiter inst; return inst; }
 }

+ 47 - 1
src/rate_limiter.hpp

@@ -1,20 +1,66 @@
 #pragma once
+#include <cstddef>
 #include <cstdint>
 #include <functional>
 #include <mutex>
 #include <string>
 #include <unordered_map>
 namespace svapi {
+/// Fixed-window counters, keyed on whatever the caller decides identity is.
+///
+/// THE WINDOW IS FIXED, NOT SLIDING (`now / 60`), and that is observable: a
+/// burst spends the whole allowance at once and every later call in that
+/// wall-clock minute is refused rather than draining smoothly, and a burst
+/// straddling a boundary can land 2x the limit inside a rolling 60 s. A
+/// REFUSAL COSTS NOTHING - `allow()` increments only on the admitting path - so
+/// a client retrying a 429 is not digging its own counter deeper, which is the
+/// opposite of what most callers assume.
+///
+/// THE KEY SPACE IS BOUNDED, AND IT HAS TO BE NOW THAT IT IS NOT ONLY KEY IDS.
+/// `windows_` used to grow forever: every unseen key default-constructed an
+/// entry and nothing ever removed one. That was safe only because every key was
+/// an API key id and a deployment has a dozen of those - a property of the
+/// CALLERS, not of this class, written down nowhere. The moment anything is
+/// keyed on a source address the key space becomes attacker-controlled, and an
+/// unauthenticated flood against a public /fn route would grow this map without
+/// bound on a box that is already on swap. Two mechanisms, deliberately both:
+///   - a SWEEP when the minute advances, which is what makes the steady state
+///     proportional to callers-per-minute rather than to callers-ever; and
+///   - a hard CAP, because a flood inside one minute outruns any sweep.
+///
+/// AT THE CAP IT FAILS OPEN, which is the uncomfortable choice and the right
+/// one. Refusing unknown keys when the table is full would let an attacker
+/// deny service to everyone else by spraying addresses - a denial of service
+/// achieved by being refused, which is exactly the shape the /fn ordering rule
+/// already exists to prevent. A limiter bounds damage; it is not an
+/// authorization control, and it must not become one by accident.
 class RateLimiter {
 public:
+    /// Entries kept before new keys stop being tracked. ~100k x ~64 B is a few
+    /// MB, which fits a small box while being far above any honest caller
+    /// count.
+    static constexpr std::size_t kMaxWindows = 100000;
+
     RateLimiter();
     bool allow(const std::string& keyId, uint32_t limitPerMin); // true if under limit; 0 = unlimited
     void setClockForTesting(std::function<int64_t()> fn);
+
+    /// Tracked keys. For tests and for an operator asking whether the cap is
+    /// being reached; NOT a request counter.
+    std::size_t trackedKeys() const;
+    /// True once the cap has been hit since the last sweep, i.e. some keys are
+    /// currently untracked and therefore unlimited.
+    bool overCapacity() const;
+
 private:
+    void sweepLocked(int64_t minute);
+
     struct Window { int64_t minute = -1; uint32_t count = 0; };
     std::unordered_map<std::string, Window> windows_;
     std::function<int64_t()> now_;   // epoch seconds
-    std::mutex mu_;
+    int64_t lastSweptMinute_ = -1;
+    bool overCapacity_ = false;
+    mutable std::mutex mu_;
 };
 RateLimiter& rateLimiter();  // process singleton
 }

+ 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

+ 30 - 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,31 @@ 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 = clientIpFor(req, *snap);
+        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;

+ 14 - 0
src/server.hpp

@@ -16,6 +16,20 @@
 
 namespace svapi {
 
+/// The caller's address for THIS request, under the deployment's trusted-proxy
+/// rules. ONE implementation, deliberately.
+///
+/// It is used by two places that must never disagree: the address allow-list on
+/// a function policy, and the line written to our own access log. If those
+/// drifted, the log would name a different caller than the gate acted on -
+/// which is worse than having no log at all, because it is the artefact
+/// somebody reads during an incident and believes.
+///
+/// The decision itself is pure and lives in client_ip.hpp; this only pulls the
+/// three inputs out of an httplib request and the settings snapshot.
+std::string clientIpFor(const httplib::Request& req, const Settings& settings);
+
+
 struct ServerDeps {
     DbGateway& db;
     SettingsStore& settings;

+ 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

+ 16 - 1
tests/CMakeLists.txt

@@ -25,6 +25,18 @@ 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_ip_allow test_ip_allow.cpp)
+target_link_libraries(test_ip_allow PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_ip_allow)
+
+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 +242,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);
+}

+ 157 - 0
tests/test_api_integration.cpp

@@ -4708,6 +4708,81 @@ public:
 
 } // namespace
 
+// --- the ADDRESS gate ------------------------------------------------------
+//
+// Same no-runner trick as the auth gate below, and for the same reason: the
+// address check sits ahead of the runner check, so a refusal is observable
+// without one and a request that PASSES falls through to 503.
+//
+// The fixture's client connects from 127.0.0.1, which the default
+// `trusted_proxy_cidrs` trusts, so a test can set `X-Real-IP` and have it
+// BELIEVED. That is what makes the strongest form of these tests possible:
+// vary the caller's address and demand the answer varies with it, rather than
+// asserting a refusal that might equally be a dispatch refusing everything.
+namespace {
+svapi::KeyScope policyWithIpAllow(std::vector<std::string> cidrs) {
+    svapi::KeyScope s;
+    s.ipAllow = std::move(cidrs);
+    return s;
+}
+} // namespace
+
+TEST_F(ApiFixture, AFunctionWithAnAddressAllowListRefusesACallerOutsideIt) {
+    functions_->put(project_, fnRow("ipgate", "public"),
+                    policyWithIpAllow({"203.0.113.0/24"}));
+    auto anon = noAuth();
+    auto res = anon.Get(("/fn/" + project_ + "/ipgate").c_str());
+    ASSERT_TRUE(res);
+    EXPECT_EQ(res->status, 403) << res->body;
+    EXPECT_EQ(nlohmann::json::parse(res->body)["error"]["code"], "ip_not_allowed") << res->body;
+    // The refusal must not hand a prober its own apparent address back.
+    EXPECT_EQ(res->body.find("127.0.0.1"), std::string::npos)
+        << "the message must not echo the caller's address: " << res->body;
+}
+
+// THE PAIRING, and it varies the INPUT rather than the policy: the same
+// function, the same list, a different caller address. Without this the test
+// above would pass just as well against a dispatch that refused everything.
+TEST_F(ApiFixture, TheSameFunctionADMITSACallerInsideTheListAndReachesTheRunnerCheck) {
+    functions_->put(project_, fnRow("ipgate2", "public"),
+                    policyWithIpAllow({"203.0.113.0/24"}));
+    auto anon = noAuth();
+    httplib::Headers h{{"X-Real-IP", "203.0.113.9"}};
+    auto res = anon.Get(("/fn/" + project_ + "/ipgate2").c_str(), h);
+    ASSERT_TRUE(res);
+    // 503 because this deployment has no runner: the request got PAST the
+    // address gate and died on the next check down.
+    EXPECT_EQ(res->status, 503) << res->body;
+    EXPECT_EQ(nlohmann::json::parse(res->body)["error"]["code"], "runner_unavailable")
+        << res->body;
+}
+
+TEST_F(ApiFixture, AnEmptyAllowListRestrictsNothing) {
+    functions_->put(project_, fnRow("ipgate3", "public"), policyWithIpAllow({}));
+    auto anon = noAuth();
+    auto res = anon.Get(("/fn/" + project_ + "/ipgate3").c_str());
+    ASSERT_TRUE(res);
+    EXPECT_EQ(res->status, 503) << "no list means no restriction: " << res->body;
+}
+
+// THE ORDERING, which is the load-bearing claim and the one a later edit is
+// most likely to break by moving the check somewhere tidier. A function that
+// is BOTH key-gated and address-restricted, called anonymously from a
+// disallowed address, must answer the ADDRESS refusal - not 401. If this
+// returns `unauthorized`, the address check has been moved after the auth
+// gate, and a caller who has no business here can once again make us look up
+// a token and charge a rate-limit bucket.
+TEST_F(ApiFixture, TheAddressGateRunsBEFOREAuthenticationSoARefusedCallerIsNeverLookedUp) {
+    functions_->put(project_, fnRow("ipgate4", "key"),
+                    policyWithIpAllow({"203.0.113.0/24"}));
+    auto anon = noAuth();
+    auto res = anon.Get(("/fn/" + project_ + "/ipgate4").c_str());
+    ASSERT_TRUE(res);
+    EXPECT_EQ(res->status, 403) << res->body;
+    EXPECT_EQ(nlohmann::json::parse(res->body)["error"]["code"], "ip_not_allowed")
+        << "a 401 here would mean the address gate moved after authentication: " << res->body;
+}
+
 TEST_F(ApiFixture, AGatedFunctionRefusesAnAnonymousCallerAndNamesHowToAuthenticate) {
     functions_->put(project_, fnRow("gated", "key"), svapi::KeyScope{});
 
@@ -5003,3 +5078,85 @@ TEST_F(ApiFixture, PatchReportsAnAbsentDocumentWithoutAnExistenceProbe) {
     EXPECT_EQ(body["v"], 1) << "the empty patch or the merge dropped an existing field";
     EXPECT_EQ(body["w"], 2);
 }
+
+// --- the documents listing's paging metadata ---------------------------------
+//
+// `total` and `has_more` are computed by the database BEFORE pagination and
+// were being discarded by our handler, which sent only `count` - the PAGE size.
+// A consumer therefore had to page an entire matching set to learn how big it
+// was, and one measured instance of that was a full scan plus 1750 documents of
+// encoding to obtain a single integer.
+
+TEST_F(ApiFixture, TheDocumentsListingReportsTheFILTEREDTotalNotThePageOrTheCollection) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","pagemeta"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/pagemeta/documents";
+    // SEVEN rows, FOUR of which match. Three distinct numbers - page 2, match
+    // total 4, collection 7 - so confusing any pair of them fails this test.
+    // With one shared number the assertions would pass under every mix-up.
+    for (const char* k : {"yes", "yes", "yes", "yes", "no", "no", "no"})
+        ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"flag", k}}.dump(),
+                         "application/json")->status, 201);
+
+    auto first = c.Get((docs + "?filter=flag:eq:yes&limit=2").c_str());
+    ASSERT_TRUE(first); ASSERT_EQ(first->status, 200);
+    const nlohmann::json a = nlohmann::json::parse(first->body);
+    // PRESENCE BEFORE VALUE, in every arm. Indexing a missing key with
+    // `operator[]` on a const json ASSERTS inside nlohmann and aborts the whole
+    // binary - which in a suite that must run serially would take every later
+    // test with it and report the regression as a crash rather than as a named
+    // failing assertion. Found by deliberately falsifying this test.
+    ASSERT_TRUE(a.contains("total")) << "the listing stopped reporting `total`";
+    ASSERT_TRUE(a.contains("has_more")) << "the listing stopped reporting `has_more`";
+    EXPECT_EQ(a["documents"].size(), 2u);
+    EXPECT_EQ(a["count"], 2) << "`count` must stay the PAGE size; callers parse it already";
+    EXPECT_EQ(a["total"], 4) << "the filtered match total, not the page (2) and not the "
+                                "collection (7)";
+    EXPECT_TRUE(a["has_more"].get<bool>());
+
+    // The PAIRING, and the half that makes `has_more` worth sending: the last
+    // page must say false while `total` is unchanged. Without this arm a
+    // handler hardcoding `true` would pass the assertion above.
+    auto last = c.Get((docs + "?filter=flag:eq:yes&limit=2&offset=2").c_str());
+    ASSERT_TRUE(last); ASSERT_EQ(last->status, 200);
+    const nlohmann::json b = nlohmann::json::parse(last->body);
+    ASSERT_TRUE(b.contains("total")); ASSERT_TRUE(b.contains("has_more"));
+    EXPECT_EQ(b["documents"].size(), 2u);
+    EXPECT_EQ(b["total"], 4);
+    EXPECT_FALSE(b["has_more"].get<bool>()) << "a full page and the LAST page must not look "
+                                               "identical - that was the original defect";
+
+    // Unfiltered, the total is the whole collection. Pins that the filter is
+    // what narrows `total`, rather than `total` happening to equal some
+    // constant this collection has.
+    auto all = c.Get((docs + "?limit=1").c_str());
+    ASSERT_TRUE(all); ASSERT_EQ(all->status, 200);
+    const nlohmann::json u = nlohmann::json::parse(all->body);
+    ASSERT_TRUE(u.contains("total"));
+    EXPECT_EQ(u["total"], 7);
+}
+
+TEST_F(ApiFixture, ThePagingFieldsArePRESENTEvenWhenNothingMatches) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","pagempty"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/pagempty/documents";
+    ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"flag","no"}}.dump(),
+                     "application/json")->status, 201);
+
+    auto r = c.Get((docs + "?filter=flag:eq:nothingmatchesthis").c_str());
+    ASSERT_TRUE(r); ASSERT_EQ(r->status, 200);
+    const nlohmann::json body = nlohmann::json::parse(r->body);
+    // KEY PRESENCE is the assertion, not the value. It is what makes "the field
+    // is absent" mean exactly one thing - a server older than this release -
+    // rather than also meaning "there was nothing interesting to report". A
+    // field emitted only when true is this codebase's most repeated trap.
+    ASSERT_TRUE(body.contains("total"));
+    ASSERT_TRUE(body.contains("has_more"));
+    EXPECT_EQ(body["total"], 0);
+    EXPECT_FALSE(body["has_more"].get<bool>());
+    EXPECT_TRUE(body["documents"].empty());
+}

+ 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("[]"));
+}

+ 82 - 0
tests/test_ip_allow.cpp

@@ -0,0 +1,82 @@
+#include "apikey.hpp"
+#include "functions/net_guard.hpp"
+#include <gtest/gtest.h>
+
+using namespace svapi;
+
+namespace {
+/// The subject is the membership decision, which lives beside the CIDR code
+/// rather than on KeyScope - see net_guard.hpp on why.
+bool allowed(const std::vector<std::string>& list, const std::string& ip) {
+    return svapi::functions::addressAllowedBy(list, ip);
+}
+} // namespace
+
+TEST(IpAllow, AnEmptyListMeansNoRestriction) {
+    EXPECT_TRUE(allowed({}, "203.0.113.9"));
+    // Including for a caller we could not identify: no list, no question.
+    EXPECT_TRUE(allowed({}, ""));
+}
+
+TEST(IpAllow, AMemberIsAllowedAndANonMemberIsNot) {
+    const std::vector<std::string> s = {"203.0.113.0/24", "198.51.100.7"};
+    EXPECT_TRUE(allowed(s, "203.0.113.9"));
+    EXPECT_TRUE(allowed(s, "198.51.100.7"));   // bare address is a host route
+    EXPECT_FALSE(allowed(s, "203.0.114.9"));
+    EXPECT_FALSE(allowed(s, "198.51.100.8"));
+}
+
+TEST(IpAllow, IPv6RangesWork) {
+    const std::vector<std::string> s = {"2001:db8::/32"};
+    EXPECT_TRUE(allowed(s, "2001:db8::5"));
+    EXPECT_FALSE(allowed(s, "2001:db9::5"));
+    // A family mismatch is simply not a member, not an error.
+    EXPECT_FALSE(allowed(s, "203.0.113.9"));
+}
+
+// --- the two directions a security control can fail -------------------------
+
+TEST(IpAllow, ANonEmptyListFAILSCLOSEDOnAnAddressWeCouldNotEstablish) {
+    const std::vector<std::string> s = {"203.0.113.0/24"};
+    // Mirrors originAllowed("") being false for a non-empty origin list: if a
+    // restriction is asked for and we cannot say who is calling, the answer is
+    // no. This is the arm that makes a wrong trusted_proxy_cidrs refuse
+    // everyone, which the owner accepted deliberately.
+    EXPECT_FALSE(allowed(s, ""));
+    EXPECT_FALSE(allowed(s, "not-an-address"));
+}
+
+TEST(IpAllow, AMalformedEntryRemovesONLYITSELFAndNeverWidensTheList) {
+    // The one direction this must never fail in: a typo turning the list into
+    // "allow everyone". It removes itself and the good entry still decides.
+    const std::vector<std::string> s = {"not-a-cidr", "203.0.113.0/24"};
+    EXPECT_TRUE(allowed(s, "203.0.113.9"));
+    EXPECT_FALSE(allowed(s, "198.51.100.1"));
+
+    // And a list of NOTHING BUT typos refuses everything rather than allowing
+    // it, because the list is still non-empty: the operator asked for a
+    // restriction and we cannot honour it.
+    const std::vector<std::string> broken = {"not-a-cidr", "999.999.999.999/8"};
+    EXPECT_FALSE(allowed(broken, "203.0.113.9"));
+}
+
+// --- round trip, since the field has to survive storage ---------------------
+
+TEST(IpAllow, SurvivesAJsonRoundTripAndIsAlwaysEmitted) {
+    KeyScope scope;
+    scope.ipAllow = {"203.0.113.0/24"};
+    const nlohmann::json j = scope.toJson();
+    ASSERT_TRUE(j.contains("ip_allow"));
+    EXPECT_EQ(j["ip_allow"].size(), 1u);
+    const KeyScope back = KeyScope::fromJson(j);
+    EXPECT_EQ(back.ipAllow, scope.ipAllow);
+    EXPECT_TRUE(allowed(back.ipAllow, "203.0.113.9"));
+
+    // Emitted even when empty: "no restriction" and "this server does not know
+    // the field" must not look the same, which is this codebase's most
+    // repeated trap.
+    KeyScope none;
+    EXPECT_TRUE(none.toJson().contains("ip_allow"));
+    EXPECT_TRUE(none.toJson()["ip_allow"].is_array());
+    EXPECT_TRUE(none.toJson()["ip_allow"].empty());
+}

+ 49 - 0
tests/test_rate_limiter.cpp

@@ -17,3 +17,52 @@ TEST(RateLimiter, KeysAreIndependent) {
     EXPECT_TRUE(rl.allow("a",1)); EXPECT_FALSE(rl.allow("a",1));
     EXPECT_TRUE(rl.allow("b",1));
 }
+
+// --- the key space is bounded ------------------------------------------------
+//
+// `windows_` used to grow forever. That was safe only while every key was an
+// API key id; keyed on a source address it becomes attacker-controlled.
+
+TEST(RateLimiter, StaleWindowsAreSweptWhenTheMinuteAdvances) {
+    RateLimiter rl; int64_t t = 1000; rl.setClockForTesting([&]{ return t; });
+    for (int i = 0; i < 500; ++i) rl.allow("key-" + std::to_string(i), 10);
+    EXPECT_EQ(rl.trackedKeys(), 500u);
+    t += 60;
+    rl.allow("someone-else", 10);            // the call that triggers the sweep
+    // The 500 from the previous minute are gone, not merely reset: the steady
+    // state tracks callers PER MINUTE rather than callers ever seen.
+    EXPECT_EQ(rl.trackedKeys(), 1u);
+}
+
+TEST(RateLimiter, AFloodOfUNIQUEKeysInOneMinuteCannotGrowTheTableWithoutBound) {
+    RateLimiter rl; int64_t t = 1000; rl.setClockForTesting([&]{ return t; });
+    // A sweep cannot help inside a single minute, which is why the cap exists.
+    for (std::size_t i = 0; i < RateLimiter::kMaxWindows + 2000; ++i)
+        rl.allow("ip-" + std::to_string(i), 5);
+    EXPECT_LE(rl.trackedKeys(), RateLimiter::kMaxWindows);
+    EXPECT_TRUE(rl.overCapacity());
+}
+
+TEST(RateLimiter, AtCapacityANewKeyIsALLOWEDRatherThanRefused) {
+    RateLimiter rl; int64_t t = 1000; rl.setClockForTesting([&]{ return t; });
+    for (std::size_t i = 0; i < RateLimiter::kMaxWindows; ++i)
+        rl.allow("ip-" + std::to_string(i), 5);
+    ASSERT_EQ(rl.trackedKeys(), RateLimiter::kMaxWindows);
+    // Failing CLOSED here would let an attacker spraying addresses lock out
+    // every legitimate caller - a denial of service achieved by being refused.
+    EXPECT_TRUE(rl.allow("an-honest-caller-arriving-late", 1));
+    EXPECT_TRUE(rl.allow("an-honest-caller-arriving-late", 1));  // untracked, so unlimited
+}
+
+TEST(RateLimiter, CapacityClearsAfterASweepSoTheLimitComesBack) {
+    RateLimiter rl; int64_t t = 1000; rl.setClockForTesting([&]{ return t; });
+    for (std::size_t i = 0; i < RateLimiter::kMaxWindows + 10; ++i)
+        rl.allow("ip-" + std::to_string(i), 5);
+    ASSERT_TRUE(rl.overCapacity());
+    t += 60;
+    rl.allow("fresh", 5);
+    EXPECT_FALSE(rl.overCapacity());
+    // And the limit is enforced again for a key tracked after the sweep.
+    EXPECT_TRUE(rl.allow("fresh", 2));
+    EXPECT_FALSE(rl.allow("fresh", 2));
+}