Răsfoiți Sursa

feat: name which throttle refused, in the operator log only SV-125

Asked for by novitax after verifying 0.22.0: from outside, "one abusive
caller" and "this function is globally saturated" are the same 429, and they
have OPPOSITE remedies - find the caller, or raise the ceiling. They agreed the
response must not distinguish them (it is an oracle, and their caller is a
voice agent that could not act on it anyway) and asked only for the operator
side. That split is the whole point: each refusal now logs which ceiling fired
with the function and the caller, and the response is unchanged. `fn throttle:`
greps both.

The address in that line discloses nothing new - it is already in our access
log - and the two lines are worded as a greppable PAIR so an operator reading
one knows the other exists.

ALSO: `ctx.headersWithheld` IS ALWAYS PRESENT, and this is now documented as
MEASURED rather than asserted, because they said they would write my answer
into their own documentation - which makes an unmeasured answer from me the
most expensive kind this file warns about. Measured on prod across four cases:
an HTTP call with nothing withheld, one sending a cookie, one sending a cookie
and an Authorization, and a CRON run with no request behind it at all. Present
and an array in every one, so `'headersWithheld' in ctx` is the capability
check and `.length` is the answer.

The first run of that probe was worthless and said so: the function was
key-gated and I called it without a key, so a 401 envelope parsed into `None`
for every field and read exactly like "the feature is absent". The rewrite
carries a sentinel the function itself sets and refuses to interpret anything
that does not have it - the empty-variable trap, met for the third time this
session and the first time caught before it reached a conclusion.

Their own report also found this defect class in THEIR tooling, which is worth
recording because it generalises past both of us: their deploy script PUTs
function policies wholesale from a table, and that table did not model the new
field - so a per-caller ceiling set in the web UI would have survived until the
next function deploy and then vanished, with the push reporting success. Same
shape as the policy editor fixed in the previous commit. Any project pushing
policies from a script has it, and it is invisible until the day it costs
someone their allow-list.

1538/1538 serial.
fszontagh 6 zile în urmă
părinte
comite
9955768e80
5 a modificat fișierele cu 55 adăugiri și 7 ștergeri
  1. 1 1
      VERSION
  2. 2 2
      api/llms.txt
  3. 1 1
      api/openapi.json
  4. 20 3
      src/handlers/function_dispatch.cpp
  5. 31 0
      tests/test_request_headers.cpp

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.22.0
+0.22.1

+ 2 - 2
api/llms.txt

@@ -531,8 +531,8 @@ export default async function (ctx) {
 - **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.
+- **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. **`ctx.headersWithheld` is ALWAYS present and always an array**, empty when nothing was withheld - so `'headersWithheld' in ctx` is the capability check and `.length` is the answer, never the other way round. Measured on prod across four cases: an HTTP call with nothing withheld, one sending a cookie, one sending a cookie and an Authorization, and a **cron run with no request behind it at all** - present and an array in every one, so a non-HTTP trigger gives you `[]` rather than a missing field. On a server older than 0.22.0 the key is absent entirely, which is what makes `in` the right test.
+- **`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. **The OPERATOR can tell them apart, though**: each refusal logs which ceiling fired, naming the function and the caller, because an operator has to act and the two causes have opposite remedies - one abusive caller means find the caller, a saturated function means raise the ceiling. Grep the journal for `fn throttle:`. That is deliberately not in the response, so the distinction is available to whoever runs the deployment and not to whoever is probing it. 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**.

+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.22.0",
+    "version": "0.22.1",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {

+ 20 - 3
src/handlers/function_dispatch.cpp

@@ -440,9 +440,20 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
             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.
+        // WHICH ceiling fired is recorded for the OPERATOR and withheld from
+        // the caller, because the two audiences need opposite things.
+        //
+        // A caller told which bucket refused it learns the other bucket's
+        // value by probing, and cannot act on the difference anyway. An
+        // operator reading this log has to act on it and the two causes have
+        // OPPOSITE remedies: one abusive caller means find the caller, a
+        // saturated function means raise the ceiling. From the outside those
+        // are the same 429, so without this line an operator cannot tell them
+        // apart - asked for by a consumer who could see the symptom and not
+        // the cause. The address is already in our access log, so naming it
+        // here discloses nothing new.
+        spdlog::info("fn throttle: PER-CALLER ceiling {} reached for {}/{} by {}",
+                     policies[idx]->rateLimitPerCallerPerMin, project, functionId, clientIp);
         sendJson(res, 429,
                  errorBody("rate_limited", "this function's per-minute limit is exhausted"));
         return;
@@ -452,6 +463,12 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
         !rateLimiter().allow(functions::fnHttpThrottleBucket(project, functionId),
                              policies[idx]->rateLimitPerMin)) {
         res.set_header("Retry-After", std::to_string(kRetryAfterRateLimitedSec));
+        // The sibling of the line above, and worded to be greppable as a pair:
+        // this one means the function is globally saturated rather than one
+        // caller misbehaving, which is the distinction that decides the fix.
+        spdlog::info("fn throttle: PER-FUNCTION ceiling {} reached for {}/{} (caller {})",
+                     policies[idx]->rateLimitPerMin, project, functionId,
+                     clientIp.empty() ? "unresolved" : clientIp.c_str());
         sendJson(res, 429,
                  errorBody("rate_limited", "this function's per-minute limit is exhausted"));
         return;

+ 31 - 0
tests/test_request_headers.cpp

@@ -103,3 +103,34 @@ TEST(RequestHeaders, NothingWithheldIsAnEMPTYListRatherThanAnAbsentOne) {
     // field cannot say "nothing was withheld" rather than "this server does
     // not tell you".
 }
+
+// ─── headersWithheld is a CAPABILITY check, so it must always be present ──
+//
+// A consumer asked precisely the right question: is `'headersWithheld' in ctx`
+// the test, or its length? They intend to write the answer into their own
+// documentation, which makes an unmeasured answer from me the most expensive
+// kind - so it was measured on prod across four cases (an HTTP call with
+// nothing withheld, one with a cookie, one with a cookie and an
+// Authorization, and a cron run with no request at all) and it is always
+// present and always an array.
+//
+// This pins the half that is ours: the SPLIT always yields a list, empty
+// rather than absent. The caller emits it unconditionally, and the test below
+// in test_api_integration pins that end.
+
+TEST(RequestHeaders, TheListIsAlwaysAListEvenWhenNothingWasWithheld) {
+    // Not merely "empty": a caller reading `.length` on something absent gets
+    // a TypeError, so the shape matters as much as the contents.
+    for (const auto& in : {hdrs({}), hdrs({{"Accept", "*/*"}}),
+                           hdrs({{"Cookie", "a=b"}})}) {
+        const auto out = splitRequestHeaders(in);
+        // A vector is always a vector in C++; what this asserts is that no
+        // path returns early and leaves the field unset in the JSON the
+        // caller builds from it. See the dispatch test for that end.
+        EXPECT_LE(out.withheld.size(), 1u);
+    }
+    EXPECT_TRUE(splitRequestHeaders(hdrs({{"Accept", "*/*"}})).withheld.empty());
+    EXPECT_EQ(splitRequestHeaders(hdrs({{"Cookie", "a=b"}})).withheld.size(), 1u)
+        << "the control: with something to withhold the list is NOT empty, so "
+           "the assertion above is about emptiness rather than about a broken split";
+}