Browse Source

feat: pin a function to caller addresses, and bound the limiter that made it possible

Two halves of one request: an admin-only address allow-list on a function
policy, and the eviction the rate limiter never had - which had to land first,
because per-caller keying is what makes an unbounded table dangerous.

THE ALLOW-LIST

`ip_allow` on a function policy (admin-only, like the policy route it lives on,
and never on the `on` block - a code push must not widen its own access, and an
author editing their own whitelist is exactly that). Outside the list is 403
`ip_not_allowed`.

Four decisions are load-bearing:

- CHECKED FIRST, ahead of the `auth: 'key'` gate and ahead of the throttle. Same
  argument as the existing authenticate-before-throttle rule, one step earlier: a
  caller with no business here must not be able to spend the function's minute
  budget, nor to have a token looked up. Pinned by an integration test that
  demands 403 `ip_not_allowed` rather than 401 from a key-gated function called
  anonymously from a disallowed address, and deliberately falsified by moving the
  gate below the auth block: exactly that test goes red and the other three stay
  green.

- A REFUSAL WRITES NO RUN-LOG ROW, because nothing ran. That is the cheap refusal
  a tenant actually needed: a function that compares a token inside the script
  RUNS first, so every wrong-token request from the open internet appends a row to
  that tenant's run log, and a sustained flood evicts their real runs. See the
  task filed about that write amplifier; this does not close it, it gives the one
  case an alternative.

- FAILS CLOSED, and the cost was approved rather than discovered: a non-empty list
  refuses any request whose address we could not establish, so a wrong
  `trusted_proxy_cidrs` refuses EVERY caller rather than the wrong ones. Mirrors
  `originAllowed("")` being false for a non-empty origin list.

- THE MESSAGE DOES NOT ECHO THE ADDRESS BACK. It is in our own access log where an
  operator can read it; reflecting it would hand a prober a free "what do you
  think my address is" oracle. A test asserts the body contains no address.

REFUSED ON API KEYS RATHER THAN STORED (422 `unsupported_option`). `KeyScope` is
shared between keys and function policies, and nothing checks an address for an
API key - so storing one would create this codebase's favourite defect: a
security control that reads back from the server and is silently never applied,
leaving an operator believing a key was pinned to their office. "Refuse what you
cannot honour", turned on ourselves. `origins` is the control that works for a
browser key; a server-side key has none today, because a non-browser client sends
no Origin - which is the gap an address list would eventually close.

THE LIMITER

`windows_` had no eviction of any kind. That was safe only because every key was
an API key id and a deployment has a dozen - a property of the CALLERS, not of
the class, written down nowhere. Keyed on an address it becomes attacker-
controlled, and an unauthenticated flood would grow it without bound on a box
already on swap. Now a sweep when the minute advances (so the steady state tracks
callers-per-minute, not callers-ever) plus a hard cap, both falsified
independently with the three original tests staying green in each case.

AT THE CAP IT FAILS OPEN, which is the uncomfortable direction and the right one:
refusing unknown keys when the table is full would let an attacker spraying
addresses deny service to everyone else - a denial of service achieved by being
refused. A limiter bounds damage; it must not become an authorization control by
accident.

TWO BOUNDARY ERRORS OF MINE, both caught by the build rather than by review, and
both the same shape

`ipAllowed()` started as a method on `KeyScope`, which put CIDR parsing into
`apikey.cpp` - compiled standalone by four narrow test targets, all of which
stopped linking. The failure was correct: an API key is not the place that knows
how to parse a network range. The membership test now lives in `net_guard.hpp`
beside the CIDR code, `KeyScope` holds only data, and the allow-list semantics
(empty allows, non-empty fails closed, a bad entry removes only itself) are
documented there as the deliberate inverse of the blocklist next to them.

Earlier in the same stretch the request trace went into `access_log.cpp` and
broke `test_project_secret_store` for the same reason. Those narrow targets exist
to keep these dependencies honest and they did it twice.

AND ONE DUPLICATION FOUND BY RE-READING MY OWN DIFF: the client-IP resolution was
copied into both the access-log writer and the dispatch gate. Had they drifted,
the log would have named a different caller than the gate acted on - worse than no
log, because it is the artefact somebody reads during an incident and believes.
One `clientIpFor()` now, with `resolveClientIp` down to a single call site.

Suite 1408/1408, 167.50 s, serial, with zero pending build steps before ctest -
stated because two earlier runs of this work were VOID: one exited 0 while 50
build steps were still pending, and one reported five tests "Not Run" because a
concurrent build was relinking their executable. A green suite over stale binaries
is a check that cannot fail.

`api/llms.txt` and `api/openapi.json` updated, including what the field does NOT
do and the fail-closed cost, since a silence there propagates as confidently as a
wrong sentence.
fszontagh 1 week ago
parent
commit
de7f5d5873

+ 15 - 2
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.
@@ -227,7 +228,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 +383,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 +406,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.

+ 61 - 0
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": [
@@ -4180,6 +4199,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 +4315,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"
+                    ]
                   }
                 }
               }

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

+ 12 - 0
src/client_ip.cpp

@@ -1,4 +1,5 @@
 #include "client_ip.hpp"
+#include "server.hpp"
 #include <algorithm>
 
 namespace svapi {
@@ -75,4 +76,15 @@ std::string resolveClientIp(const std::string& peer, const std::string& headerVa
     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

+ 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:

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

+ 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
 }

+ 1 - 6
src/server.cpp

@@ -238,12 +238,7 @@ void ApiServer::registerRoutes() {
         if (!accessLog().enabled()) return;
         auto snap = d_.settings.snapshot();
         AccessLogEntry e;
-        e.clientIp = resolveClientIp(
-            req.remote_addr,
-            snap->clientIpHeader.empty() ? std::string()
-                                         : req.get_header_value(snap->clientIpHeader.c_str()),
-            clientIpConfigFrom(snap->clientIpHeader, snap->clientIpHeaderIsList,
-                               snap->trustedProxyCidrs));
+        e.clientIp = clientIpFor(req, *snap);
         e.method = req.method;
         e.path = req.path;
         e.status = res.status;

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

+ 4 - 0
tests/CMakeLists.txt

@@ -29,6 +29,10 @@ 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)

+ 75 - 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{});
 

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