Selaa lähdekoodia

feat: throttle /fn and let a function require an API key

/fn was unauthenticated AND unthrottled, and the second half surprises
people who read the first. The unauthenticated part is a design decision
and still right - a published HTTP function is published. The unthrottled
part was a gap, and the field that looked like it covered it did not:
rate_limit_per_min was enforced only inside requireCapabilityCore, on the
function's DATA access, so a published function that sends mail or spends a
paid API was reachable by anyone who learned the URL with no ceiling at all.

Two changes, one release:

- `auth: 'key'` in the `on` block requires an Authorization: Bearer key
  granted the function's project, looked up by the same code that guards
  /api/*. 401 with WWW-Authenticate when absent or unknown - identically,
  so a prober learns nothing from the difference - and 403 for a real key
  on the wrong project, since re-sending it cannot help.
- rate_limit_per_min is now charged on calls as well as on data access.

Five decisions worth not rediscovering:

- AUTHENTICATE FIRST, THROTTLE SECOND. The reverse lets an anonymous flood
  spend the whole minute budget and lock out the caller holding a key - a
  denial of service achieved by being refused.
- The two ceilings use SEPARATE buckets against the same number. Sharing one
  would mean a function doing three reads per request spent four tokens per
  call, so adding a read to a script would lower its own request ceiling.
- `auth` defaults to public, and an unrecognised VALUE is refused while an
  unknown KEY stays ignored. A newer script must still load; a typo must
  never publish a function its author believed was gated.
- The gate sits before the runner check. Behind it, a gated function would
  answer 503 on every deployment without a runner, which is the default, and
  an author would conclude the gate did not work.
- A refused call is not written to the run log: nothing ran, and logging
  refusals would let an unauthenticated caller append a database row per
  request, turning a public URL into a write amplifier.

Stated in the docs rather than glossed: the ceiling is per FUNCTION, not per
caller, so it bounds the damage and not the denial, and an older server
ignores `auth` entirely so a gated function deployed backwards is silently
public.

24 tests. The pure decision is enumerated in test_fn_gate.cpp and both
halves were falsified - defaulting an unknown auth value to public turns the
fail-closed test red, and removing the public short-circuit turns the
pairing red. Eight integration tests drive the actual route, because a
policy field is not done until a test exercises its route; network_egress
shipped in the wrong handler with a green suite and prod acceptance caught
it. Suite 1308/1308 serially.

Two traps the tests themselves hit. The first throttle test set the policy on
the pushed record and the limit silently did not apply, because
mergeForCodePush takes the policy from the stored row and never reads the
push - the invariant working as written, so the test "disproved" a throttle
that worked. And it was flaky on the real clock, since the limiter buckets by
now/60 and two requests either side of a minute boundary land in different
windows; it now freezes the clock.
fszontagh 1 kuukausi sitten
vanhempi
sitoutus
696b4315ba

+ 9 - 1
CLAUDE.md

@@ -87,7 +87,15 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **Descriptor parsing never throws** (`functions/descriptor.hpp`, pure): a script author's typo is data. Unknown keys are ignored so a script written for a later server still loads. 404 and 405 stay distinct, so a 405 can carry its `Allow:` union.
 - **Routes:** functions are managed at `/api/v1/projects/{p}/functions*` (project-manage; **policy is admin-only**) and served to the world at **`/fn/{project}/*`**, which is **unauthenticated** - the project segment is therefore hostile input: charset-restricted (no `:`, the `qualify()` separator), confirmed against `listProjects()` before anything qualifies a collection, and a `..` segment is refused anywhere (httplib percent-decodes before the handler sees the path, and `..` can be captured by a `:name` param). Disabled and invalid functions are absent from the descriptor list, so they 404 rather than 403, and function error text never reaches the caller - it goes to the run log, with the `run_id` in the response.
 - **`/fn` IS UNAUTHENTICATED *AND* UNTHROTTLED, AND THE SECOND HALF SURPRISES PEOPLE WHO READ THE FIRST.** Verified in code 2026-10-13, prompted by a consumer asking how to send a verification e-mail: `function_dispatch.cpp` never touches `rateLimiter()`, and the policy's `rate_limit_per_min` is enforced only inside `requireCapabilityCore` - that is, on the function's DATA access through `ctx.collections`. **`ctx.mail` and `ctx.fetch` are outside the policy entirely** (a function with `rules: []` can still send mail, which is recorded above as a deliberate decision). So a published function that sends mail or makes an outbound call is reachable by anyone who learns the URL, with no per-function ceiling: an e-mail bomb aimed at any address, on the tenant's SMTP quota and sender reputation, or a paid API burned.
-  The unauthenticated part is a design decision and still right - a published HTTP function is published. **The unthrottled part is not a decision, it is a gap**, and the field that looks like it covers it does not. I believed it did when I started answering. See task #77; the lean is to honour `rate_limit_per_min` on `/fn`, because a consumer reading the policy vocabulary will assume it already applies and will not test that assumption. Until then the only protection is the tenant's own: a secret header the function checks itself, or no HTTP trigger at all - a `db`-triggered function behind an `insert` grant has no public endpoint to abuse.
+  The unauthenticated part is a design decision and still right - a published HTTP function is published. **The unthrottled part was not a decision, it was a gap**, and the field that looked like it covered it did not. I believed it did when I started answering.
+  **CLOSED IN 0.15.0, both halves, and the lesson is kept because the shape recurs.** `rate_limit_per_min` is now charged on `/fn` as well as on data access, and a function can require a key with `auth: 'key'` in its `on` block. Five decisions in that fix are load-bearing:
+  - **AUTHENTICATE FIRST, THROTTLE SECOND.** The reverse lets an anonymous flood spend a function's whole minute budget and lock out the one caller holding a key - a denial of service achieved by being refused. Ordering it this way rejects that flood without charging the bucket the legitimate caller shares.
+  - **The two ceilings are counted in SEPARATE buckets against the same number.** One shared bucket would make the limit mean something nobody intends: a function doing three reads per request would spend four tokens per call, so a limit of 60 would admit 15 requests and **adding a read to a script would silently lower its own request ceiling**. That is the same mistake as charging a listing one token per collection examined, which this file already records fixing once.
+  - **`auth` defaults to `public` and an unrecognised VALUE is REFUSED**, while an unknown KEY in the `on` block stays ignored. Both are deliberate and they pull in opposite directions: an unknown key is a script written for a newer server and must still load, whereas `auth: 'kye'` falling back to public would publish a function whose author believed it was gated. A typo must never widen access. Note the honest limitation: **an older server ignores the key entirely, so a gated function deployed backwards is silently public** - the one place forward-compatibility cuts against safety.
+  - **The gate sits BEFORE the runner check**, following the ordering rule here. Behind it, a gated function would answer 503 on every deployment without a runner - which is the default - and an author would conclude their gate did not work. An integration test pins it by demanding 401 with no runner configured, paired with a VALID key on the same route reaching 503 instead, so the test proves the gate is passed rather than that everything is refused.
+  - **A refused call is NOT written to the run log**, which is a security decision rather than an oversight: the run log lives in the database, so logging refusals would let an unauthenticated caller append a row per request and turn a public URL into a write amplifier against the tenant's own storage.
+  **What it still does NOT do, stated because the limit is easy to overread:** the ceiling is per FUNCTION, not per caller, so it bounds the DAMAGE - mail sent, paid API spend - and not the denial. One abusive caller can still exhaust a public function's minute. Per-caller throttling needs an identity, which is exactly what `auth: 'key'` provides and an anonymous request does not have.
+  **And a test-writing trap met while proving it, worth more than the feature:** the first throttle test set `incoming.policy` on the record it pushed and the limit silently did not apply, because `mergeForCodePush` takes the policy from the STORED row and never reads the one in the push - the "a code push can never widen access" invariant, working exactly as written. The test therefore "disproved" a throttle that worked. A first registration inherits the `projectDefault` argument, so that is where a test's policy has to go. The same test was also **flaky on the real clock**, because the limiter buckets by `now / 60` and two requests straddling a minute boundary land in different windows; it now freezes the clock, since a test that fails once an hour teaches people to re-run rather than to read.
 - **A write is validated on a runner before storage**, so the engine that validates is the engine that executes; with no healthy runner the write is refused **503** rather than stored unchecked.
 - **`RunnerPool` retry is three-way, not two.** Never connected → retry (nothing ran). Answered, whatever the answer → never retry (the runner did its job). **Delivered then unanswered** (read timeout, non-200, unparseable body) → **do not retry**, mark unhealthy: the handler may be running right now, and a retry would run a side-effecting function twice. `validate()` retries everything, because compiling has no side effects. Also: `RunnerPool::Options::readTimeoutSec` **must exceed** the runner's `max_wall_time_ms`, or our read times out before the runner can report its own timeout and the caller gets a misleading 503 instead of a 504.
 - **`ctx.collections(...)` is a direct gateway call, never loopback HTTP**, and `ctx.fetch` pins the connection to the single address the guard approved (`set_hostname_addr_map`) rather than re-resolving - re-resolving IS the rebinding window. One resolution, one classification.

+ 11 - 2
api/llms.txt

@@ -280,7 +280,7 @@ export default async function (ctx) {
 }
 ```
 
-`on` fields: `id` (required), `type` (`http`, default), `route` (required for http), `method` (a string or an array of strings; **absent means every method**), `timeoutMs` (clamped to the runner's ceiling), `singleFlight`. The STORED `descriptor` always reports `method` as an **array**, and omits it entirely when the function accepts any method - a client rendering it must not assume the singular form the source uses.
+`on` fields: `id` (required), `type` (`http`, default), `route` (required for http), `method` (a string or an array of strings; **absent means every method**), `auth` (`public` default, or `key` to require an API key - http only, see "Calling a function"), `timeoutMs` (clamped to the runner's ceiling), `singleFlight`. The STORED `descriptor` always reports `method` as an **array**, and omits it entirely when the function accepts any method - a client rendering it must not assume the singular form the source uses.
 
 `ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
 
@@ -362,7 +362,16 @@ export default async function (ctx) {
 
 ### Calling a function
 
-- `ANY /fn/{project}/{path}` - **Unauthenticated.** This is where a published function is served; it takes no API key, because a function's HTTP route is public by design. The project is the first path segment and the rest is matched against that project's `on` routes, so `/fn/acme/kb/hungary` reaches the `acme` function declaring `route: '/kb/:topic'` with `topic = "hungary"`.
+- `ANY /fn/{project}/{path}` - **Unauthenticated BY DEFAULT**, and gateable per function since 0.15.0. This is where a published function is served. The project is the first path segment and the rest is matched against that project's `on` routes, so `/fn/acme/kb/hungary` reaches the `acme` function declaring `route: '/kb/:topic'` with `topic = "hungary"`.
+- **`auth: 'key'` in the `on` block requires an API key on the call**, sent as `Authorization: Bearer <key>`. The key must authenticate and must be granted the function's project; it is checked by the same code that guards `/api/*`, so a function's gate cannot drift from the rest of the server. No key or an unknown one is **401** `unauthorized` with `WWW-Authenticate: Bearer`; a valid key for a different project is **403** `forbidden`, because re-sending the same credential cannot help. **A missing key and a wrong key answer identically on purpose** - distinguishing them tells someone probing tokens which half of the guess was right.
+  - `auth: 'public'` is the default and the historical behaviour, so **nothing already deployed changes**. A key sent to a public function is neither required nor rejected.
+  - **An unrecognised value is REFUSED at push time** (`auth: 'kye'` fails the write), unlike an unknown KEY in the `on` block, which is still ignored so a script written for a newer server keeps loading. A typo must never publish a function its author believed was gated.
+  - **On a server older than 0.15.0 this key is IGNORED and the function is public, silently.** That is the one place the forward-compatibility rule cuts against safety, so check the server version before treating `auth` as the only gate on something sensitive.
+  - 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.
+- **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.
+  - **A refused call is not written to the run log.** Nothing ran, so there is no run to record - and logging refusals would let an unauthenticated caller append a database row per request, turning a public URL into a write amplifier against the tenant's own storage.
 - The function chooses the response: its returned `status`, `headers` and `body` are sent as-is. Returning a plain object with none of those keys sends it as a `200` body, and an object mixing them with other keys **fails the run** rather than being guessed at.
 - A path matching no function is **404**; a path that matches but not for this method is **405** with an `Allow:` header. Disabled and invalid functions are simply absent, so they are **404** too - a public caller learns nothing about what a project contains.
 - A function that threw is **500**, a wall-time timeout is **504** `function_timeout`, exceeding the memory ceiling is **500** `function_out_of_memory`, and no healthy runner is **503** `runner_unavailable` with `Retry-After`. **The function's error text is never returned** - a stack trace on an open endpoint is an information leak. The response carries `error.details.run_id`, and the message is in `GET .../functions/{id}/logs`.

+ 48 - 2
api/openapi.json

@@ -20,7 +20,7 @@
             "Functions"
           ],
           "summary": "Invoke a published function",
-          "description": "Served without authentication. The function's returned status, headers and body are sent as-is; an object carrying none of those keys is sent as a 200 body. Cookie, Authorization, Proxy-Authorization and X-Captcha-Token are not forwarded to the function, because the web UI shares this origin and forwarding Cookie would hand an admin session to every function author in the project. Repeated query parameters collapse to the last value, and HEAD is not routable.",
+          "description": "Served without authentication BY DEFAULT. A function may require an API key by declaring auth: 'key' in its on block, in which case the call must carry Authorization: Bearer <key> and that key must be granted the function's project; the gate uses the same key lookup that guards /api/*. A function's rate_limit_per_min policy also applies to CALLS on this route, counted in a bucket separate from the function's data-access budget, so one number is a ceiling on requests AND, independently, on data operations. The ceiling is per function rather than per caller, so it bounds the damage done rather than preventing denial of service. The function's returned status, headers and body are sent as-is; an object carrying none of those keys is sent as a 200 body. Cookie, Authorization, Proxy-Authorization and X-Captcha-Token are not forwarded to the function, because the web UI shares this origin and forwarding Cookie would hand an admin session to every function author in the project - this also means a gated function never sees the credential that admitted the call. Repeated query parameters collapse to the last value, and HEAD is not routable.",
           "security": [],
           "parameters": [
             {
@@ -51,6 +51,34 @@
                 }
               }
             },
+            "401": {
+              "description": "This function declares auth: 'key' and the call carried no usable API key. A missing key and an unknown key answer identically, so a caller probing tokens learns nothing from the difference.",
+              "headers": {
+                "WWW-Authenticate": {
+                  "description": "Always 'Bearer'.",
+                  "schema": {
+                    "type": "string"
+                  }
+                }
+              },
+              "content": {
+                "application/json": {
+                  "schema": {
+                    "$ref": "#/components/schemas/Error"
+                  }
+                }
+              }
+            },
+            "403": {
+              "description": "The key authenticated but is not granted the project this function belongs to. 403 rather than 401 because re-sending the same credential cannot help.",
+              "content": {
+                "application/json": {
+                  "schema": {
+                    "$ref": "#/components/schemas/Error"
+                  }
+                }
+              }
+            },
             "404": {
               "description": "No enabled, valid function matches this path. Disabled and invalid functions are absent from matching, so a public caller cannot tell them from a path that was never published.",
               "content": {
@@ -79,6 +107,24 @@
                 }
               }
             },
+            "429": {
+              "description": "The function's own rate_limit_per_min is exhausted for this minute. Charged per function, not per caller. A refused call is NOT written to the run log: nothing ran, and recording refusals would let an unauthenticated caller append a database row per request.",
+              "headers": {
+                "Retry-After": {
+                  "description": "Seconds to wait; always 60.",
+                  "schema": {
+                    "type": "string"
+                  }
+                }
+              },
+              "content": {
+                "application/json": {
+                  "schema": {
+                    "$ref": "#/components/schemas/Error"
+                  }
+                }
+              }
+            },
             "500": {
               "description": "The function threw (code function_error), or exceeded its memory ceiling (function_out_of_memory). The function's error text is deliberately NOT included - a stack trace on an open endpoint is an information leak. error.details.run_id locates the full message in the function's run log.",
               "content": {
@@ -3401,7 +3447,7 @@
       }
     },
     "/fn/{project}/{path}": {
-      "description": "Public dispatch for a project's HTTP functions. Unauthenticated by design: a published function's route is public. The project is the first path segment; the remainder is matched against that project's declared routes.",
+      "description": "Public dispatch for a project's HTTP functions. Unauthenticated by default; a function may require an API key with auth: 'key', and its rate_limit_per_min policy bounds calls here. The project is the first path segment; the remainder is matched against that project's declared routes.",
       "get": {
         "$ref": "#/components/pathItems/FunctionDispatch/get"
       },

+ 1 - 0
src/CMakeLists.txt

@@ -53,6 +53,7 @@ add_library(vectorapi_core STATIC
     functions/cron.cpp
     functions/timezone.cpp
     functions/descriptor.cpp
+    functions/fn_gate.cpp
     functions/net_guard.cpp
 )
 target_include_directories(vectorapi_core PUBLIC

+ 21 - 0
src/functions/descriptor.cpp

@@ -110,6 +110,14 @@ bool FunctionDescriptor::acceptsMethod(const std::string& method) const {
     return std::find(methods.begin(), methods.end(), norm) != methods.end();
 }
 
+bool fnAuthFromString(const std::string& s, FnAuth& out) {
+    if (s == "public") { out = FnAuth::Public; return true; }
+    if (s == "key")    { out = FnAuth::Key;    return true; }
+    return false;
+}
+
+std::string fnAuthToString(FnAuth a) { return a == FnAuth::Key ? "key" : "public"; }
+
 nlohmann::json FunctionDescriptor::toJson() const {
     nlohmann::json j = nlohmann::json::object();
     j["id"] = id;
@@ -118,6 +126,10 @@ nlohmann::json FunctionDescriptor::toJson() const {
         j["type"] = "http";
         j["route"] = route;
         if (!methods.empty()) j["method"] = methods;
+        // Written unconditionally, like singleFlight: a gate that vanished
+        // from the stored row on a reload would silently republish the
+        // function, which is the one direction this field must never fail in.
+        j["auth"] = fnAuthToString(auth);
         break;
     case TriggerType::Cron:
         j["type"] = "cron";
@@ -179,6 +191,15 @@ ParseResult parseDescriptor(const nlohmann::json& on) {
         d.route = on.at("route").get<std::string>();
         if (const std::string e = routeError(d.route); !e.empty()) return fail(e);
         if (const std::string e = parseMethods(on, d.methods); !e.empty()) return fail(e);
+        if (on.contains("auth")) {
+            if (!on.at("auth").is_string()) return fail("http 'auth' must be a string");
+            const std::string raw = on.at("auth").get<std::string>();
+            // REFUSED rather than defaulted. An unknown KEY is ignored below so
+            // a newer script still loads here, but an unknown VALUE of this key
+            // would publish a function its author believed was gated.
+            if (!fnAuthFromString(raw, d.auth))
+                return fail("http 'auth' must be one of public, key: '" + raw + "'");
+        }
         break;
     }
     case TriggerType::Cron: {

+ 43 - 0
src/functions/descriptor.hpp

@@ -17,6 +17,37 @@ enum class TriggerType { Http, Cron, Db, Job };
 
 enum class DbEvent { Insert, Update, Delete };
 
+/// Who may call a published HTTP function.
+///
+/// `/fn/*` is unauthenticated by design - a published HTTP function is
+/// published - but until now that was the ONLY option. An author who wanted a
+/// webhook reachable by one caller had to invent the check inside their own
+/// script, usually a shared secret compared in JS, which means every author
+/// re-implements authentication and the ones who forget have no gate at all.
+///
+/// Public stays the DEFAULT, because anything else would take every deployed
+/// function offline the moment this shipped - the same reasoning that makes
+/// `network_egress` default to allow. What was missing is the ABILITY to
+/// require a key, not a new posture for functions that never asked for one.
+enum class FnAuth {
+    /// Anyone who learns the URL. The historical and current default.
+    Public,
+    /// A valid API key granted this project, sent as `Authorization: Bearer`.
+    /// Authenticated and authorized by the SAME code that guards `/api/*`, so
+    /// a function's gate cannot drift from the rest of the server.
+    Key,
+};
+
+/// Parse an `auth` value. False for anything unrecognised.
+///
+/// parseDescriptor REFUSES an unrecognised value rather than defaulting, which
+/// is the opposite of how it treats an unknown KEY. Both are deliberate: an
+/// unknown key is a script written for a newer server and must still load,
+/// whereas `auth: 'kye'` falling back to Public would publish a function whose
+/// author believed it was gated. A typo must never widen access.
+bool fnAuthFromString(const std::string& s, FnAuth& out);
+std::string fnAuthToString(FnAuth a);
+
 /// Captured path parameters, keyed by the `:name` in the pattern. Ordered so
 /// two matches of the same route compare equal regardless of segment order.
 using RouteParams = std::map<std::string, std::string>;
@@ -37,6 +68,18 @@ struct FunctionDescriptor {
     /// EMPTY MEANS ANY METHOD - it is not "no method allowed".
     std::vector<std::string> methods;
 
+    /// Who may call this route. Http only; ignored for every other trigger,
+    /// since a cron or db function has no caller to authenticate.
+    ///
+    /// WARNING worth knowing before relying on it: an OLDER server ignores
+    /// this key entirely (parseDescriptor skips unknown keys so a newer script
+    /// still loads), so a function declaring `auth: 'key'` deployed to a
+    /// server that predates this field is PUBLIC, silently. That is the one
+    /// place the forward-compatibility rule cuts against safety. Check the
+    /// server version before treating this as the only gate on a sensitive
+    /// function.
+    FnAuth auth = FnAuth::Public;
+
     // Cron.
     std::string schedule;
     /// IANA zone the schedule is read in; empty means UTC.

+ 41 - 0
src/functions/fn_gate.cpp

@@ -0,0 +1,41 @@
+#include "functions/fn_gate.hpp"
+
+namespace svapi::functions {
+
+FnGateDecision decideFnAuth(FnAuth mode, const FnAuthFacts& facts) {
+    FnGateDecision d;
+    if (mode == FnAuth::Public) return d;  // every fact is irrelevant; see header
+
+    if (!facts.keyPresent) {
+        d.outcome = FnGateOutcome::Unauthenticated;
+        d.slug = "unauthorized";
+        d.message = "this function requires an API key: send Authorization: Bearer <key>";
+        return d;
+    }
+    if (!facts.keyAuthenticates) {
+        // Same answer as a missing key, on purpose: distinguishing "no key"
+        // from "wrong key" tells an attacker probing tokens which half of the
+        // guess was right, and tells a legitimate caller nothing they cannot
+        // determine from their own key.
+        d.outcome = FnGateOutcome::Unauthenticated;
+        d.slug = "unauthorized";
+        d.message = "this function requires an API key: send Authorization: Bearer <key>";
+        return d;
+    }
+    if (!facts.keyGrantsProject) {
+        // A real key, wrong project. 403 rather than 401 because re-sending
+        // the same credential cannot help, which is exactly the distinction
+        // 401 and 403 exist to carry.
+        d.outcome = FnGateOutcome::Forbidden;
+        d.slug = "forbidden";
+        d.message = "this key is not granted the project this function belongs to";
+        return d;
+    }
+    return d;
+}
+
+std::string fnHttpThrottleBucket(const std::string& project, const std::string& functionId) {
+    return "fnhttp:" + project + "/" + functionId;
+}
+
+} // namespace svapi::functions

+ 74 - 0
src/functions/fn_gate.hpp

@@ -0,0 +1,74 @@
+#pragma once
+#include "functions/descriptor.hpp"
+#include <string>
+
+namespace svapi::functions {
+
+/// What the gate decided, and what to answer.
+enum class FnGateOutcome {
+    Allow,
+    /// 401. No key, or a key that does not authenticate.
+    Unauthenticated,
+    /// 403. A real key that is not granted this project.
+    Forbidden,
+    /// 429. Over the function's own per-minute ceiling.
+    RateLimited,
+};
+
+struct FnGateDecision {
+    FnGateOutcome outcome = FnGateOutcome::Allow;
+    /// Error slug, empty when Allow.
+    std::string slug;
+    /// Caller-facing message, empty when Allow.
+    std::string message;
+
+    bool allowed() const { return outcome == FnGateOutcome::Allow; }
+};
+
+/// What the request carried, reduced to the three facts the decision needs.
+///
+/// Deliberately NOT the httplib request: the whole point of this header is
+/// that the policy question is decidable without a socket, a database or a
+/// registry, so it can be tested exhaustively on the dev host.
+struct FnAuthFacts {
+    /// An Authorization: Bearer header was present and non-empty.
+    bool keyPresent = false;
+    /// That token matched a stored key.
+    bool keyAuthenticates = false;
+    /// That key is granted the project the function lives in.
+    bool keyGrantsProject = false;
+};
+
+/// Decide the AUTHENTICATION half of the gate. Pure.
+///
+/// Note a Public function ignores every fact: a key sent to a public function
+/// is neither required nor rejected, because refusing one would break a caller
+/// that attaches its key to every request to our host out of habit - and that
+/// habit is one we encourage everywhere else on this API.
+///
+/// A gated function answers 401 to an anonymous caller, which does disclose
+/// that the route EXISTS. That is deliberate and is the narrower of two bad
+/// options: a 404 would be indistinguishable from a misspelled route, so an
+/// author debugging their own webhook could not tell a missing credential from
+/// a wrong URL, and the existing 404-for-disabled behaviour already means a
+/// 404 here carries a different meaning. The route's existence is not the
+/// secret; the ability to RUN it is.
+FnGateDecision decideFnAuth(FnAuth mode, const FnAuthFacts& facts);
+
+/// The rate-limit bucket an HTTP invocation of a function is charged to.
+///
+/// SEPARATE from the bucket `requireCapabilityCore` charges for the function's
+/// DATA access, although both read the same `rate_limit_per_min` from the same
+/// policy. One shared bucket would make the ceiling mean something nobody
+/// intends: a function doing three collection reads per request would spend
+/// four tokens per call, so a limit of 60 would admit 15 requests, and adding
+/// a read to a script would silently lower its own request ceiling. That is
+/// the same mistake as charging a listing one token per collection examined,
+/// which this codebase already fixed once.
+///
+/// So the number is a ceiling on REQUESTS and, independently, a ceiling on
+/// data operations. Prefixed rather than bare so it can never collide with a
+/// key id or with a function's own principal id.
+std::string fnHttpThrottleBucket(const std::string& project, const std::string& functionId);
+
+} // namespace svapi::functions

+ 74 - 0
src/handlers/function_dispatch.cpp

@@ -11,6 +11,8 @@
 #include "errors.hpp"
 #include "functions/trigger_body.hpp"
 #include "functions/descriptor.hpp"
+#include "functions/fn_gate.hpp"
+#include "rate_limiter.hpp"
 #include "json_http.hpp"
 #include "server.hpp"
 #include <algorithm>
@@ -243,8 +245,13 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
 
     std::vector<functions::FunctionDescriptor> descriptors;
     std::vector<std::string> ids;
+    // The policy travels with the descriptor because the gate below needs the
+    // function's own rate ceiling, and re-reading the registry row after the
+    // route match would be a second read of data already in hand.
+    std::vector<const KeyScope*> policies;
     descriptors.reserve(rows.size());
     ids.reserve(rows.size());
+    policies.reserve(rows.size());
     for (const FunctionRecord& row : rows) {
         // A disabled or invalid function is invisible, not 403: a public caller
         // learns nothing about what the project holds.
@@ -253,6 +260,7 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
         if (!parsed.ok || parsed.descriptor.type != functions::TriggerType::Http) continue;
         descriptors.push_back(std::move(parsed.descriptor));
         ids.push_back(row.functionId);
+        policies.push_back(&row.policy);  // borrowed from `rows`, which outlives this
     }
 
     const functions::RouteMatch match = functions::matchHttpRoute(descriptors, req.method, path);
@@ -270,6 +278,72 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
     const size_t idx = static_cast<size_t>(match.descriptor - descriptors.data());
     const std::string functionId = ids[idx];
 
+    // --- The gate: who may call this, and how often. -----------------------
+    //
+    // ORDER IS DELIBERATE: authenticate first, throttle second. The reverse
+    // lets an anonymous flood spend a function's whole minute budget and lock
+    // out the one caller that holds a key - a denial of service achieved by
+    // being refused. Authenticating first rejects that flood without charging
+    // anything to the bucket the legitimate caller shares.
+    const functions::FunctionDescriptor& desc = *match.descriptor;
+    if (desc.auth == functions::FnAuth::Key) {
+        functions::FnAuthFacts facts;
+        std::string token;
+        if (auto it = req.headers.find("Authorization"); it != req.headers.end()) {
+            if (auto t = bearerToken(it->second)) token = *t;
+        }
+        facts.keyPresent = !token.empty();
+        if (facts.keyPresent) {
+            // The SAME lookup that guards /api/*, so a function's gate cannot
+            // drift from the rest of the server's idea of a valid key.
+            if (std::optional<ApiKey> k = d.keys.lookup(token)) {
+                facts.keyAuthenticates = true;
+                facts.keyGrantsProject = k->canAccess(project);
+            }
+        }
+        const functions::FnGateDecision gate = functions::decideFnAuth(desc.auth, facts);
+        if (!gate.allowed()) {
+            // NOT written to the run log, and that is a security decision
+            // rather than an oversight: the run log lives in the database, and
+            // 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.
+            const int status =
+                gate.outcome == functions::FnGateOutcome::Unauthenticated ? 401 : 403;
+            if (status == 401) res.set_header("WWW-Authenticate", "Bearer");
+            sendJson(res, status, errorBody(gate.slug, gate.message));
+            return;
+        }
+    }
+
+    // The function's own per-minute ceiling, finally enforced on the PUBLIC
+    // surface. `rate_limit_per_min` has always been in the policy vocabulary
+    // and was only ever charged on the function's DATA access, so a consumer
+    // reading the policy reasonably assumed it bounded calls and had no reason
+    // to test that assumption. An unthrottled public function that sends mail
+    // or spends a paid API is reachable by anyone who learns the URL.
+    //
+    // Charged to a SEPARATE bucket from the data-access budget, although both
+    // read the same number - see fnHttpThrottleBucket for why sharing one
+    // would make the ceiling mean something nobody intends.
+    //
+    // Honest about what this does NOT do: the ceiling is per FUNCTION, not per
+    // caller, so it bounds the DAMAGE (mail sent, paid calls made) and not the
+    // denial - one abusive caller can still exhaust a public function's minute
+    // 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.
+    if (policies[idx]->rateLimitPerMin > 0 &&
+        !rateLimiter().allow(functions::fnHttpThrottleBucket(project, functionId),
+                             policies[idx]->rateLimitPerMin)) {
+        res.set_header("Retry-After", "60");
+        sendJson(res, 429,
+                 errorBody("rate_limited", "this function's per-minute limit is exhausted"));
+        return;
+    }
+
     const std::string runId = randomToken();
     FunctionRunLog entry;
     entry.runId = runId;

+ 11 - 0
tests/CMakeLists.txt

@@ -96,6 +96,17 @@ target_link_libraries(test_functions_descriptor PRIVATE
     nlohmann_json::nlohmann_json GTest::gtest_main)
 gtest_discover_tests(test_functions_descriptor)
 
+# The /fn gate: pure policy decision plus the descriptor's auth mode.
+add_executable(test_fn_gate
+    test_fn_gate.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/fn_gate.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/descriptor.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/cron.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/timezone.cpp)
+target_include_directories(test_fn_gate PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_fn_gate PRIVATE nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_fn_gate)
+
 add_executable(test_functions_net_guard
     test_functions_net_guard.cpp
     ${CMAKE_SOURCE_DIR}/src/functions/net_guard.cpp)

+ 187 - 0
tests/test_api_integration.cpp

@@ -2,6 +2,7 @@
 #include "svapi/version.hpp"
 #include "embedding_cache.hpp"
 #include <thread>
+#include "rate_limiter.hpp"
 #include <chrono>
 #include <cstdio>
 #include <sys/stat.h>
@@ -4385,3 +4386,189 @@ TEST_F(ApiFixture, TheCollectionsListingIsFilteredByTheKeysScope) {
     EXPECT_EQ(one->status, 200) << "a two-per-minute key must afford one listing of "
                                    "several collections: " << one->body;
 }
+
+// ─── The /fn gate (task #77) ──────────────────────────────────────────────
+//
+// These drive the ROUTE, not the pure decision - test_fn_gate.cpp covers that
+// exhaustively. The lesson being honoured is the network_egress one: a policy
+// field is not done until a test exercises the route, because that defect
+// shipped in the wrong handler with a green suite and prod acceptance caught
+// it.
+//
+// All of them run with NO runner configured, which is the default deployment
+// and is what this fixture provides. That works precisely because the gate is
+// placed BEFORE the runner check, so a refusal is observable without one -
+// and a request that PASSES the gate falls through to 503
+// `runner_unavailable`, which is the pairing: it proves the gate was passed
+// rather than that everything is refused.
+namespace {
+
+/// Write a registry row directly, bypassing the push route.
+///
+/// A normal push validates the source on a runner and is refused 503 without
+/// one, so the HTTP path cannot create the fixture these tests need. Writing
+/// the row is legitimate here: the subject under test is DISPATCH, not the
+/// push.
+svapi::FunctionRecord fnRow(const std::string& id, const char* auth) {
+    svapi::FunctionRecord r;
+    r.functionId = id;
+    r.path = id + ".js";
+    r.source = "export const on = {};";
+    r.contentHash = "deadbeef";
+    r.descriptor = nlohmann::json{{"id", id},
+                                  {"type", "http"},
+                                  {"route", "/" + id},
+                                  {"auth", auth},
+                                  {"singleFlight", false}};
+    r.enabled = true;
+    r.valid = true;
+    return r;
+}
+
+/// The policy a FIRST registration inherits.
+///
+/// It has to arrive this way rather than on the record: mergeForCodePush takes
+/// the policy from the STORED row and never reads the one in the push, because
+/// a code push must not be able to widen its own access. Setting
+/// `incoming.policy` and expecting it to stick is therefore wrong, and quietly
+/// produced a function with no rate limit - which is how this test first
+/// "disproved" a throttle that works.
+svapi::KeyScope policyWithRate(uint32_t ratePerMin) {
+    svapi::KeyScope s;
+    s.rateLimitPerMin = ratePerMin;
+    return s;
+}
+
+/// Freeze the rate limiter's clock for the duration of a test.
+///
+/// NOT optional hygiene: the limiter buckets by `now / 60`, so two requests
+/// that straddle a minute boundary land in DIFFERENT windows and the second
+/// one is allowed. A throttle test on the real clock therefore passes or fails
+/// depending on what second of the minute it starts at - which is exactly what
+/// happened while writing these, and a test that fails once an hour in CI
+/// teaches people to re-run rather than to read.
+class FrozenRateClock {
+public:
+    FrozenRateClock() { svapi::rateLimiter().setClockForTesting([] { return int64_t{1'000'000'000}; }); }
+    ~FrozenRateClock() {
+        svapi::rateLimiter().setClockForTesting([] {
+            return std::chrono::duration_cast<std::chrono::seconds>(
+                       std::chrono::system_clock::now().time_since_epoch())
+                .count();
+        });
+    }
+};
+
+} // namespace
+
+TEST_F(ApiFixture, AGatedFunctionRefusesAnAnonymousCallerAndNamesHowToAuthenticate) {
+    functions_->put(project_, fnRow("gated", "key"), svapi::KeyScope{});
+
+    auto anon = noAuth();
+    auto res = anon.Get(("/fn/" + project_ + "/gated").c_str());
+    ASSERT_TRUE(res);
+    EXPECT_EQ(res->status, 401) << res->body;
+    EXPECT_EQ(res->get_header_value("WWW-Authenticate"), "Bearer")
+        << "a 401 owes the client the scheme it should use";
+    const auto body = nlohmann::json::parse(res->body);
+    EXPECT_EQ(body["error"]["code"], "unauthorized") << res->body;
+}
+
+// THE PAIRING. Without this, the refusal test above would pass equally well
+// against a dispatch that refused every request, which would be a worse
+// defect than the gap being closed - it would take the whole public function
+// surface offline.
+TEST_F(ApiFixture, AGatedFunctionWithAValidKeyPASSESTheGateAndReachesTheRunnerCheck) {
+    functions_->put(project_, fnRow("gated2", "key"), svapi::KeyScope{});
+
+    auto c = admin();
+    auto res = c.Get(("/fn/" + project_ + "/gated2").c_str());
+    ASSERT_TRUE(res);
+    // 503 because this deployment has no runner - which is exactly the point:
+    // the request got PAST the 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, APublicFunctionIsStillReachableWithNoKeyAtAll) {
+    // The default must not have moved. Every function deployed before `auth`
+    // existed is this case.
+    functions_->put(project_, fnRow("open", "public"), svapi::KeyScope{});
+
+    auto anon = noAuth();
+    auto res = anon.Get(("/fn/" + project_ + "/open").c_str());
+    ASSERT_TRUE(res);
+    EXPECT_EQ(res->status, 503) << "an unauthenticated caller must still reach a public "
+                                  "function: " << res->body;
+    EXPECT_EQ(nlohmann::json::parse(res->body)["error"]["code"], "runner_unavailable")
+        << res->body;
+}
+
+TEST_F(ApiFixture, AFunctionDeclaringNoAuthKeyIsPublic) {
+    // A row whose stored descriptor predates the field entirely, which is what
+    // every row on a deployed server looks like today.
+    svapi::FunctionRecord r = fnRow("legacy", "public");
+    r.descriptor.erase("auth");
+    functions_->put(project_, r, svapi::KeyScope{});
+
+    auto anon = noAuth();
+    auto res = anon.Get(("/fn/" + project_ + "/legacy").c_str());
+    ASSERT_TRUE(res);
+    EXPECT_EQ(res->status, 503) << "a descriptor with no auth key must stay public: "
+                                << res->body;
+}
+
+TEST_F(ApiFixture, TheFunctionsOwnRateLimitIsFinallyENFORCEDonThePublicSurface) {
+    // rate_limit_per_min has always been in the policy vocabulary and was only
+    // ever charged on the function's DATA access, so /fn was unthrottled - an
+    // e-mail bomb or a paid API burned by anyone who learned the URL.
+    const FrozenRateClock frozen;
+    functions_->put(project_, fnRow("limited", "public"), policyWithRate(1));
+
+    auto anon = noAuth();
+    const std::string path = "/fn/" + project_ + "/limited";
+
+    auto first = anon.Get(path.c_str());
+    ASSERT_TRUE(first);
+    EXPECT_EQ(first->status, 503) << "the first call is under the limit and should reach "
+                                    "the runner check: " << first->body;
+
+    auto second = anon.Get(path.c_str());
+    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")
+        << "a 429 must say when to come back";
+}
+
+TEST_F(ApiFixture, AFunctionWithNoRateLimitIsNotThrottled) {
+    // The pairing for the throttle: 0 means unlimited, as it does everywhere
+    // else in this codebase, and must not be read as "a limit of zero".
+    const FrozenRateClock frozen;
+    functions_->put(project_, fnRow("unlimited", "public"), policyWithRate(0));
+
+    auto anon = noAuth();
+    const std::string path = "/fn/" + project_ + "/unlimited";
+    for (int i = 0; i < 5; ++i) {
+        auto res = anon.Get(path.c_str());
+        ASSERT_TRUE(res);
+        EXPECT_EQ(res->status, 503) << "call " << i << " must not be throttled: " << res->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
+    // runner check a gated function would answer 503 on every deployment
+    // without a runner - which is the default - and an author would conclude
+    // their gate did not work.
+    functions_->put(project_, fnRow("ordered", "key"), svapi::KeyScope{});
+
+    auto anon = noAuth();
+    auto res = anon.Get(("/fn/" + project_ + "/ordered").c_str());
+    ASSERT_TRUE(res);
+    EXPECT_EQ(res->status, 401) << "the gate must answer before the missing runner does: "
+                                << res->body;
+}

+ 182 - 0
tests/test_fn_gate.cpp

@@ -0,0 +1,182 @@
+// The /fn gate: who may call a published HTTP function, and how often.
+//
+// Pure by construction - decideFnAuth takes three booleans rather than an
+// httplib request, so every combination can be enumerated here on the dev
+// host. The point of the split is that the POLICY question is answerable
+// without a socket, a key store or a registry.
+#include "functions/descriptor.hpp"
+#include "functions/fn_gate.hpp"
+#include <gtest/gtest.h>
+
+using namespace svapi::functions;
+
+namespace {
+
+nlohmann::json httpOn(const char* extraKey = nullptr,
+                      nlohmann::json extraValue = nlohmann::json()) {
+    nlohmann::json on{{"id", "hook"}, {"type", "http"}, {"route", "/hook"}};
+    if (extraKey) on[extraKey] = std::move(extraValue);
+    return on;
+}
+
+} // namespace
+
+// --- The declared mode --------------------------------------------------
+
+TEST(FnAuthDescriptor, DefaultsToPublicSoNothingDeployedGoesDark) {
+    // The whole reason Public is the default: every function deployed before
+    // this field existed must keep answering. A default of Key would have
+    // taken them all offline the moment the field shipped.
+    const ParseResult r = parseDescriptor(httpOn());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.descriptor.auth, FnAuth::Public);
+}
+
+TEST(FnAuthDescriptor, ParsesKey) {
+    const ParseResult r = parseDescriptor(httpOn("auth", "key"));
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.descriptor.auth, FnAuth::Key);
+}
+
+TEST(FnAuthDescriptor, ParsesAnExplicitPublic) {
+    const ParseResult r = parseDescriptor(httpOn("auth", "public"));
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.descriptor.auth, FnAuth::Public);
+}
+
+// THE important one. An unknown VALUE must be refused, where an unknown KEY is
+// ignored - a typo must never publish a function its author believed was
+// gated. Had this defaulted to Public, `auth: 'kye'` would be a silent hole
+// with a green test suite.
+TEST(FnAuthDescriptor, RefusesAnUnrecognisedValueRatherThanDefaultingToPublic) {
+    const ParseResult r = parseDescriptor(httpOn("auth", "kye"));
+    EXPECT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("auth"), std::string::npos);
+    EXPECT_NE(r.error.find("kye"), std::string::npos) << "the error must quote what was written";
+}
+
+TEST(FnAuthDescriptor, RefusesANonStringValue) {
+    EXPECT_FALSE(parseDescriptor(httpOn("auth", true)).ok);
+    EXPECT_FALSE(parseDescriptor(httpOn("auth", 1)).ok);
+}
+
+// The pairing for the refusal above: an unknown KEY is still tolerated, so the
+// strictness cannot have quietly become "refuse anything unfamiliar", which
+// would break the forward-compatibility rule parseDescriptor exists to keep.
+TEST(FnAuthDescriptor, StillIgnoresAnUnknownKeySoANewerScriptLoads) {
+    nlohmann::json on = httpOn("somethingFromALaterServer", "whatever");
+    const ParseResult r = parseDescriptor(on);
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.descriptor.auth, FnAuth::Public);
+}
+
+TEST(FnAuthDescriptor, SurvivesTheRoundTripThroughTheStoredRow) {
+    // The gate must not evaporate on a reload: toJson writes it
+    // unconditionally for exactly this reason.
+    const ParseResult first = parseDescriptor(httpOn("auth", "key"));
+    ASSERT_TRUE(first.ok) << first.error;
+    const nlohmann::json stored = first.descriptor.toJson();
+    ASSERT_TRUE(stored.contains("auth"));
+    const ParseResult second = parseDescriptor(stored);
+    ASSERT_TRUE(second.ok) << second.error;
+    EXPECT_EQ(second.descriptor.auth, FnAuth::Key);
+}
+
+TEST(FnAuthDescriptor, AuthIsIgnoredForATriggerWithNoCaller) {
+    // A cron function has nobody to authenticate. The field is accepted and
+    // simply means nothing there, rather than being an error - the descriptor
+    // vocabulary is shared across trigger types by design.
+    nlohmann::json on{{"id", "nightly"}, {"type", "cron"}, {"schedule", "0 3 * * *"}};
+    const ParseResult r = parseDescriptor(on);
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.descriptor.auth, FnAuth::Public);
+}
+
+// --- The decision -------------------------------------------------------
+
+TEST(FnGate, APublicFunctionAllowsAnAnonymousCaller) {
+    EXPECT_TRUE(decideFnAuth(FnAuth::Public, FnAuthFacts{}).allowed());
+}
+
+// The falsifiability pairing for the whole gate. Without it, every refusal
+// test below would pass just as well against a gate that refused EVERYTHING,
+// which is a worse defect than the one being fixed: it would take the public
+// function surface offline.
+TEST(FnGate, APublicFunctionIgnoresEveryFactIncludingAGarbageKey) {
+    FnAuthFacts junk;
+    junk.keyPresent = true;
+    junk.keyAuthenticates = false;
+    junk.keyGrantsProject = false;
+    EXPECT_TRUE(decideFnAuth(FnAuth::Public, junk).allowed())
+        << "a key sent to a public function must be neither required nor rejected";
+}
+
+TEST(FnGate, AGatedFunctionRefusesAnAnonymousCallerWith401) {
+    const FnGateDecision d = decideFnAuth(FnAuth::Key, FnAuthFacts{});
+    EXPECT_FALSE(d.allowed());
+    EXPECT_EQ(d.outcome, FnGateOutcome::Unauthenticated);
+    EXPECT_EQ(d.slug, "unauthorized");
+    EXPECT_NE(d.message.find("Authorization"), std::string::npos)
+        << "the message must say how to authenticate, or the author cannot act on it";
+}
+
+TEST(FnGate, AnUnknownTokenIsINDISTINGUISHABLEfromNoTokenAtAll) {
+    // Deliberate: telling a prober that the token was well formed but unknown
+    // tells them which half of the guess was right.
+    FnAuthFacts absent;
+    FnAuthFacts wrong;
+    wrong.keyPresent = true;
+    const FnGateDecision a = decideFnAuth(FnAuth::Key, absent);
+    const FnGateDecision b = decideFnAuth(FnAuth::Key, wrong);
+    EXPECT_EQ(a.outcome, b.outcome);
+    EXPECT_EQ(a.slug, b.slug);
+    EXPECT_EQ(a.message, b.message);
+}
+
+TEST(FnGate, ARealKeyForTheWrongProjectIs403NOT401) {
+    // 401 would tell the caller to try again with a credential, and re-sending
+    // the same valid key can never help. That distinction is the only thing
+    // the two statuses carry.
+    FnAuthFacts f;
+    f.keyPresent = true;
+    f.keyAuthenticates = true;
+    f.keyGrantsProject = false;
+    const FnGateDecision d = decideFnAuth(FnAuth::Key, f);
+    EXPECT_EQ(d.outcome, FnGateOutcome::Forbidden);
+    EXPECT_EQ(d.slug, "forbidden");
+}
+
+TEST(FnGate, AGrantedKeyIsAllowed) {
+    FnAuthFacts f;
+    f.keyPresent = true;
+    f.keyAuthenticates = true;
+    f.keyGrantsProject = true;
+    EXPECT_TRUE(decideFnAuth(FnAuth::Key, f).allowed());
+}
+
+// --- The throttle bucket ------------------------------------------------
+
+TEST(FnThrottleBucket, IsPerFunctionAndPerProject) {
+    EXPECT_NE(fnHttpThrottleBucket("a", "fn"), fnHttpThrottleBucket("b", "fn"));
+    EXPECT_NE(fnHttpThrottleBucket("a", "one"), fnHttpThrottleBucket("a", "two"));
+    EXPECT_EQ(fnHttpThrottleBucket("a", "fn"), fnHttpThrottleBucket("a", "fn"));
+}
+
+// The bucket is deliberately NOT the function's principal id, which is what
+// requireCapabilityCore charges for data access. Sharing one bucket would mean
+// a function doing three reads per request spent four tokens per call, so
+// adding a read to a script would silently lower its own request ceiling -
+// the same mistake as charging a listing one token per collection examined.
+TEST(FnThrottleBucket, IsSEPARATEfromTheDataAccessBudget) {
+    const std::string project = "proj";
+    const std::string id = "sendmail";
+    const std::string httpBucket = fnHttpThrottleBucket(project, id);
+    // The shapes a principal id takes elsewhere in the server.
+    EXPECT_NE(httpBucket, id);
+    EXPECT_NE(httpBucket, project + "/" + id);
+    EXPECT_NE(httpBucket, "fn:" + project + "/" + id);
+    EXPECT_NE(httpBucket, "fn:" + project + "/" + id + ":0");
+    // And it cannot collide with a key id, which is a bare token elsewhere.
+    EXPECT_NE(httpBucket.find(':'), std::string::npos)
+        << "the bucket must be namespaced, or it could collide with a key id";
+}