Kaynağa Gözat

feat: ctx.clientIp, named header withholdings, a per-caller throttle SV-26 SV-125

A consumer needs to move a customer review portal's e-mail-sending routes onto
/fn, and could not: a function cannot see who is calling it. Measured rather
than recalled, with the probe their own could not be - `Object.keys(ctx)` plus
an explicit test for eleven plausible spellings - fifteen keys and no address
under any of them. Their user believed it was already handled, which with a
probe incapable of contradicting it is how a per-IP throttle gets built on
`undefined`: one global bucket wearing a per-caller bucket's name.

ctx.clientIp IS THE RESOLVED ADDRESS, never a header the caller wrote. The
value already existed on this exact path - function_dispatch computed it for
the ip_allow gate and threw it away - so this carries it onward rather than
resolving anything new. It is now resolved ONCE for all four consumers (the
allow-list gate, the new throttle, ctx, the access log), which is what stops
them disagreeing about who the caller is.

`null`, never `""`, when there is no caller, and the property is set ALWAYS so
`'clientIp' in ctx` is the capability check while the value answers whether
this run had a caller. An empty string is the trap: it still reads as an
address to `typeof`.

NOTHING WAS WIDENED ABOUT HEADERS, BECAUSE NOTHING NEEDED TO BE. Asked to pass
"all possible headers", I found there is no allow-list and never was - any
header already arrives. The consumer's probe showed five names and that was
simply what their client sent. What was missing was the ability to tell "we
removed it" from "your client never sent it", which were the same observation.
`ctx.headersWithheld` names them; values never travel.

The five stay. Cookie is not an inconvenience: the admin UI shares this
origin, so a logged-in operator's browser attaches its session cookie to /fn
too, and forwarding it would hand that session to every function author in the
project. The right way to carry a browser session is a header of your own,
which already works.

The split moved to a PURE header, which is the real repair: the denylist is a
security boundary and lived in an anonymous namespace, so it could not be
tested at all, and the only way to observe it was to run a function - which a
deployment without a runner cannot do, and that is the default.

rate_limit_per_caller_per_min CLOSES THE DENIAL the per-function cap documents
and does not fix ("one abusive caller can still exhaust a public function's
minute"). Charged BEFORE the shared bucket, so an abusive caller is refused on
its own without spending anyone else's - the authenticate-before-throttle
argument one level down. Same slug as the per-function refusal on purpose:
naming which ceiling was hit lets a prober learn the other one's value, and
the remedy is identical. This was only possible because RateLimiter's key
space is now bounded; keyed on an address it is attacker-controlled.

FALSIFIED THREE WAYS, each confirmed red: reversing the two throttles reddens
the ordering test alone; dropping clientIp from the caller bucket reddens the
differing-caller pairing while the same-caller test stays green, which is what
proves the pairing carries the per-caller claim; a substring denylist reddens
the resembles-a-secret pairing.

Three mistakes of mine, all caught by controls rather than review. The first
version of the ctx field used operator[] on a CONST json, where a missing key
is undefined behaviour - every non-HTTP trigger lacks it, and it aborted all
160 HostContext tests. I then made the SAME mistake in the new test file,
where it turned a falsification into a crash that killed the rest of the
binary; the reads are abort-safe now. And a `git checkout` during falsification
cleanup reverted the bucket helper's definition while leaving its declaration,
which a link error caught - after a `grep -i error:` of mine had reported six
build errors by matching QJS_BUILD_WERROR, and a `>/dev/null` had hidden the
real one.

1535/1535 serial. llms.txt and openapi.json updated.
fszontagh 6 gün önce
ebeveyn
işleme
9d5c466c6c

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.21.1
+0.22.0

+ 3 - 0
api/llms.txt

@@ -530,6 +530,9 @@ export default async function (ctx) {
 - **Its RESOLUTION IS ONE SECOND, and the effective floor is 1 s per phase.** The HTTP client underneath takes whole seconds and treats 0 as "no timeout", so every value below 1000 ms resolves to the same thing: 1 s to connect plus 1 s to read. `embedTimeoutMs: 1` therefore allows up to **2 s**, not 1 ms, and a provider that answers inside that second succeeds normally - which reads exactly like the option being ignored. It is not: a value of 1 and a value of 999 are genuinely indistinguishable, and tuning inside that range does nothing. Ask for **2000 or more** if you want the split to be meaningful, and expect a timeout to surface at a whole-second boundary rather than at the millisecond you named. **From 0.18.1 the split favours the READ phase, and this changed because the old split was a defect.** Connect is capped at an absolute 2 s (operator setting `embedding_connect_cap_sec`) and still never takes more than half the available time, so a 6000 ms ask now becomes **2 s connect + 4 s read** where it previously became 3 s + 3 s. That mattered: a consumer whose voice agent asks for exactly 6000 ms was getting a THREE second read deadline, and the 504 then quoted 6000 ms - a number no phase ever had. A 4000 ms ask is unchanged at 2 s + 2 s, since half of four is already two. The two phases are SEQUENTIAL, so what the option bounds is their sum; it was never a promise that connect gets half. **The 504 message now names the deadline that was applied as well as the one you asked for**, so `embedTimeoutMs 6000ms was applied as connect 2s + read 4s` tells you where the time went without reading our source.
 - **A blocking host call cannot be interrupted.** The run's wall budget is enforced between bytecode operations, so while an embedding or `ctx.fetch` request is in flight the deadline cannot be noticed - the budget ends the run once the call returns. Host calls are bounded by giving them timeouts that already fit the remaining budget (connect **and** read together), not by preemption. For a hard latency ceiling, catch the error and have a fallback path.
 - `ctx.fetch(url, {method, headers, body, timeoutMs, responseType})` - outbound HTTP, **SSRF-guarded**: loopback, private and link-local destinations are refused, which means a function cannot call this API back. The refusal is reported in the run's console rather than as a network error.
+- **`ctx.clientIp` is the RESOLVED caller address, and `null` when there is no caller.** From 0.22.0. It is the same value the `ip_allow` policy gate and our access log act on - resolved through `client_ip_header`, `client_ip_header_is_list` and `trusted_proxy_cidrs` - so **it is NOT a header the caller wrote and cannot be spoofed by one.** That is the whole reason it exists rather than leaving you to read `X-Forwarded-For` out of `ctx.headers`: a throttle keyed on a caller-controlled value is not a throttle. A cron, job, db or error run has no request behind it and reads `null`. The property is **always present**, null included, so `'clientIp' in ctx` tells you the server supports it while the value tells you whether this run had a caller - an absent key would conflate the two. Null rather than `''` deliberately: an empty string still looks like an address to `typeof`, and bucketing on it gives you one shared counter wearing a per-caller counter's name.
+- **EVERY request header reaches your function except five, and the five are now NAMED rather than silently missing.** There is no allow-list and there never was: any header your client sends arrives under `ctx.headers`, lower-cased. The five withheld are **`cookie`, `set-cookie`, `authorization`, `proxy-authorization` and `x-captcha-token`**, and `ctx.headersWithheld` lists by NAME those that were present and removed (always an array, empty when nothing was). Values never travel, so this tells you a header was sent and nothing about what it held. **Cookie is withheld because the admin web UI is served from this same origin**, so a logged-in operator's browser attaches its session cookie to `/fn/*` too, and forwarding it would hand that operator's session to every function author in the project - a privilege escalation, not an inconvenience. `authorization` is the same argument for the credential that authenticated the call. **To carry a browser session, use a header of your own** (`X-My-Session`): it arrives untouched today and needs nothing from us. Matching is exact, so `X-Cookie-Preference` is forwarded normally. If you expected a header and do not see it, check `ctx.headersWithheld` - if it is not named there, your client or a proxy did not send it, which was previously indistinguishable from us removing it.
+- **`rate_limit_per_caller_per_min` throttles ONE CALLER, which `rate_limit_per_min` deliberately does not.** From 0.22.0, on a function's policy, keyed on the resolved caller address. The two are separate ceilings answering different questions and both are charged: the per-FUNCTION limit bounds the **damage** (mail sent, paid API spend) and says nothing about who caused it, so one abusive caller could exhaust a public function's minute and shut everyone else out. The per-caller limit bounds that. **0 means unlimited**, as everywhere else here. The per-caller bucket is charged FIRST, so an abusive caller is refused on its own bucket without spending the shared one - and a refusal costs nothing, so retrying a 429 does not dig the counter deeper. Both refusals answer **429 `rate_limited`** with the same message and `Retry-After`, deliberately: telling you which ceiling you hit would let you learn the other one's value by probing, and the remedy is the same either way. Only an HTTP request is charged against it; a cron or job run has no caller. Note the ceiling is per caller per FUNCTION, not per project.
 - **A job, cron or db run's `ctx` is NOT the HTTP shape.** It carries `trigger`, `depth`, `enqueued_by` and `enqueued_at_ms`, with your payload under **`ctx.body`** - there is no `ctx.method`, `ctx.path`, `ctx.query` or `ctx.params`. A cron payload is `{schedule, scheduled_at}`; a database-event payload is `{collection, table, id, event, document}`.
 - `ctx.mail` - **IMAP read and SMTP send.** Three calls, deliberately few, each opening one session and closing it. Connection fields are shared: `host`, `port` (optional, 0 or absent means the scheme default), `user`/`userSecret`, `password`/`passwordSecret`, `tls` (default **true**), `startTls`, `timeoutMs`. **Prefer `passwordSecret`/`userSecret`**: they name a project secret resolved host-side, so an error or a log that echoes your options object cannot leak it and an operator can rotate it without a code push. A literal `password` is accepted, because `ctx.env` already hands your script the value anyway. Naming a secret that does not exist is **422** `mail_secret_missing`, which names the secret and never a value; passing both a literal and a secret name for the same credential is `ambiguous_body`. An unknown option key is **refused, not ignored**.
   - `ctx.mail.read({mailbox, criteria, limit, ...})` -> `{messages: [...], matched: n}`. `mailbox` defaults to `INBOX`; `limit` defaults to 20 and is **capped at 200** (over it is refused, not clamped). `matched` is the size of the whole search result and `messages` the newest `limit` of it, so you can tell a full page from the end of the mailbox. Each message carries `uid`, `seq`, `flags`, `internal_date`, `size`, `header`, `text`, `body_sections` and a `headerEncoding`/`textEncoding` of `text` or `base64` - **mail is routinely not UTF-8**, so the encoding is stated rather than assumed. Reading uses `EXAMINE` and `BODY.PEEK`, so **it never marks mail as seen**.

+ 13 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.21.1",
+    "version": "0.22.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {
@@ -273,6 +273,12 @@
             "type": "boolean",
             "default": false,
             "description": "Accept a same-origin request that carries NO Origin header, when Sec-Fetch-Site is same-origin and Host is one this key already lists. Off by default: Sec-Fetch-Site is trustworthy in a browser but trivially set by a non-browser client, so this is opted into per key rather than applied to all."
+          },
+          "rate_limit_per_caller_per_min": {
+            "type": "integer",
+            "minimum": 0,
+            "default": 0,
+            "description": "A ceiling on ONE caller's requests per minute, keyed on the resolved client address. 0 means unlimited. Separate from rate_limit_per_min, which bounds the function's total damage and not one caller's share; both are charged, the per-caller bucket first. Only an HTTP request is charged against it. Refusal is 429 rate_limited, the same slug as the per-function refusal."
           }
         }
       },
@@ -637,6 +643,12 @@
             "type": "boolean",
             "default": false,
             "description": "Accept a same-origin request that carries NO Origin header, when Sec-Fetch-Site is same-origin and Host is one this key already lists. Off by default: Sec-Fetch-Site is trustworthy in a browser but trivially set by a non-browser client, so this is opted into per key rather than applied to all."
+          },
+          "rate_limit_per_caller_per_min": {
+            "type": "integer",
+            "minimum": 0,
+            "default": 0,
+            "description": "A ceiling on ONE caller's requests per minute, keyed on the resolved client address. 0 means unlimited. Separate from rate_limit_per_min, which bounds the function's total damage and not one caller's share; both are charged, the per-caller bucket first. Only an HTTP request is charged against it. Refusal is 429 rate_limited, the same slug as the per-function refusal."
           }
         },
         "required": [

+ 33 - 0
runner/src/host_context.cpp

@@ -3010,6 +3010,39 @@ bool HostContext::install(const JsBindingTarget& target, std::string& error) {
     JS_SetPropertyStr(ctx, *ctxObject, "params", toJs(ctx, triggerObject(trigger, "params")));
     JS_SetPropertyStr(ctx, *ctxObject, "query", toJs(ctx, triggerObject(trigger, "query")));
     JS_SetPropertyStr(ctx, *ctxObject, "headers", toJs(ctx, triggerObject(trigger, "headers")));
+    // THE RESOLVED CALLER ADDRESS, and `null` rather than "" when there is no
+    // caller - a cron, job, db or error run has no request behind it.
+    //
+    // The property is set ALWAYS, including as null, for the reason `ip_allow`
+    // and `scope_filtered` are emitted unconditionally: a script must be able
+    // to tell "this run has no caller" from "this server is too old to tell
+    // me", and an absent key conflates the two. `'clientIp' in ctx` is
+    // therefore the capability check, and the value is the answer.
+    //
+    // Empty would be the worse choice of the two: a falsy STRING still reads
+    // as an address to `typeof`, and a throttle keyed on "" is one shared
+    // bucket wearing a per-caller bucket's name - which is precisely the
+    // failure exposing this is meant to prevent.
+    // What we removed, by name. See applyTriggerHeaders: the values never
+    // travel, and this exists so an author can tell "we withheld it" from
+    // "your client never sent it", which were previously the same observation.
+    //
+    // `contains` before reading, NOT `operator[]`: on a CONST json a missing
+    // key is undefined behaviour rather than a null, and every non-HTTP
+    // trigger - cron, job, db, error - has no such key. The first version of
+    // this line aborted all 160 HostContext tests, which is the cheapest
+    // possible way to find it.
+    JS_SetPropertyStr(
+        ctx, *ctxObject, "headersWithheld",
+        toJs(ctx, (trigger.is_object() && trigger.contains("headersWithheld") &&
+                   trigger.at("headersWithheld").is_array())
+                      ? trigger.at("headersWithheld")
+                      : nlohmann::json::array()));
+    {
+        const std::string resolved = triggerString(trigger, "clientIp");
+        JS_SetPropertyStr(ctx, *ctxObject, "clientIp",
+                          resolved.empty() ? JS_NULL : JS_NewString(ctx, resolved.c_str()));
+    }
     // The body is whatever arrived, including a JSON array or a bare string.
     JS_SetPropertyStr(ctx, *ctxObject, "body",
                       toJs(ctx, trigger.is_object() ? trigger.value("body", nlohmann::json())

+ 4 - 1
src/apikey.cpp

@@ -101,6 +101,7 @@ KeyScope KeyScope::fromJson(const nlohmann::json& j) {
     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.rateLimitPerCallerPerMin = j.value("rate_limit_per_caller_per_min", 0u);
     s.expiresAt       = j.value("expires_at", 0ull);
     return s;
 }
@@ -121,7 +122,9 @@ nlohmann::json KeyScope::toJson() const {
     // tell "this key does not opt in" from "this server has no such field".
     return {{"rules", rules_j}, {"origins", origins}, {"ip_allow", ipAllow},
             {"allow_same_origin_host", allowSameOriginHost},
-            {"rate_limit_per_min", rateLimitPerMin}, {"expires_at", expiresAt}};
+            {"rate_limit_per_min", rateLimitPerMin},
+            {"rate_limit_per_caller_per_min", rateLimitPerCallerPerMin},
+            {"expires_at", expiresAt}};
 }
 
 // ---------------------------------------------------------------------------

+ 15 - 0
src/apikey.hpp

@@ -45,6 +45,21 @@ struct KeyScope {
     /// targets, and giving it CIDR parsing broke four of them.
     std::vector<std::string> ipAllow;
     uint32_t rateLimitPerMin = 0;      // 0 = unlimited
+    /// A ceiling on one CALLER's requests per minute, charged per resolved
+    /// source address. 0 = unlimited.
+    ///
+    /// SEPARATE from rateLimitPerMin because the two answer different
+    /// questions and a single number cannot express both. The per-FUNCTION
+    /// ceiling bounds the DAMAGE - mail sent, paid API spend - and says
+    /// nothing about who caused it; the per-CALLER ceiling bounds one
+    /// caller's share, which is what stops a single abusive client
+    /// exhausting a public function's minute and shutting out everyone
+    /// else. That denial was named as a known limitation of the per-function
+    /// cap and this is the missing half.
+    ///
+    /// Only meaningful where a caller address exists, i.e. an HTTP request.
+    /// A cron, job, db or error run is not charged against it.
+    uint32_t rateLimitPerCallerPerMin = 0;
     uint64_t expiresAt       = 0;      // epoch seconds; 0 = never
     const KeyScopeRule* findRule(const std::string& collection, KeyOp op) const;
 

+ 7 - 0
src/functions/fn_gate.cpp

@@ -38,4 +38,11 @@ std::string fnHttpThrottleBucket(const std::string& project, const std::string&
     return "fnhttp:" + project + "/" + functionId;
 }
 
+std::string fnCallerThrottleBucket(const std::string& project, const std::string& functionId,
+                                   const std::string& clientIp) {
+    // A distinct prefix, so a caller bucket can never collide with the
+    // function's own bucket, a key id or a function principal id.
+    return "fncaller:" + project + "/" + functionId + "/" + clientIp;
+}
+
 } // namespace svapi::functions

+ 17 - 0
src/functions/fn_gate.hpp

@@ -71,4 +71,21 @@ FnGateDecision decideFnAuth(FnAuth mode, const FnAuthFacts& facts);
 /// key id or with a function's own principal id.
 std::string fnHttpThrottleBucket(const std::string& project, const std::string& functionId);
 
+/// The bucket ONE CALLER's requests to a function are charged to.
+///
+/// Charged BEFORE the per-function bucket, which is the ordering that matters:
+/// charging the shared bucket first lets an abusive caller spend the
+/// function's whole minute before being refused by its own ceiling - a denial
+/// of service achieved by being refused, the same shape the
+/// authenticate-before-throttle rule already exists to prevent, one level
+/// down. Charged this way round, an abusive caller is refused on its own
+/// bucket having spent nothing of anyone else's.
+///
+/// The address is attacker-controlled in volume, which is why this could not
+/// exist until RateLimiter bounded its key space - it sweeps per minute and
+/// caps hard, and FAILS OPEN at the cap so that spraying addresses cannot
+/// deny service to everybody else.
+std::string fnCallerThrottleBucket(const std::string& project, const std::string& functionId,
+                                   const std::string& clientIp);
+
 } // namespace svapi::functions

+ 85 - 0
src/functions/request_headers.hpp

@@ -0,0 +1,85 @@
+#pragma once
+
+#include <nlohmann/json.hpp>
+
+#include <algorithm>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+/// Which request headers reach a function, and which are withheld by name.
+///
+/// PURE and header-only on purpose. The split used to live in an anonymous
+/// namespace in `handlers/function_dispatch.cpp`, so the denylist - a security
+/// boundary - could not be tested at all, and the only way to observe it was
+/// to run a function and look at `ctx.headers`. A deployment without a runner
+/// cannot do that, which is the default, so in practice it was never checked.
+///
+/// Header-only rather than a .cpp for the reason recorded beside `ip_allow`:
+/// several narrow test targets compile a subset of this tree, and a new object
+/// file is a link error waiting for whichever target does not list it.
+namespace svapi::functions {
+
+/// Request headers never forwarded into user code.
+///
+/// COOKIE IS THE DANGEROUS ONE and the reason this list exists. The admin web
+/// UI is served from this same origin, so a logged-in operator's browser
+/// attaches its session cookie to `/fn/*` as well - forwarding it would hand
+/// that operator's session to every function author in the project, which is a
+/// privilege escalation rather than an inconvenience. `Authorization` is the
+/// same argument applied to the credential that authenticated the call: a
+/// function has no use for it and a tenant's script must not be able to
+/// harvest the key that called it.
+///
+/// WIDENING THIS LIST IS SAFE; NARROWING IT IS A SECURITY CHANGE. Anyone
+/// tempted to let `cookie` through to carry a session should send the session
+/// in a header of their own - any `X-...` name already arrives untouched,
+/// because there is NO allow-list here and never was.
+inline bool secretRequestHeader(std::string_view lower) {
+    return lower == "cookie" || lower == "set-cookie" || lower == "authorization"
+        || lower == "proxy-authorization" || lower == "x-captcha-token";
+}
+
+struct TriggerHeaders {
+    /// Lower-cased name -> value, so a script need not guess the casing a
+    /// client happened to send.
+    nlohmann::json forwarded = nlohmann::json::object();
+    /// The NAMES of headers that were present and withheld. Sorted and
+    /// deduplicated, so the value is a function of the request rather than of
+    /// header order, which is what makes it safe to assert on.
+    ///
+    /// Names only - a value never travels. This exists so that "we removed it"
+    /// and "your client never sent it" stop being the same observation, which
+    /// is the absence-is-not-information trap, and it discloses only that a
+    /// header was present.
+    std::vector<std::string> withheld;
+};
+
+inline std::string lowerCaseAscii(std::string_view s) {
+    std::string out(s);
+    std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) {
+        return static_cast<char>(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c);
+    });
+    return out;
+}
+
+/// `in` is (name, value) in arrival order; the caller flattens whatever
+/// container its HTTP library uses.
+inline TriggerHeaders splitRequestHeaders(
+    const std::vector<std::pair<std::string, std::string>>& in) {
+    TriggerHeaders out;
+    for (const auto& [name, value] : in) {
+        const std::string lower = lowerCaseAscii(name);
+        if (secretRequestHeader(lower)) {
+            if (std::find(out.withheld.begin(), out.withheld.end(), lower) == out.withheld.end())
+                out.withheld.push_back(lower);
+            continue;
+        }
+        out.forwarded[lower] = value;
+    }
+    std::sort(out.withheld.begin(), out.withheld.end());
+    return out;
+}
+
+} // namespace svapi::functions

+ 71 - 20
src/handlers/function_dispatch.cpp

@@ -14,6 +14,7 @@
 #include "functions/descriptor.hpp"
 #include "function_error_dispatch.hpp"
 #include "functions/fn_gate.hpp"
+#include "functions/request_headers.hpp"
 #include "rate_limiter.hpp"
 #include "json_http.hpp"
 #include "server.hpp"
@@ -21,6 +22,7 @@
 #include <chrono>
 #include <ctime>
 #include <mutex>
+#include <vector>
 #include <spdlog/spdlog.h>
 
 namespace svapi {
@@ -43,11 +45,6 @@ bool reservedResponseHeader(const std::string& lower) {
 /// a logged-in admin's browser attaches the session cookie to /fn/* as well,
 /// and forwarding it would hand that admin's session to every function author
 /// in the project. Authorization goes for the same reason.
-bool secretRequestHeader(const std::string& lower) {
-    return lower == "cookie" || lower == "set-cookie" || lower == "authorization"
-        || lower == "proxy-authorization" || lower == "x-captcha-token";
-}
-
 std::string lowerCase(std::string s) {
     std::transform(s.begin(), s.end(), s.begin(),
                    [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
@@ -135,16 +132,33 @@ bool hasDotDotSegment(const std::string& path) {
     return false;
 }
 
-nlohmann::json headerJson(const httplib::Request& req) {
-    nlohmann::json out = nlohmann::json::object();
-    for (const auto& [name, value] : req.headers) {
-        const std::string lower = lowerCase(name);
-        if (secretRequestHeader(lower)) continue;
-        // Lower-cased keys so a script can look one up without guessing the
-        // casing a client happened to send.
-        out[lower] = value;
-    }
-    return out;
+/// EVERY request header reaches a function except the five `secretRequestHeader`
+/// denies - there is no allow-list, and there never was. A script that cannot
+/// find a header it expected is almost always looking at a header the CLIENT
+/// did not send, not one we removed.
+///
+/// What was missing is the ability to tell those two apart. A withheld header
+/// was simply ABSENT, so "my cookie is not arriving" and "my proxy is not
+/// forwarding it" produced identical evidence - the absence-is-not-information
+/// trap this codebase keeps meeting. `headersWithheld` names what we took out,
+/// so the question is answerable from inside the function.
+///
+/// NAMES ONLY, NEVER VALUES, and the list is the fixed five rather than
+/// anything caller-controlled - so this discloses that a header was PRESENT
+/// and nothing about what it held. That is the whole point of the five: the
+/// web UI is served from this same origin, so a logged-in admin's browser
+/// attaches its session cookie to /fn/* too, and forwarding it would hand that
+/// admin's session to every function author in the project.
+void applyTriggerHeaders(nlohmann::json& t, const httplib::Request& req) {
+    std::vector<std::pair<std::string, std::string>> flat;
+    flat.reserve(req.headers.size());
+    for (const auto& [name, value] : req.headers) flat.emplace_back(name, value);
+    functions::TriggerHeaders split = functions::splitRequestHeaders(flat);
+    t["headers"] = std::move(split.forwarded);
+    // Emitted ALWAYS, empty array included, for the reason `ip_allow` is: an
+    // absent field cannot distinguish "nothing was withheld" from "this
+    // server does not tell you".
+    t["headersWithheld"] = std::move(split.withheld);
 }
 
 /// Repeated query keys collapse to the last value, because the trigger shape is
@@ -340,11 +354,20 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
     // 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()) {
+    //
+    // RESOLVED ONCE, HERE, for all four consumers: the allow-list gate below,
+    // the per-caller throttle after it, `ctx.clientIp`, and the access log.
+    // It used to be computed inside the allow-list branch, so a function
+    // without a list never had it - and the throttle and the ctx field both
+    // need it whether or not a list exists. One resolution also means the four
+    // cannot disagree about who the caller is, which is the property that
+    // makes the access log usable as evidence about the gate's decision.
+    const std::string clientIp = [&] {
         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);
+        return clientIpFor(req, *snap);
+    }();
+
+    if (!policies[idx]->ipAllow.empty()) {
         if (!functions::addressAllowedBy(policies[idx]->ipAllow, clientIp)) {
             sendJson(res, 403,
                      errorBody("ip_not_allowed",
@@ -404,6 +427,27 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
     // and shut out legitimate ones. Per-caller throttling needs an identity,
     // which is exactly what `auth: 'key'` provides and an anonymous request
     // does not have.
+    // THE PER-CALLER CEILING, charged first - see fnCallerThrottleBucket for
+    // why the order is load-bearing rather than incidental. It is the missing
+    // half of the sentence below: the per-function cap bounds the damage and
+    // explicitly does NOT bound the denial, and this does.
+    //
+    // Only where a caller exists. An empty address means nothing trustworthy
+    // resolved, and bucketing those together would charge every such request
+    // to one shared counter - a throttle keyed on "" rather than on a caller.
+    if (policies[idx]->rateLimitPerCallerPerMin > 0 && !clientIp.empty() &&
+        !rateLimiter().allow(
+            functions::fnCallerThrottleBucket(project, functionId, clientIp),
+            policies[idx]->rateLimitPerCallerPerMin)) {
+        res.set_header("Retry-After", std::to_string(kRetryAfterRateLimitedSec));
+        // Deliberately the SAME slug as the per-function refusal. A caller
+        // learning which ceiling it hit learns the other ceiling's value by
+        // probing, and the remedy is identical either way: slow down.
+        sendJson(res, 429,
+                 errorBody("rate_limited", "this function's per-minute limit is exhausted"));
+        return;
+    }
+
     if (policies[idx]->rateLimitPerMin > 0 &&
         !rateLimiter().allow(functions::fnHttpThrottleBucket(project, functionId),
                              policies[idx]->rateLimitPerMin)) {
@@ -439,7 +483,14 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
                            {"path", path},
                            {"params", routeParamsJson(match.params)},
                            {"query", queryJson(req)},
-                           {"headers", headerJson(req)}};
+                           // The RESOLVED address, never a header the caller
+                           // wrote. A throttle keyed on a caller-controlled
+                           // value is not a throttle, which is the whole
+                           // reason this is worth exposing rather than letting
+                           // a script read X-Forwarded-For out of ctx.headers
+                           // and believe it.
+                           {"clientIp", clientIp}};
+    applyTriggerHeaders(trigger, req);
     applyTriggerBody(trigger, req);
 
     const RunnerRunResult r = d.runners->run(project, functionId, trigger);

+ 5 - 0
tests/CMakeLists.txt

@@ -318,6 +318,11 @@ gtest_discover_tests(test_utf8_text)
 add_executable(test_trigger_body test_trigger_body.cpp)
 target_include_directories(test_trigger_body PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_trigger_body PRIVATE vectorapi_core GTest::gtest_main)
+
+add_executable(test_request_headers test_request_headers.cpp)
+target_include_directories(test_request_headers PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_request_headers PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_request_headers)
 gtest_discover_tests(test_trigger_body)
 
 add_executable(test_header_fields test_header_fields.cpp)

+ 104 - 0
tests/test_api_integration.cpp

@@ -4905,6 +4905,110 @@ TEST_F(ApiFixture, AFunctionWithNoRateLimitIsNotThrottled) {
     }
 }
 
+namespace {
+svapi::KeyScope policyWithCallerRate(uint32_t perCaller, uint32_t perFunction = 0) {
+    svapi::KeyScope s;
+    s.rateLimitPerCallerPerMin = perCaller;
+    s.rateLimitPerMin = perFunction;
+    return s;
+}
+} // namespace
+
+// ─── The per-caller ceiling (the missing half of the per-function one) ────
+//
+// The per-function cap bounds the DAMAGE and says so in its own comment:
+// "one abusive caller can still exhaust a public function's minute and shut
+// out legitimate ones". This is that denial, closed. A consumer needed it to
+// move an e-mail-sending route onto /fn, where a per-e-mail bucket alone lets
+// someone walk addresses at a whole domain.
+
+TEST_F(ApiFixture, APerCallerLimitRefusesASecondCallFromTheSAMEaddress) {
+    const FrozenRateClock frozen;
+    functions_->put(project_, fnRow("callerlimit", "public"), policyWithCallerRate(1));
+    auto anon = noAuth();
+    const std::string path = "/fn/" + project_ + "/callerlimit";
+    httplib::Headers a{{"X-Real-IP", "203.0.113.7"}};
+
+    auto first = anon.Get(path.c_str(), a);
+    ASSERT_TRUE(first);
+    EXPECT_EQ(first->status, 503) << "the first call is under the limit: " << first->body;
+
+    auto second = anon.Get(path.c_str(), a);
+    ASSERT_TRUE(second);
+    EXPECT_EQ(second->status, 429) << second->body;
+    EXPECT_EQ(nlohmann::json::parse(second->body)["error"]["code"], "rate_limited")
+        << second->body;
+    EXPECT_EQ(second->get_header_value("Retry-After"), "60");
+}
+
+// THE PAIRING, AND IT IS THE ENTIRE POINT OF THE FEATURE: vary the caller and
+// demand the answer varies with it. Without this, the test above passes just
+// as well against the per-FUNCTION throttle that already existed - which is
+// precisely the behaviour this is meant to improve on, so a test that cannot
+// tell them apart would be testing nothing new.
+TEST_F(ApiFixture, ADIFFERENTcallerIsUNAFFECTEDbyAnotherCallersExhaustedBucket) {
+    const FrozenRateClock frozen;
+    functions_->put(project_, fnRow("callerlimit2", "public"), policyWithCallerRate(1));
+    auto anon = noAuth();
+    const std::string path = "/fn/" + project_ + "/callerlimit2";
+
+    httplib::Headers a{{"X-Real-IP", "203.0.113.7"}};
+    ASSERT_TRUE(anon.Get(path.c_str(), a));                 // spends A's allowance
+    auto aAgain = anon.Get(path.c_str(), a);
+    ASSERT_TRUE(aAgain);
+    ASSERT_EQ(aAgain->status, 429) << "precondition: A is exhausted";
+
+    httplib::Headers b{{"X-Real-IP", "198.51.100.4"}};
+    auto bFirst = anon.Get(path.c_str(), b);
+    ASSERT_TRUE(bFirst);
+    EXPECT_EQ(bFirst->status, 503)
+        << "B has its own bucket; if this is 429 the limit is per FUNCTION, not per "
+           "caller, and the denial it exists to prevent is still open: " << bFirst->body;
+}
+
+TEST_F(ApiFixture, APerCallerLimitOfZeroIsUnlimited) {
+    // 0 means unlimited, as everywhere else here, and must never read as a
+    // limit of zero - which would make every public function unreachable the
+    // moment the field appeared.
+    const FrozenRateClock frozen;
+    functions_->put(project_, fnRow("callerlimit3", "public"), policyWithCallerRate(0));
+    auto anon = noAuth();
+    const std::string path = "/fn/" + project_ + "/callerlimit3";
+    httplib::Headers a{{"X-Real-IP", "203.0.113.7"}};
+    for (int i = 0; i < 4; ++i) {
+        auto res = anon.Get(path.c_str(), a);
+        ASSERT_TRUE(res);
+        EXPECT_EQ(res->status, 503) << "call " << i << " must not be throttled: " << res->body;
+    }
+}
+
+// The per-caller bucket is charged BEFORE the shared one, so an abusive
+// caller cannot spend the function's whole minute on its way to being
+// refused - a denial achieved by being refused. A caller limit of 1 against a
+// function limit of 2 must leave the SECOND caller able to get through.
+TEST_F(ApiFixture, AnAbusiveCallerDoesNotSpendTheFunctionsSharedBudgetOnItsWayToA429) {
+    const FrozenRateClock frozen;
+    functions_->put(project_, fnRow("callerorder", "public"),
+                    policyWithCallerRate(1, /*perFunction=*/2));
+    auto anon = noAuth();
+    const std::string path = "/fn/" + project_ + "/callerorder";
+
+    httplib::Headers a{{"X-Real-IP", "203.0.113.7"}};
+    ASSERT_TRUE(anon.Get(path.c_str(), a));            // A: 1 of its 1, 1 of the shared 2
+    for (int i = 0; i < 3; ++i) {
+        auto refused = anon.Get(path.c_str(), a);      // A refused, and must cost nothing
+        ASSERT_TRUE(refused);
+        ASSERT_EQ(refused->status, 429) << "precondition: A stays refused";
+    }
+
+    httplib::Headers b{{"X-Real-IP", "198.51.100.4"}};
+    auto bFirst = anon.Get(path.c_str(), b);
+    ASSERT_TRUE(bFirst);
+    EXPECT_EQ(bFirst->status, 503)
+        << "A's three refusals must not have drained the function's shared bucket; "
+           "if this is 429 the per-caller check runs AFTER the shared one: " << bFirst->body;
+}
+
 TEST_F(ApiFixture, TheGateIsCheckedBeforeTheRunnerSoItDoesNotNeedOne) {
     // Explicit about the ordering, which is the same rule the invoke envelope
     // follows: authorize, then the request, then the resource. Behind the

+ 105 - 0
tests/test_request_headers.cpp

@@ -0,0 +1,105 @@
+#include "functions/request_headers.hpp"
+
+#include <gtest/gtest.h>
+
+using svapi::functions::secretRequestHeader;
+using svapi::functions::splitRequestHeaders;
+
+namespace {
+/// Read a forwarded header SAFELY.
+///
+/// `operator[]` on a const nlohmann::json with a missing key aborts the whole
+/// binary on an internal assertion, so a test written that way does not fail -
+/// it CRASHES, taking every later test in the file with it and reporting
+/// nlohmann internals instead of the claim. Found by falsifying the denylist:
+/// the substring version made these keys absent and the run died at test 5 of
+/// 7. The same mistake, in the same session, as the one it caught in
+/// host_context.cpp.
+std::string forwarded(const svapi::functions::TriggerHeaders& h, const char* name) {
+    if (!h.forwarded.contains(name)) return "<<ABSENT>>";
+    return h.forwarded.at(name).get<std::string>();
+}
+
+std::vector<std::pair<std::string, std::string>> hdrs(
+    std::initializer_list<std::pair<std::string, std::string>> l) {
+    return {l.begin(), l.end()};
+}
+} // namespace
+
+// ─── There is NO allow-list, and that is the thing most worth pinning ─────
+//
+// A consumer reported a "missing header problem" and the diagnosis was that
+// nothing is missing: an arbitrary header already arrives. Their probe showed
+// five header names and they read that as a filter, when it was simply what
+// their client had sent. This test is what makes that claim checkable rather
+// than something someone has to take on trust.
+
+TEST(RequestHeaders, AnArbitraryHeaderIsForwardedUNTOUCHED) {
+    const auto out = splitRequestHeaders(hdrs({{"X-Review-Session", "tok-123"},
+                                               {"X-Anything-At-All", "v"},
+                                               {"Accept", "application/json"}}));
+    EXPECT_EQ(forwarded(out, "x-review-session"), "tok-123");
+    EXPECT_EQ(forwarded(out, "x-anything-at-all"), "v");
+    EXPECT_EQ(forwarded(out, "accept"), "application/json");
+    EXPECT_TRUE(out.withheld.empty()) << "nothing here is secret";
+}
+
+TEST(RequestHeaders, NamesAreLowerCasedSoAScriptNeedNotGuessTheCasing) {
+    const auto out = splitRequestHeaders(hdrs({{"X-MiXeD-CaSe", "v"}}));
+    EXPECT_EQ(forwarded(out, "x-mixed-case"), "v");
+    EXPECT_FALSE(out.forwarded.contains("X-MiXeD-CaSe"));
+}
+
+// ─── The five withholdings: present, named, and their values gone ─────────
+
+TEST(RequestHeaders, CookieIsWithheldAndItsVALUEneverTravels) {
+    const auto out = splitRequestHeaders(hdrs({{"Cookie", "svapi_session=SECRET-SESSION"},
+                                               {"Accept", "*/*"}}));
+    EXPECT_FALSE(out.forwarded.contains("cookie"));
+    EXPECT_EQ(out.withheld, std::vector<std::string>{"cookie"});
+    // The whole reason the denylist exists: the admin UI shares this origin,
+    // so a logged-in operator's session cookie rides along to /fn.
+    EXPECT_EQ(out.forwarded.dump().find("SECRET-SESSION"), std::string::npos)
+        << "a withheld value must not appear anywhere in the trigger";
+}
+
+TEST(RequestHeaders, EveryHeaderOnTheDenylistIsActuallyDenied) {
+    for (const char* n : {"cookie", "set-cookie", "authorization", "proxy-authorization",
+                          "x-captcha-token"}) {
+        EXPECT_TRUE(secretRequestHeader(n)) << n;
+        const auto out = splitRequestHeaders(hdrs({{n, "value"}}));
+        EXPECT_FALSE(out.forwarded.contains(n)) << n << " must not be forwarded";
+        EXPECT_EQ(out.withheld.size(), 1u) << n << " must be named as withheld";
+    }
+}
+
+// THE PAIRING. Without it every assertion above would pass against a split
+// that withheld EVERYTHING, which is the failure mode a denylist test cannot
+// otherwise see.
+TEST(RequestHeaders, AHeaderWhoseNameMERELYRESEMBLESAsecretOneIsForwarded) {
+    const auto out = splitRequestHeaders(hdrs({{"X-Cookie-Preference", "none"},
+                                               {"Authorization-Scheme-Hint", "bearer"},
+                                               {"My-Cookie", "c"}}));
+    EXPECT_EQ(forwarded(out, "x-cookie-preference"), "none");
+    EXPECT_EQ(forwarded(out, "authorization-scheme-hint"), "bearer");
+    EXPECT_EQ(forwarded(out, "my-cookie"), "c");
+    EXPECT_TRUE(out.withheld.empty())
+        << "the match is exact; a substring match would silently eat tenant headers";
+}
+
+TEST(RequestHeaders, TheWithheldListIsSortedAndDeduplicated) {
+    // httplib can hand us a repeated header, and the same name twice would
+    // read as two separate withholdings.
+    const auto out = splitRequestHeaders(hdrs({{"Cookie", "a"},
+                                               {"Authorization", "Bearer x"},
+                                               {"Cookie", "b"}}));
+    EXPECT_EQ(out.withheld, (std::vector<std::string>{"authorization", "cookie"}));
+}
+
+TEST(RequestHeaders, NothingWithheldIsAnEMPTYListRatherThanAnAbsentOne) {
+    const auto out = splitRequestHeaders(hdrs({{"Accept", "*/*"}}));
+    EXPECT_TRUE(out.withheld.empty());
+    // The caller emits this unconditionally; see the note there. An absent
+    // field cannot say "nothing was withheld" rather than "this server does
+    // not tell you".
+}