Ver código fonte

fix: refuse an unknown key on the invoke envelope, and reserve _expires_at

Two defects in the same family, both of which answered 200 while doing
something other than what the caller asked.

POST /functions/{id}/invoke takes an ENVELOPE describing the request to
synthesise, and every key it did not recognise was silently dropped. So a
bare `{"day":"2026-10-12"}` ran the function with an EMPTY ctx.body and
answered 200, which cannot be told apart from a run that worked - it
surfaced only because a caller asked for two different days and got the
same day back twice. Now 422 unknown_option, naming every unknown key and
listing the accepted set.

The refusal sits BEFORE the function lookup and before requireRunner,
following the one ordering rule here: authorize, then the request, then the
resource. Behind the lookup it would answer 404 to anyone whose function
was misnamed; behind the runner check it would answer 503 on every
deployment without a runner, which is the default. A non-object body gets
the same slug rather than its own, which also closes a latent 500, since
value() on a non-object throws.

manualTrigger moved to a pure header so the PAIRING could be tested at all:
without "a correct {body:{...}} still reaches ctx.body", the refusal tests
would pass equally against a route that refused everything, which is a
worse defect than the one being fixed. Falsified by adding a key to the
accepted set and confirming two tests go red while the pairing stays green.

Separately, _expires_at joins dbMetadataFields(). It is reserved by the
database from 2.19.0 and needs no client bump to matter: on the client we
ship today a caller posting it has it stored as an ordinary user field, and
such a row keeps that invisible shadow copy forever after the pin moves.
Paired with a test that an underscore field nothing reserves is still
stored, so the strip cannot become "discard anything starting with _".

Also adds a regression test for the mail timeout plumbing, labelled with
what it does NOT cover - see CLAUDE.md on CVE-2026-92387.

Consumers asked before this was written: novitax-6c and
furniture-designer-38 both measured zero /invoke call sites and neither
posts _expires_at; personal-assistant-48 had already verified {} and
{body:{...}} against their functions.

CLAUDE.md additionally records a prod diagnosis from the same morning and
the mistake in it: a 403 for a collection name nobody provisioned is
byte-identical to one for a misspelled name, and I asserted which it was
without having seen the caller's source. Four cited observations and one
uncited inference, which is the shape this file keeps warning about. The
measured parts stand; the conclusion was the consumer's to supply and they
did. Also notes a third instance of a swallowed error hiding a live defect,
and why the scope refusal needs to name the collection it refused.

It also records a second wrong inference about the same collection, made
while writing up the first: a requirement read off traffic that a fix had
removed hours earlier, so the mitigated state was mistaken for the design.
Both were about a consumer's own code and both were avoidable by asking.
fszontagh 1 mês atrás
pai
commit
5e8b9ed753

+ 18 - 3
CLAUDE.md

@@ -71,6 +71,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A CHECK THAT CANNOT *TELL* IS A DIFFERENT FAILURE FROM A CHECK THAT CANNOT FAIL, and it is harder to see.** Most of the traps recorded here are checks that could not fail. This is the other kind: a check that fires reliably and answers a DIFFERENT question than the one asked of it. The specimen: a consumer proposed detecting whether a filtered search ran on the uncapped server path by reading `db_client` from `/api/v1/version`. That field would have been returned every time, correctly, and it reports the CLIENT library version - so a client at 2.14 against a server at 2.13, where the filtered call is refused and the capped emulation runs, reads 2.14.0 throughout. The answer was dependable and about something else. Their own documentation already carried the line "`db_client` is the RUNTIME library version", written by them, three paragraphs above the proposal. **The defence is to verify when asked to confirm**: they asked me to confirm the mapping was version-deterministic and it was checking rather than agreeing that found it.
 - **Tightening a contract only helps if the consumer's failure path is LOUDER than the behaviour it replaced.** A STRICTER ERROR IS ONLY LOUD IF THE CALLER DOES NOT SWALLOW IT. Tightening `/search` to refuse an unknown option was meant to turn a silently wrong answer into a visible failure. A consumer then checked and found their `recall_memory` catches EVERY search error and falls back to keyword matching - so the new 422 would have silently degraded their search instead, with nothing logged anywhere. The defect would have moved rather than been fixed: from our silence to theirs. They now rethrow `unknown_option` specifically, and a deliberately misspelled option fails four of their tests. So when tightening a contract, "would your tests notice if you started?" has to be paired with **"does your error handling swallow it?"** - a caller with a broad catch converts a loud contract violation into a quiet capability loss, which is strictly worse than the original bug because it looks like a working system. Note what the defect becomes rather than merely where it goes: a dropped filter stops being a dropped filter and becomes a silently different retrieval strategy - still 200, still wrong, and now one layer further from the cause. In a RAG path that is a wrong answer delivered confidently, which is the single failure a knowledge base cannot afford.
   **THE SIBLING QUESTION, AND IT INVERTS THE USUAL ASSUMPTION: ASK WHETHER A HANG IS WORSE THAN A FAILURE FOR THAT CALLER, BECAUSE SOMETIMES IT IS.** Measured on the only public WRITE path on prod, toloajto's offer submission, and stated by its owner 2026-10-15. Their `quotes` INSERT is best-effort - try/catch, no retry, **no fetch timeout** - so a FAILED insert is swallowed with a console warning and is genuinely harmless, because the MiniCRM/n8n push that actually DELIVERS the offer still runs. But that insert is `await`ed SEQUENTIALLY BEFORE the delivery push, so a HUNG insert blocks the delivery for the full stall with no timeout to cut it short: the button spins, and **if the customer closes the tab mid-hang the CRM push never runs and the offer is lost outright**. So for that caller our cheapest failure is an error and our most expensive one is latency - the opposite of the usual reading, where an error is the bad outcome and a slow success is tolerable.
+  **THE QUESTION TO ASK A CONSUMER IS NOT "DO YOU RETRY ON STATUS" BUT "DOES ANYTHING ABOVE THE CALL SITE CONVERT A THROW INTO A DEFAULT".** novitax-6c's framing, 2026-10-16, when asked whether the `/invoke` 422 would reach them. Their retry set is keyed on STATUS (`RETRYABLE = new Set([429, 502, 503, 504])`, 3 attempts at 500 ms) and never on the error code, which is the design that makes a widening slug set safe - but they pointed out the half a retry question misses, from their own live code: their public portal answers an identical 202 whether the mail went out or not, so the loud failure exists and something ABOVE it flattens the signal. A status-keyed retry is only safe while nothing wraps a broad catch around the call. **toloajto is the clean instance of that same shape being the RIGHT design rather than a bug:** `postValidate()` is `if (!res.ok) return null;`, so every non-2xx including a 422 degrades to the local client-side price - deliberate, because server-authoritative pricing is an optional hardening layer with an intended fallback. So one shape is a defect in one codebase and a feature in another, only the owner can tell you which, and neither answer is visible from our side of the call.
   Two consequences worth carrying. When pricing ANY window or slow path, "what does your error handling do" is only half the question; the other half is **"what does your code do while waiting, and what is downstream of the await"**. And a caller with no client-side timeout does not experience a slow dependency as slowness - it experiences it as an abandoned transaction, which is silent, unlogged on both sides, and indistinguishable from a customer who simply changed their mind. Note our own `/rag/` mount sets `proxy_read_timeout 180s`, so the ceiling on that spin is ours, not theirs. **CLOSED ON THEIR SIDE THE SAME DAY, and the lesson is KEPT because the shape recurs rather than because the instance is open:** told that the 180 s ceiling was ours and not theirs, they added an 8 s `AbortSignal.timeout` to both offer-flow inserts and the copy-link insert, so a stall now lands in the harmless path a failure already had - the design still goes out through the CRM push, the quote simply is not persisted to rag, and the link falls back to a self-contained URL. A three-minute freeze became an 8 s fail-fast. Worth noting WHAT unlocked it: they had the timeout problem in their own code and could not see the number, because the ceiling lived in our nginx config. **A latency budget split across two owners is invisible to both of them**, so saying out loud which side holds the ceiling is cheap and is the thing that made the fix obvious.
 - **clangd, clang-format and clang-tidy are configured** (`.clangd`, `.clang-format`) and read `build-host/compile_commands.json`, so they cover `src/`, `tests/` and `runner/` including `runner/src/main.cpp`. The tidy set is narrow on purpose (`bugprone`/`cert`/`clang-analyzer`/`misc`/`performance`): the broad `modernize`/`readability` families bury real findings under thousands of style notes. `.clang-format` **describes the style the code already uses** rather than imposing one, so it is close to a no-op; `LambdaBodyIndentation: OuterScope` is the setting that matters, since every route handler is a lambda whose body is indented from the statement. Even so the codebase is hand-laid-out and not formatter-clean, so format **new or changed code only** (`git clang-format`), never whole files.
 - TS: no `any`, no TS `enum`, no constructor parameter-property shorthand (tsconfig `erasableSyntaxOnly`). Iterating parsed JSON: bind to a named var first (range-for over `nlohmann::json::parse(...)[...]` dangles).
@@ -105,7 +106,12 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 
   **But the query string CANNOT take the body's blanket treatment, and that is why this needs design rather than a copy-paste.** Every key in a JSON body is deliberate, so refusing all unknowns is safe. A query string legitimately collects things nobody meant as options - a cache-buster, a proxy's addition, a UI's `_=<timestamp>` - so a blanket 422 would break callers for params that were never asking for behaviour. The defensible line is to refuse the params a caller plausibly sends EXPECTING AN EFFECT and that we do not implement (`offset`, `page`, `cursor`, `sort`, `fields`), and to keep ignoring genuinely incidental ones. Refusing `offset` is the point; refusing `_=1760000000` is a regression.
 - **An unknown key on a vector `/search` body is REFUSED (422 `unknown_option`), not ignored** (`functions/known_keys.hpp`, pure). It was ignored until 0.10.3, and measured on prod that produced silently wrong answers rather than errors: `topK: 3` returned the DEFAULT five rows, `minScore: 0.99` returned rows where the correct spelling returns none, and **`filter:` in the singular returned the rows the caller meant to EXCLUDE** - a dropped filter is frequently a tenancy boundary in the caller's mind, which is what makes this a defect and not an ergonomic wish. Every unrecognised key is named at once, and the accepted set is listed, because the usual cause is a plausible spelling of a real option. Matching is exact and case-sensitive on purpose: accepting `Top_K` would give the service two spellings for one option, which is how the next drift starts. `ctx.fetch`, `ctx.mail` and `ctx.jobs` already behaved this way; this brought the HTTP surface in line.
-- **`POST /functions/{id}/invoke` TAKES AN ENVELOPE, AND A BARE PAYLOAD IS SILENTLY DISCARDED WITH A 200 - ANOTHER SIBLING OF THE `unknown_option` CLASS, STILL UNFIXED.** Reported by a consumer 2026-10-15 and confirmed in code: `manualTrigger()` (`handlers/functions.cpp:146`) reads exactly `method`, `path`, `params`, `query`, `headers` and `body`, and **every other key is ignored**, leaving `t["body"]` null. So `POST .../invoke` with `{"day":"2026-10-12"}` runs the function with an EMPTY `ctx.body` and answers **200**. `{json: ...}` and a JSON string do the same. The correct envelope is `{"body": {...}}`.
+- **`POST /functions/{id}/invoke` TAKES AN ENVELOPE, AND A BARE PAYLOAD USED TO BE SILENTLY DISCARDED WITH A 200. FIXED IN 0.14.0; the lesson is kept because the shape recurs.** Reported by a consumer 2026-10-15 and confirmed in code: `manualTrigger()` read exactly `method`, `path`, `params`, `query`, `headers` and `body`, and **every other key was ignored**, leaving `t["body"]` null. So `POST .../invoke` with `{"day":"2026-10-12"}` ran the function with an EMPTY `ctx.body` and answered **200**. `{json: ...}` and a JSON string did the same. The correct envelope is `{"body": {...}}`.
+  **Now refused 422 `unknown_option`** by `requireInvokeEnvelope()` (`functions/invoke_envelope.hpp`, pure), which names every unknown key at once and lists the accepted set. Four things in the fix are worth not rediscovering:
+  - **It is placed BEFORE the function lookup and before `requireRunner`**, following the one ordering rule here - authorize, then the request, then the resource. Behind the lookup it would answer 404 to anyone whose function was absent or misnamed; behind the runner check it would answer 503 on every deployment without a runner, **which is the default**, since installing the runner does not enable functions. An integration test pins it by invoking a function id that does NOT exist and demanding 422, with the pairing that a CORRECT envelope on that same path answers 404 or 503 instead - so the test proves the ordering rather than only the refusal.
+  - **A non-object body gets the SAME slug** rather than its own. A bare JSON string is the identical mistake in a different costume, and two error codes would send a caller looking for two fixes. It also stopped a latent 500: `body.value(...)` on a non-object throws `type_error`, so a posted JSON string was never the clean 200 the original report assumed.
+  - **A known key of the WRONG TYPE is still tolerated** - `params` as a string falls back to an empty object, as it always has. The defect is keys nobody reads, not retyping a field, and a test pins that as a decision rather than an oversight.
+  - **`manualTrigger` was EXTRACTED to the pure header to make the pairing testable at all.** It sat in an anonymous namespace in a file that links the database client, so "a correct `{"body":{...}}` still reaches `ctx.body`" could not be asserted anywhere - and without that half, the refusal tests would pass just as well against a route that refused EVERYTHING, which is a worse defect than the one being fixed. Deliberately falsified by adding `day` to `kInvokeEnvelopeKeys`: two refusal tests go red while the pairing stays green.
   **The cost is a false pass, which is worse than a failure.** Their re-run "looked like it had processed the day I asked for", and the function had quietly processed its DEFAULT day; it surfaced only because a second request for a DIFFERENT day returned the same day in its result. A control that returns 200 for an input it discarded cannot be distinguished from one that worked, which is exactly the shape `unknownKeys()` exists to prevent on the vector `/search` body. **This is a JSON BODY, so the blanket rule applies and is safe** - the query-string caveat about incidental parameters does not reach here, since every key in a posted body is deliberate. Fix is to run the existing `unknownKeys()` over the invoke envelope and 422 with the accepted set named, which is the same idiom and the same error shape. Their suggestion is worth taking too: echo which input the run actually used, so the answer carries its own evidence.
 - **`embedTimeoutMs` on `.search()`/`.store()` is validated, not coerced.** A non-integer or non-positive value is 422, and exceeding it is **504** `embedding_timeout` (distinct from the run simply running out of budget, because the remedies differ). It went unnoticed for a release while being silently accepted and ignored, which is exactly why an unsupported option must be refused rather than dropped.
 - **Wall time has TWO ceilings** (`functions/wall_budget.hpp`): an HTTP one (~2 s, which `RunnerPool::readTimeoutSec` must exceed) and a JOB one, which is exempt because a queue-claimed run holds no socket. `RunService::run` takes the kind as a PARAMETER, never inferred from the descriptor, and defaults to Http - the narrow budget - so a caller that forgets is slow rather than dangerous. Precedence: `min(descriptor timeoutMs or default, project max or kind ceiling, hard ceiling)`, resolved by the pure `resolveWallBudget()`. **The project cap is per kind** (`{http, job}` on `PUT /projects/{p}/settings/functions`): one number could not express "10 s for routes, 60 s for jobs", so capping a project's routes also cut its cron work and the only safe setting was no cap. `FunctionView` carries BOTH and `RunService::run` selects, because `lookup()` does not know how a run was triggered. The engine's `JsLimits::wall_time_ms` is raised to the highest ceiling at construction, or the clamp inside `JsRuntime::run` would kill every job at the HTTP value.
@@ -207,11 +213,17 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A SECOND RESTART IS NOT NEEDED ON 2.17.2, measured rather than reasoned.** Our `KeyStore`/`SettingsStore` bootstraps DO perform the online upgrade after the migration, and the log says so - but with **0 rows and 0 history versions rewritten**, because the collections are already ciphertext through the bare-alias merge. `encryption-verify` then reports `sealed: yes`, `CLEAN`, exit 0. So the window is TWO steps and ONE compaction (upgrade, then start vectorapi), with verify as the branch: plain `CLEAN` means done, `CLEAN (UNSEALED: ...)` means take the reseal inside the window. On 2.17.1 that same flag move requested a reseal that compacted every project, which is where the obsolete three-step plan came from.
   Note the upstream log line still says "old plaintext copies are removed at the next restart" even when it rewrote NOTHING, which contradicts verify's `sealed: yes` and would have an operator restart for no reason. Trust verify.
 - **MOVING THE CLIENT PACKAGE UNDER AN EXISTING BINARY IS AN ABI QUESTION, AND IT IS CHEAP TO TEST.** Every 2.x client shares one SONAME, so apt will happily put a 2.17.2 `libsmartbotic-db-client.so.2` under a server binary compiled against 2.14.0 headers - and the documented failure mode is that it installs fine and segfaults later. Verified before deploying rather than hoped: a Debian 13 container holding the real `smartbotic-vectorapi 0.12.0-1` deb plus `libsmartbotic-db-client 2.17.2-1`, against a 2.17.2 server, answered **21 of 21 calls** correctly - including `POST /indexes` with `unique`, which exercises `CreateIndexResult`, the by-value struct whose SIZE is the thing that would break, and a 409 duplicate refusal, which proves `duplicateExamples` crossed the boundary intact. `/api/v1/version` reported `db_client: 2.17.2` so the new library really was loaded. Repeat this whenever `DB_CLIENT_VERSION` and the deployed client diverge; it takes minutes and the alternative is a restart days later.
+- **A 403 FOR A COLLECTION NAME NOBODY PROVISIONED LOOKS EXACTLY LIKE A 403 FOR A MISSPELLED ONE, AND I GUESSED WHICH - WRONGLY, IN A SENTENCE THAT READ AS MEASURED.** 2026-10-16, found by sweeping prod's nginx log during toloajto's go-live. The live site requested `toloajto:kitchen_presets` on every page load and got **403**, 63 times on 14 Oct, 70 on the 15th, 6 on the 16th. What I measured was sound: the 403 is real, every other collection on the same page load answers 200 from the same origin with the same key (so not the key, not the Origin allow-list), `kitchen_presets` is absent from the admin listing of all eight collections, and the key IS granted `read`/`list` on `catalog_kitchen_modules`. **What I then asserted, having never looked at their client, is that `kitchen_presets` was a typo for `catalog_kitchen_modules` - and it was not.** The owner traced it: the two collections are genuinely unrelated, `kitchen_presets` feeds a kitchen TEMPLATE shape (layout, wallDims, plinthColor) while `catalog_kitchen_modules` is a module catalogue of a different shape that their client never reads at all, so the rename I recommended would have loaded module documents and used them as layout templates. The real cause is that the read sat in a SHARED startup catalogue load, so it fired on the public wardrobe site although kitchen is dev-gated; the fix was to gate the fetch, and the collection was simply never provisioned.
+  **The similar name is what made the wrong hypothesis attractive, and "what else would produce this exact result?" has an obvious second answer: a collection nobody ever created.** Both produce an identical 403, because the refusal names neither the collection nor the op - see the next bullet. So this is the family trap again, committed in the same afternoon as a long note about committing it, and committed in its most deceptive shape: four cited observations and one uncited inference, which reads with the credibility of its neighbours. **The rule already written here applies verbatim - if a claim has no file, line or measurement behind it, say so in the same sentence** - and the specific discipline for diagnosing someone else's caller is that **their client's INTENT is not derivable from our logs**, however suggestive the names are. Ask them.
+  **THEN I GOT THE SAME COLLECTION WRONG A SECOND TIME, IN THE MESSAGE WHERE I RECORDED GETTING IT WRONG THE FIRST TIME - AND THE SECOND ERROR HAS ITS OWN SHAPE WORTH NAMING: A REQUIREMENT INFERRED FROM TRAFFIC MEASURED AFTER THE FIX THAT SUPPRESSED THAT TRAFFIC.** Filing the follow-up, I wrote that the public key "appears not to need" `kitchen_presets` because the templates feed an admin tool. The owner corrected it: the templates feed BOTH - their startup catalogue load reads them with the PUBLIC key and renders them as the customer-facing template gallery, and the admin CRUD is the other consumer. The only reason prod showed admin-shaped access alone is that they had gated the public read behind `?dev=1` **hours earlier, that same morning, as the fix**. So I measured the state the mitigation produced and read it as the design. **The cost would have been the identical 403 on kitchen launch day, which is the failure we had just spent the morning diagnosing, reproduced at the next launch because the wrong line had hardened into the task.**
+  **The tell is a question worth asking whenever a requirement is read off observed traffic: WHAT CHANGED RECENTLY THAT WOULD REMOVE THIS TRAFFIC?** A measurement taken after a mitigation describes the mitigated system, and "nobody calls this" is not evidence that nobody needs it - most sharply when the thing that stopped the calls is a change you were told about in the same conversation. Note what did NOT save me either time: both inferences were about a consumer's own code, both were avoidable by asking, and the first correction's lesson ("a caller's intent is not derivable from our logs") was already written down when I made the second. **Writing the rule is not the same as applying it, and the gap between them is one message.**
+  **IT HID FOR THREE DAYS BECAUSE A `.catch(() => [])` TURNED IT INTO THE IN-CODE DEFAULTS**, so no user ever saw anything wrong and only our log knew. That is the THIRD independent instance in one day of the same mechanism, which is why it is recorded as a rule rather than an anecdote: novitax-6c's portal answering an identical 202 whether mail went out or not, toloajto's `postValidate()` returning null on any non-2xx, and this swallow-into-defaults. **A silent fetch failure is invisible to users and visible in our logs, which makes a log sweep worth doing on someone else's behalf** - and it is the strongest argument for the error message in the next bullet, since the one party who CAN see these has only the status code to go on.
 - **PROD HAS TWO HOSTNAMES AND THEY SERVE DIFFERENT SURFACES. Probing the customer-facing one at `/` answers 404 BY DESIGN.** Added 2026-10-15.
   - `qdrant-1.shop.static.shopcall.ai/rag/` - the ORIGINAL mount, unchanged and still the full surface including the admin web UI. `proxy_pass` carries a TRAILING SLASH here, which strips the `/rag` prefix before vectorapi sees it.
   - `global-api-01.smartbotics.ai` - the CUSTOMER-FACING name, at the ROOT, with its own Let's Encrypt cert (expires 2027-01-13, `--redirect` so 80 answers 301). `proxy_pass` has NO trailing slash, so the path reaches vectorapi unchanged. The two mounts are deliberately different and must never be copied onto each other.
   **It is a WHITELIST, not a deny-list on `/`, and that is the load-bearing choice**: `/api/` and `/healthz` are proxied, everything else returns 404. vectorapi serves its ADMIN WEB UI at `/`, which does not belong on a hostname handed to customers - and with a deny-list, a route added by a later release would be exposed the moment the package upgraded, with nobody noticing. The cost is that a genuinely public new route must be added here deliberately, which is the point. The shared proxy settings (180 s read timeout for the server-side embedding, 10 MB body) live in `/etc/nginx/snippets/vectorapi-proxy.conf` and are included by every location, so the two cannot drift.
   **`/docs`, `/openapi.json` and `/llms.txt` WERE whitelisted here for about five hours on 2026-10-15, and were then removed by the owner's decision: the API is the only thing this hostname serves.** The reason is worth keeping because it is not secrecy - nothing there was callable without a key. The docs page renders the COMPLETE operation list, admin key management, project deletion, the read-only lock and the server-wide stats included, so it published a catalogue of what to come back and try. A customer needs the one URL they were given plus minimal docs for the part they actually use. All three stay reachable on the OLD name under `/rag/`, which is where we read them. `/healthz` stays because it was verified to return `{"status":"ok"}` and nothing else, so an outside monitor needs no credential. The 404 discloses nothing further either: `server_tokens` is already off globally, so it answers `Server: nginx` with no version.
+  **AND THE REFUSAL ITSELF IS TOO QUIET: `requireCapabilityCore` ANSWERS 403 "scope does not permit this operation" WITH NO COLLECTION, NO OP AND NO HINT OF WHAT THE KEY CAN REACH** (`src/server.cpp:57`). A misspelled name, an ungranted one and a never-provisioned one are byte-identical in that answer. Confirmed by the consumer it happened to: it sent them to re-verify their KEY rather than the string, which is the wrong half of the system. **Keep the 403 - do NOT answer 404 for absent and 403 for ungranted**, because that pair lets a scoped key probe which collections exist in its project outside its scope, the leak closed deliberately above. Fix the MESSAGE: name the collection and the op asked, and echo the collections this key IS granted, which discloses nothing a holder cannot read off their own key - the same reasoning that makes `scope_filtered` safe to send unconditionally. Task #83, and deliberately NOT slipped into 0.14.0, because two consumers had already cleared that payload and changing it after they agreed means re-asking them.
   **A KEYED 404 IS THE CONTROL THAT PROVES THE BLOCK IS NGINX'S OWN.** `/docs` answers 404 WITH a valid admin key as well as without one. Without that control a 404 on this host is equally consistent with "the route is gone" and "the request was not authorized" - and those are different stories, one of which would come back the moment a customer sent a key.
   **REMOVING A ROUTE DOES NOT CLOSE A PAGE THAT IS ALREADY OPEN, AND THE HALF-DEAD RESULT READS LIKE A SERVER FAULT.** Measured in a browser immediately after the reload: the HTML and `rapidoc-min.js` came from the browser's DISK CACHE so the title still rendered, while `openapi.json` went to the network and 404'd - leaving a page that looked alive and listed nothing. A cache-busting query string answered nginx's own 404, which is the real state. So verify a withdrawal with a URL the cache has never seen, and expect anyone who had the page open to meet a BROKEN docs page rather than an absent one.
   **THE ERROR PAGES ARE BRANDED NOW, AND ONE SETTING DECIDES WHETHER THAT IS COSMETIC OR BREAKING.** `/etc/nginx/snippets/branded-errors.conf` maps 403/404/500/502/503/504 to static pages under `/var/www/smartbotics-errors/_brand/`, styled from the design tokens read off smartbotics.ai (`--gradient-primary`, `--foreground`, `--radius`), bilingual EN/HU, with a dark-mode variant. **`proxy_intercept_errors` is OFF, which is the default, and MUST STAY OFF**: it is the single setting that would replace vectorapi's own `{"error":{"code":...}}` JSON with HTML and silently break every client that parses our errors. Verified after the change that an unauthenticated `/api/v1/version` still answers the JSON envelope, because the branding is only meant to cover the errors NGINX ITSELF raises. Everything the page needs is on local disk, so the 502 page still renders when the upstream it is reporting on is down - an error page that fetched its own assets through the proxy would be blank in exactly the case it exists for. The pages are `internal` (unreachable as paths); only the logo is not, since the browser must fetch it.
@@ -315,7 +327,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   - **It can legitimately be in the PAST**, which is the whole point: the sweep runs every second, a `restrict` relation can hold a row past its TTL, and a copy taken while the server is stopped keeps expired rows until a server opens it. That is exactly the "121 hours past its deadline" row a consumer met.
   - **The restore rule, which closes the immortal-marker defect:** absent → insert with no TTL; in the PAST → **skip the row**; otherwise `ttlSeconds = ceil((_expires_at - now)/1000)`.
   - Filtering on it (`lt`, `exists`) needs a 2.19.0 **SERVER** (capability `document_expires_at`), so it is NOT available on prod today - reading it is, filtering is not. A row with no expiry is ABSENT for those filters rather than 0, so an upper bound cannot sweep up permanent rows.
-  - **IT IS RESERVED AND OUR STRIP LIST DOES NOT KNOW IT YET.** `dbMetadataFields()` (`documents_util.hpp:36`) lists six names and `_expires_at` is not among them, so on our current client a caller posting `{"_expires_at": ...}` to `POST .../documents` has it stored as an ordinary user field - precisely the shadow-copy trap that list exists to prevent, where every read overwrites the stored value and no filter can reach it. A 2.19.0 client strips it on write on both sides, but **add it to `dbMetadataFields()` regardless and independently of the pin move**: it is reserved from 2.19.0 onward, the cost to a caller is nil (they could never read their own value back), and doing it early means no row is ever written carrying one.
+  - **IT IS RESERVED AND IS NOW IN OUR STRIP LIST - DONE IN 0.14.0, INDEPENDENTLY OF THE PIN MOVE.** `dbMetadataFields()` (`documents_util.hpp`) listed six names and `_expires_at` was not among them, so a caller posting `{"_expires_at": ...}` to `POST .../documents` had it stored as an ordinary user field - precisely the shadow-copy trap that list exists to prevent, where every read overwrites the stored value and no filter can reach it. A 2.19.0 client strips it on write on both sides, but it was added **early and deliberately**, because the cost to a caller is nil (they could never read their own value back) and doing it before the pin moves means **no row is ever written carrying one** - a row written the old way keeps its invisible copy forever afterwards. Paired with a test that an underscore field nothing reserves (`_internal_id`) is still STORED, so the strip can never quietly become "discard anything starting with an underscore". Note `api/llms.txt` says plainly that the field is stripped but **not yet RETURNED** on reads, since the client we ship drops it before we see it - claiming otherwise would have been a documented guarantee nobody could observe.
 - **TTL EXPIRY IS LAZY, SO A BACKUP LEGITIMATELY HOLDS ROWS THE LIVE PROJECT NO LONGER HAS - AND ANY BACKUP-VERSUS-LIVE COMPARISON READS THAT AS DATA LOSS.** Found by a consumer verifying their own backup right after a platform window, which is the worst possible moment to meet it: their tool reported `reminders_sent: 1 NOT in the live project`, which reads exactly like we lost a row during the maintenance. We had not. The row was an idempotency marker with a 48-hour TTL that expired 2026-10-10, was **still physically present in a backup taken 121 hours past its deadline**, and had been reaped by the time they verified an hour later. So the same row is present or absent depending on when the reaper happened to run, not on whether anything was lost.
   **There is NO supported way to read a document's REMAINING TTL** - audited in `client.hpp`: `ttlSeconds` appears on insert/upsert, `patchWithTtl` and `setFileTtl`, all WRITE paths, and `CollectionInfo::defaultTtlSeconds` is the COLLECTION's default rather than a row's expiry. So inferring from row age against a table of known TTLs is currently the only method, which is sound but needs the caller to know every TTL they ever set. Requested upstream.
   **THE SHARP EDGE IS ON RESTORE, AND IT IS OURS TOO: A RESTORED ROW CARRIES NO TTL, SO PUTTING AN EXPIRED ROW BACK MAKES IT IMMORTAL.** For their idempotency markers that meant a restore would permanently suppress the work the marker guards. Our own export has the same shape - nothing in it carries a TTL, because nothing can read one - so **a restore through `POST .../documents` resurrects expired rows as permanent ones**, and the more faithful the restore looks (every id back in place) the more complete the damage. Their fix is the right pattern for anyone restoring from our export: leave expired rows OUT, and say so in the output (`0 row(s) put back, 1341 already present, 1 expired left out`) rather than silently.
@@ -330,7 +342,10 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **The deb `Depends` lists are HAND-MAINTAINED** - `create-debs.sh` copies each `control.*` template verbatim and never runs `dpkg-shlibdeps`, so a new shared-library dependency does **not** appear by itself; it surfaces as a service that refuses to start on a customer box. The mail surface added two to `control.runner`, both confirmed with `ldd` against the built binary rather than guessed: **`ca-certificates`**, because the vendored curl detects the CA bundle at CONFIGURE time and bakes the path in, and with TLS verification always on a missing bundle makes *every* mail connection fail as `mail_tls_untrusted` (which reads as a broken mail server, not a missing package); and **`libidn2-0`**, because the vendored curl keeps IDN support. IDN is deliberately not compiled out - mail hostnames are usually ASCII, but breaking an internationalised one to save a dependency is the wrong trade. **zlib, zstd and brotli are deliberately absent**: they are HTTP content encodings, HTTP is compiled out of the vendored curl, and leaving them enabled made them real package dependencies for capabilities the code cannot reach.
 - **Installing the runner does not enable functions.** `config.json` ships with no `functions.runners` endpoints, and the server disables the function routes when the list is empty (answering 503). An operator has to add the endpoint by hand, and set the same `SVAPI_RUNNER_TOKEN` in both `vectorapi.env` and `runner.env`.
 - **UPSTREAM PIN REVIEW, 2026-10-09.** Both pins were checked against what this service actually reaches, which is the standing discipline here rather than chasing version numbers.
-  - **curl: a bump to 8.23.0 is REQUIRED and is not optional.** It ships 2026-10-14 fixing **twenty-two** vulnerabilities including **CVE-2026-92392, rated HIGH** - only the third HIGH the curl project has issued since 2021 - and the details are embargoed until release day, so it cannot be judged in advance. Two of the disclosed ones are outside our build: CVE-2026-6253 (credentials leaked from a first proxy to a second) cannot apply because `PROXY` is compiled OUT, and CVE-2026-80230 (public-key pinning not enforced when peer verification is disabled) cannot apply because verification is always on and we pin no keys. The HIGH one is unknown. Since we VENDOR curl, a fix means rebuilding and republishing both binaries - `apt` cannot see a statically linked curl - so this is ours to do.
+  - **curl 8.23.0: JUDGED ITEM BY ITEM NOW THAT THE EMBARGO HAS LIFTED, AND THE HIGH IS NOT OUR EXPOSURE.** This entry used to say the bump was "REQUIRED and not optional" with "the HIGH one is unknown"; the details are public since 2026-10-14 and the picture is nearly the opposite of what the severity implied. **CVE-2026-92392 (HIGH) is a use-after-free in HTTP/2 UPLOAD handling** - a malicious server's `RST_STREAM` with `HTTP_1_1_REQUIRED` or `REFUSED_STREAM` frees a `struct Curl_easy` still in use, proven convertible to RCE under exact conditions. **We cannot reach it, for two independent reasons read off our own build rather than from prose: `CURL_DISABLE_HTTP ON` and `USE_NGHTTP2 OFF`** (`runner/CMakeLists.txt`). There is no HTTP in this curl at all, let alone HTTP/2. Of the other twenty-one, every one is rated Low and twenty are unreachable here, each ruled out by a specific setting or a missing call rather than by assumption: cookies, ALTSVC and HSTS are `CURL_DISABLE_*` (5 CVEs); `CURL_DISABLE_PROXY` (1); `CURL_USE_GSSAPI OFF` plus `CURL_DISABLE_NTLM` kill the three Negotiate ones; FTP, TFTP, POP3 and WEBSOCKETS are in the disable loop (3); OpenSSL rather than wolfSSL or GnuTLS (2); no libssh2 or libssh, so SSH `known_hosts` and the SFTP/SCP redirect are out (2); `BUILD_CURL_EXE OFF`, so the two flaws in the command-line TOOL cannot ship in a library-only build; and `curl_mime_*`, `CURLOPT_INTERFACE`, `CURLOPT_SSLCERT` and `CURLINFO_EFFECTIVE_URL` appear NOWHERE in `runner/src` (4) - we build MIME ourselves in `net/mime_build.cpp`.
+    **THE ONE THAT DOES REACH US IS A LOW, AND IT MATTERS MORE TO US THAN THE HIGH - WHICH IS THE WHOLE POINT OF JUDGING AGAINST WHAT THE SERVICE REACHES RATHER THAN AGAINST THE SEVERITY COLUMN. `CVE-2026-92387` NAMES FTP, IMAP, POP3 AND SMTP** - the "ping-pong" protocols - and is an unreachable-exit-condition loop: a server that keeps feeding data at the client's read speed while **permanently omitting the final control-response line BYPASSES `CURLOPT_TIMEOUT_MS`**. That option is exactly how `MailBudget::totalMs` is enforced (`net/mail_session.cpp:110`), so the one ceiling built against a slow mail server is the one the flaw defeats - and because a blocking host call cannot be interrupted, the QuickJS wall budget cannot rescue the run either, so an unbounded mail call holds its lease on a runtime the whole pool shares.
+    **I TRIED TO SETTLE IT BY MEASUREMENT AND THE MEASUREMENT DID NOT COVER THE CLAIM.** `MailStall.AServerThatNeverCompletesACommandIsStillBounded` (`runner/tests/mail_session_test.cpp`) drives a fake IMAP server that dribbles untagged lines forever and never sends the tagged completion. It passes - bounded at 1500 ms - but it fails with CURL'S OWN message, "Operation timed out after 1500 milliseconds with 1500 bytes received", so **`CURLOPT_TIMEOUT_MS` is what caught it, i.e. the healthy path, not the flawed loop**. The advisory's precondition needs a server feeding at the client's read speed ("an extremely high network speed or an unusually slow client") and a 20 ms dribble over loopback is neither. A bounded pass is therefore equally consistent with "not exposed" and "not reproduced", and the green tick cannot tell them apart - the same shape as everything else in this file, committed while writing the test that was meant to catch it. **So the CVE stays UNRESOLVED for us until 8.23.0 is vendored**, the test is kept as a regression test for the timeout plumbing and labelled with what it does not cover, and the tell to watch for in any future repro is a failure attributed to our own `progressDecision` deadline INSTEAD of curl's timeout.
+    **Net decision (2026-10-16): the bump is still worth taking and it is NOT an emergency, so it does not ride along in a release that consumers have cleared on the strength of two unrelated defect fixes.** The urgency that justified its own window came from an unknown HIGH; the HIGH is now known and compiled out twice over. Two of the originally disclosed ones were already ruled out on the same grounds: CVE-2026-6253 (credentials leaked from a first proxy to a second) needs `PROXY`, and CVE-2026-80230 (public-key pinning unenforced when peer verification is off) needs verification off and pinned keys, which we never do. Since we VENDOR curl, a fix means rebuilding and republishing both binaries - `apt` cannot see a statically linked curl - so this is ours to do.
   - **cpp-httplib v0.60.0/v0.60.1 exist, and NONE of their security fixes are our exposure.** Judged individually: the hostname-verification SAN fix is Mbed TLS and we build against OpenSSL; the 303-redirect body and redirect percent-decoding fixes need redirects, which `applyOutboundDefaults()` disables; the WebSocket subprotocol and ping fixes need WebSockets, which we do not use; the SSE stale-event-id fix needs SSE, likewise. v0.60.1 is Windows certificate handling and an MSVC compile error. So the 0.59.0 pin stays deliberately, for the same reason it was not moved for the regex stack-overflow fix. Worth upgrading for hygiene when something else forces a rebuild, not before.
 - **cpp-httplib is pinned (`cmake/Dependencies.cmake`) and the pin carries its reasoning.** Currently v0.59.0. Check for an upgrade periodically: it serves the public HTTP surface AND every outbound call, upstream ships security fixes most releases, and we were 17 releases behind before anyone looked. When evaluating one, judge each fix against **what this service actually reaches** rather than the changelog's severity - `CPPHTTPLIB_REQUEST_URI_MAX_LENGTH` (8192, enforced before routing) means a long-path attack answers 414 before routing and never reaches the regex matcher, so the headline regex stack-overflow fix was never our exposure (verified against a running server, after first proving which process held the port - an earlier run of this test hit an unrelated service listening on the port I had picked), while the request-PARSING fixes (chunked transfer-coding matching, Content-Length truncation, chunk-size control characters) are. Deliberately NOT on the newest release when its fixes are for backends or features we do not use.
 - **Monaco** is bundled locally (`webui/src/monacoSetup.ts`) so the editor works offline - do not revert to the CDN loader.

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.13.0
+0.14.0

+ 5 - 2
api/llms.txt

@@ -92,7 +92,7 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
   **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values`, while a document **id** that is already taken is **409** `duplicate_id` (different remedies: change the value, versus choose another id or upsert with `PUT`) (the same slug `POST /indexes` returns), and `error.details` names the index: **`field`** when one field collided or **`fields`** when several, **`values`** (an OBJECT of the colliding field/value pairs, not a bare `value`), `conflicting_document_id` (the document already holding it), and `relation` or `current_version` where they apply. A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing collection is **404** only when its absence is CONFIRMED: if the database cannot be reached the answer is **503**, never a 404, so a 404 is always safe to treat as definitive and unretryable. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write. **On a `kind=vector` collection, a PUT whose body carries no vector is refused **422** `vector_replace_unsafe`.** A replace discards the stored embedding and the caller cannot prevent it, because no read returns the vector - so there is nothing to put back. Use `PATCH` for fields, or `POST .../vectors` to store a document together with its vector.
 
-  **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`. The metadata fields below (`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by`, `_updated_by`) are stripped from every write body, so you can read a document, edit a field and send the whole thing back without storing stale metadata as real fields.
+  **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`. The metadata fields below (`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by`, `_updated_by`, `_expires_at`) are stripped from every write body, so you can read a document, edit a field and send the whole thing back without storing stale metadata as real fields. **`_expires_at` is reserved and stripped, but this server does not yet RETURN it** - it is the document's absolute expiry in epoch ms, the database has always sent it, and the client library we currently ship drops it before we see it, so reads omit it today and will start carrying it when that pin moves. It is stripped from writes already so that no row is ever stored with an invisible copy of it. Set an expiry with `?ttl_seconds=`, never by posting this field. When it does appear, **absent means no expiry, never zero**, and a value may legitimately be in the PAST: expiry is swept lazily, so a row can outlive its deadline - which is also why a restore must LEAVE OUT an expired row rather than put it back permanent.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID. The body is the stored document **plus the database's read-only metadata**: `_id`, `_version` (an integer, starting at 1 and incremented by every write), `_created_at`, `_updated_at` (epoch ms), `_created_by`, `_updated_by`. `_version` is the value `?if_version=` takes, and it is also returned as an `ETag` header. These names are reserved: a field of your own called `_version` cannot be stored or read back.
 - `PUT   /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace the document at `{id}`, **creating it when it does not exist** (a real upsert, as the method means). Accepts the same two body shapes as POST. **201** `{id, created:true, version:1}` with a `Location` header when it created, **200** `{id, created:false, version:N}` when it replaced. A replace is not a merge: fields the body omits are dropped. Creating counts as an insert for authorization, so a capability-scoped key granted `update` but not `insert` on the collection gets **403** on a PUT to an id that does not exist yet and can only replace. PUT does not take `?ttl_seconds=`; use POST with an `id` to create with an expiry.
 - `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (RFC 7396 merge: a `null` removes a field); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. Returns `{id, version}`. **404** when the document does not exist - unlike PUT, PATCH never creates, because merging fields into nothing has no defined result and a patch body is not a whole document. Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
@@ -346,7 +346,10 @@ export default async function (ctx) {
 - `DELETE /api/v1/projects/{project}/functions/{id}` - Delete the function, its code and its policy.
 - `PUT  /api/v1/projects/{project}/functions/{id}/policy` `{policy:{rules, origins?, rate_limit_per_min?, expires_at?}}` **(admin)** - Replace what the function may touch. Same vocabulary as a key scope (`rules` of `{collection, ops}` over `read`/`list`/`search`/`insert`/`update`/`delete`), with one difference: an **empty** rule set is legal and means the function reaches nothing. This is the only route that changes a policy.
 - `PUT  /api/v1/projects/{project}/functions/{id}/enabled` `{enabled}` - Enable or disable a function.
-- `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method. Returns **200** whenever the run was *performed*, with `{run_id, ok, status, headers, body, console, duration_ms, error, timed_out, out_of_memory}` - the function's own failure is in that envelope, not in the HTTP status, so "the function returned 500" stays distinguishable from "the invoke could not be performed". A disabled or invalid function is **409**; a runner that cannot be reached is **503** `runner_unreachable`, and the failed attempt is still logged.
+- `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method.
+  **THE BODY IS AN ENVELOPE DESCRIBING THE REQUEST TO SYNTHESISE, NOT THE FUNCTION'S PAYLOAD - and getting that wrong used to answer 200.** A payload goes under `body`:
+  `curl -XPOST -H 'Authorization: Bearer $KEY' -H 'Content-Type: application/json' -d '{"body":{"day":"2026-10-12"}}' https://host/api/v1/projects/acme/functions/daily-report/invoke`
+  The function reads that as `ctx.body`. An unrecognised top-level key is **422** `unknown_option`, naming every one of them and listing the accepted set, and a body that is not a JSON object is refused the same way. Until 0.14.0 an unknown key was silently DISCARDED and the call still answered **200**, so a bare `{"day":"2026-10-12"}` ran the function with an EMPTY `ctx.body` and was indistinguishable from a run that had worked - it surfaced only when a caller asked for two different days and got the same day back twice. If you invoke with a payload, check the shape: a 422 now means you were previously getting a run of your function's DEFAULT input, not of the input you sent. A key of the wrong TYPE is not refused - `params` as a string falls back to an empty object, as it always has. Returns **200** whenever the run was *performed*, with `{run_id, ok, status, headers, body, console, duration_ms, error, timed_out, out_of_memory}` - the function's own failure is in that envelope, not in the HTTP status, so "the function returned 500" stays distinguishable from "the invoke could not be performed". A disabled or invalid function is **409**; a runner that cannot be reached is **503** `runner_unreachable`, and the failed attempt is still logged.
 - `GET  /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, headers, started_at}]}`. `headers` is omitted when the function set none, and is present so a stored run renders with the same shape as a fresh invoke envelope. `?limit=` defaults to 50.
   **A failed run now also carries `failure_kind`, which says WHOSE problem it is.** `function_fault` means the script's own doing (it threw, returned a non-response, blew its memory ceiling, is disabled or will not compile) and is never retried. `runner_fault`, `abandoned` (a runner died holding the job) and `malformed` (a corrupt queue row) are OURS, not yours. `transient_lookup` is a registry read that did not answer; `reclaimed` is a stale claim going back for another attempt, so the job has not failed. The classification was always computed and then discarded, so a failed job recorded only a free-text message - and matching on message text is exactly what nobody should have to do.
   **The field is ABSENT on a successful run AND on a server older than this release, so never read its absence as "no failure" - `ok` is the field that answers that.** The names are append-only and will not be respelled; an unrecognised one is a kind added by a newer server, so treat an unknown value as "something failed, cause not known to me" rather than ignoring the run.

+ 47 - 2
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.13.0",
+    "version": "0.14.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {
@@ -3861,7 +3861,7 @@
       ],
       "post": {
         "summary": "Run a function once with a synthesised trigger, and record the run",
-        "description": "Every field of the body is optional: an empty body invokes the function with its own route as the path and POST as the method. The call answers 200 whenever the run was PERFORMED, even if the function itself failed - its status, error and console output are in the envelope. The run is appended to the function's log either way.",
+        "description": "Every field of the body is optional: an empty body invokes the function with its own route as the path and POST as the method. The call answers 200 whenever the run was PERFORMED, even if the function itself failed - its status, error and console output are in the envelope. The run is appended to the function's log either way.\n\nTHE BODY IS AN ENVELOPE DESCRIBING THE REQUEST TO SYNTHESISE, NOT THE FUNCTION'S PAYLOAD. A payload goes under `body`: send {\"body\": {\"day\": \"2026-10-12\"}}, and the function reads it as ctx.body. An unrecognised key is refused 422 `unknown_option` naming every one of them and the accepted set. Until 0.14.0 it was silently DISCARDED and the call still answered 200, so a bare {\"day\": \"2026-10-12\"} ran the function with an EMPTY ctx.body and looked like it had worked - which is why this refusal exists rather than a tolerant read. A body that is not a JSON object is refused the same way.",
         "operationId": "invokeFunction",
         "requestBody": {
           "required": false,
@@ -3901,6 +3901,41 @@
                   "body": {
                     "description": "ctx.body; any JSON type"
                   }
+                },
+                "additionalProperties": false,
+                "description": "The request to synthesise. Unknown keys are refused 422 rather than ignored; the function's own payload belongs under `body`."
+              },
+              "examples": {
+                "payload": {
+                  "summary": "A payload for the function - the shape to copy",
+                  "value": {
+                    "body": {
+                      "day": "2026-10-12"
+                    }
+                  }
+                },
+                "smoke": {
+                  "summary": "Does it still run? No payload needed",
+                  "value": {}
+                },
+                "fullRequest": {
+                  "summary": "A complete synthesised request",
+                  "value": {
+                    "method": "GET",
+                    "path": "/report",
+                    "params": {
+                      "id": "7"
+                    },
+                    "query": {
+                      "format": "json"
+                    },
+                    "headers": {
+                      "x-trace": "1"
+                    },
+                    "body": {
+                      "day": "2026-10-12"
+                    }
+                  }
                 }
               }
             }
@@ -3926,6 +3961,16 @@
           "404": {
             "description": "No such function"
           },
+          "422": {
+            "description": "An unrecognised key on the envelope, or a body that is not an object (code unknown_option). The message names every unknown key and lists the accepted set. A payload for the function goes under `body`.",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
+          },
           "409": {
             "description": "The function is disabled (code function_disabled) or marked invalid (code function_invalid)",
             "content": {

+ 6 - 1
runner/tests/fake_mail_server.hpp

@@ -106,7 +106,12 @@ private:
         }
     }
 
-    void serve(int client) {
+protected:
+    /// Virtual so a test can model a server that never completes a command.
+    /// CVE-2026-92387 (curl <= 8.22.0) is reachable only by a server that keeps
+    /// FEEDING data while permanently omitting the final control-response
+    /// line, which no reply-per-line implementation can express.
+    virtual void serve(int client) {
         const std::string hello = greeting();
         // MSG_NOSIGNAL on every send. Writing to a peer that has gone away
         // raises SIGPIPE, whose default action kills the whole test PROCESS

+ 134 - 0
runner/tests/mail_session_test.cpp

@@ -1,6 +1,10 @@
 #include <gtest/gtest.h>
 
 #include <algorithm>
+#include <chrono>
+#include <cstring>
+#include <iostream>
+#include <thread>
 
 #include "fake_mail_server.hpp"
 #include "net/mail_session.hpp"
@@ -277,3 +281,133 @@ TEST(SmtpSend, AnEmptyEnvelopeIsRefusedBeforeAnySocketIsOpened) {
     noRecipient.sender = "from@example.com";
     EXPECT_EQ(smtpSend(accountFor(1), optionsFor(), noRecipient, "x").slug, "mail_no_recipient");
 }
+
+namespace {
+
+/// A server that answers a command with untagged lines FOREVER and never sends
+/// the tagged completion line.
+///
+/// This is the shape of CVE-2026-92387 (curl 8.10.0 through 8.22.0, Low), which
+/// names exactly our two protocols: on a "ping-pong" protocol - FTP, IMAP, POP3,
+/// SMTP - a server that permanently omits the final control-response line while
+/// continuing to feed data at the client's read speed sends libcurl into a loop
+/// whose exit condition is never reached, **bypassing `CURLOPT_TIMEOUT_MS`**.
+/// That option is precisely how `MailBudget::totalMs` is enforced, so the one
+/// ceiling we built against a slow mail server is the one the flaw defeats.
+///
+/// It matters more here than its Low rating suggests, because a blocking host
+/// call cannot be interrupted: while curl is inside this loop the QuickJS
+/// interrupt handler never runs, so the function's wall budget cannot rescue
+/// the run either. An unbounded mail call holds its lease on a pooled runtime,
+/// and the pool is shared by every tenant.
+///
+/// **WHAT THIS TEST COVERS, AND WHAT IT DOES NOT - read this before citing it.**
+/// It pins that a command the server NEVER COMPLETES is bounded rather than
+/// endless, which is worth a regression test on its own: there are two
+/// independent deadlines here (curl's `CURLOPT_TIMEOUT_MS`, and our own
+/// `progressDecision`, which compares the same `deadlineMs` against the clock
+/// and aborts by returning non-zero), and this asserts that at least one of
+/// them fires.
+///
+/// **IT DOES NOT ESTABLISH IMMUNITY TO CVE-2026-92387, and the reason is the
+/// whole lesson.** Measured on the vendored curl 8.22.0 it fails at exactly the
+/// budget with curl's own message - "Operation timed out after 1500
+/// milliseconds with 1500 bytes received" - so it was CURL'S TIMEOUT that
+/// caught it, which is the option the flaw lets a server BYPASS. In other
+/// words this server reaches the healthy path, not the flawed loop: the
+/// advisory's precondition is a server feeding at the client's read speed,
+/// needing "an extremely high network speed or an unusually slow client", and
+/// a 20 ms dribble over loopback is neither. A bounded result is therefore
+/// equally consistent with "we are not exposed" and with "the bug was not
+/// reproduced", and nothing in the pass distinguishes them.
+///
+/// So treat this as a test of our timeout plumbing, and treat the CVE as
+/// UNRESOLVED for us until 8.23.0 is vendored. If someone later writes a
+/// server that genuinely reproduces the loop, the thing to watch for is a
+/// failure attributed to our progress deadline INSTEAD of curl's timeout -
+/// that, and not a green tick here, would be the evidence.
+class FakeStallingImapServer : public FakeImapServer {
+protected:
+    void serve(int client) override {
+        const std::string hello = greeting();
+        ::send(client, hello.data(), hello.size(), MSG_NOSIGNAL);
+
+        std::string buffer;
+        char chunk[4096];
+        bool dribbling = false;
+        while (running_) {
+            if (dribbling) {
+                // An untagged line that is valid IMAP and completes nothing.
+                static const char* kNoise = "* OK still working\r\n";
+                if (::send(client, kNoise, ::strlen(kNoise), MSG_NOSIGNAL) <= 0) return;
+                std::this_thread::sleep_for(std::chrono::milliseconds(20));
+                continue;
+            }
+            const ssize_t n = ::recv(client, chunk, sizeof(chunk), 0);
+            if (n <= 0) return;
+            buffer.append(chunk, static_cast<size_t>(n));
+            size_t nl;
+            while ((nl = buffer.find("\r\n")) != std::string::npos) {
+                const std::string line = buffer.substr(0, nl);
+                buffer.erase(0, nl + 2);
+                record(line);
+                // Everything up to and including SELECT is answered properly,
+                // so the session is genuinely established and authenticated -
+                // the stall has to happen on a real command, not at the
+                // handshake, or the test would only be measuring a connect.
+                if (line.find("FETCH") != std::string::npos) {
+                    dribbling = true;
+                    break;
+                }
+                bool closeAfter = false;
+                const std::string reply = respond(line, closeAfter);
+                if (!reply.empty()) ::send(client, reply.data(), reply.size(), MSG_NOSIGNAL);
+                if (closeAfter) return;
+            }
+        }
+    }
+};
+
+}  // namespace
+
+// IS THE CVE-2026-92387 SHAPE BOUNDED ON THE CURL WE SHIP? Measured, because
+// the answer decides whether the 8.23.0 bump needs its own window or is
+// hygiene. A hang here would be a live availability finding on the deployed
+// runner; a bounded failure means our own progress-callback deadline covers
+// what curl's timeout does not.
+TEST(MailStall, AServerThatNeverCompletesACommandIsStillBounded) {
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    FakeStallingImapServer server;
+    ASSERT_TRUE(server.start());
+
+    ImapSession session;
+    // A SHORT budget, so a pass cannot be the test harness simply waiting the
+    // default out: 1500 ms of budget against a server dribbling for as long as
+    // anyone will listen.
+    ASSERT_TRUE(session.open(accountFor(server.port()), optionsFor(1500)).ok());
+
+    const auto started = std::chrono::steady_clock::now();
+    std::string response;
+    const MailFailure f = session.command("INBOX", "UID FETCH 7 BODY.PEEK[]", response);
+    const auto elapsedMs = std::chrono::duration_cast<std::chrono::milliseconds>(
+                               std::chrono::steady_clock::now() - started).count();
+
+    // It must FAIL - a success would mean we accepted a response the server
+    // never finished sending.
+    EXPECT_FALSE(f.ok()) << "a never-completed command reported success";
+    // And it must fail PROMPTLY. The ceiling is generous (10x the budget)
+    // because the point is bounded-versus-unbounded, not the exact margin; an
+    // unmitigated infinite loop would sit here until the test timeout.
+    EXPECT_LT(elapsedMs, 15000) << "the call was not bounded: " << elapsedMs << " ms";
+    // Printed rather than asserted, and worth READING rather than skipping:
+    // WHICH mechanism caught it is the informative part. curl's own message
+    // ("Operation timed out after N milliseconds") means CURLOPT_TIMEOUT_MS
+    // won, so this run did not exercise the loop CVE-2026-92387 describes -
+    // see the long comment above before drawing any conclusion about it.
+    std::cerr << "[ stall ] bounded after " << elapsedMs << " ms as "
+              << (f.slug.empty() ? "(no slug)" : f.slug) << ": " << f.message
+              << " (retryable=" << (f.retryable ? "true" : "false") << ")\n";
+
+    server.stop();
+    mailGlobalCleanup();
+}

+ 12 - 2
src/documents_util.hpp

@@ -33,9 +33,19 @@ namespace svapi {
 /// The names are reserved by the database (its projection layer always carries
 /// them across), so refusing to store a field of the same name costs a caller
 /// nothing: it could never read its own value back.
+///
+/// `_expires_at` is reserved from database 2.19.0, which is where the CLIENT
+/// began carrying it back on reads - the server had always sent it. It is
+/// listed here INDEPENDENTLY of moving our client pin, and deliberately
+/// earlier: on the client we ship today a caller posting `_expires_at` has it
+/// stored as an ordinary user field, which is exactly the shadow copy this
+/// list exists to prevent, and a row written that way keeps the invisible
+/// field after the pin moves. Stripping it now means no row is ever written
+/// carrying one. Note an ABSENT `_expires_at` means "no expiry", never zero.
 inline const std::vector<std::string>& dbMetadataFields() {
-    static const std::vector<std::string> f{
-        "_id", "_version", "_created_at", "_updated_at", "_created_by", "_updated_by"};
+    static const std::vector<std::string> f{"_id",         "_version",    "_created_at",
+                                            "_updated_at", "_created_by", "_updated_by",
+                                            "_expires_at"};
     return f;
 }
 

+ 77 - 0
src/functions/invoke_envelope.hpp

@@ -0,0 +1,77 @@
+#pragma once
+
+#include "../errors.hpp"
+#include "known_keys.hpp"
+
+#include <initializer_list>
+#include <nlohmann/json.hpp>
+#include <string>
+#include <string_view>
+
+namespace svapi::functions {
+
+/// The keys `POST /functions/{id}/invoke` accepts on its envelope.
+///
+/// The envelope describes the HTTP request to SYNTHESISE, which is why a
+/// payload goes under `body` rather than at the top level: the two are
+/// different things, and the route has no way to tell a stray top-level key
+/// from a field the caller meant to be part of the payload.
+inline constexpr std::initializer_list<std::string_view> kInvokeEnvelopeKeys = {
+    "method", "path", "params", "query", "headers", "body"};
+
+/// Refuse an envelope this route cannot honour, with 422 `unknown_option`.
+///
+/// Until 0.14.0 every unrecognised key was SILENTLY DROPPED, which made the
+/// commonest mistake a false pass rather than a failure: `POST .../invoke`
+/// with a bare `{"day":"2026-10-12"}` ran the function with an EMPTY
+/// `ctx.body` and answered **200**, so the run looked like it had processed
+/// the requested day and had actually processed its default. It surfaced only
+/// because a caller asked for two different days and got the same day back
+/// twice - a 200 for an input the handler discarded cannot be told apart from
+/// one that worked.
+///
+/// **The blanket rule is safe here BECAUSE THIS IS A JSON BODY.** The
+/// query-string routes deliberately refuse only the parameters a caller
+/// plausibly sends expecting an effect, since a query string legitimately
+/// collects cache-busters and proxy additions that were never asking for
+/// behaviour. Every key in a posted body is deliberate, so there is no
+/// incidental case to protect - the same reasoning the vector `/search` body
+/// already uses.
+///
+/// A non-object body is refused by the same slug rather than by a different
+/// one. `{"body":{...}}` is the shape, so a bare JSON string or array is the
+/// same mistake arriving in a different costume, and splitting it across two
+/// error codes would only make the caller look for two fixes.
+inline void requireInvokeEnvelope(const nlohmann::json& body) {
+    if (!body.is_object())
+        throw ApiError(ErrCode::Unprocessable, "unknown_option",
+                       "the invoke body must be an object describing the request to "
+                       "synthesise; put the function's payload under 'body', as "
+                       "{\"body\": ...}");
+    if (const auto unknown = unknownKeys(body, kInvokeEnvelopeKeys); !unknown.empty())
+        throw ApiError(ErrCode::Unprocessable, "unknown_option",
+                       unknownKeyMessage(unknown, kInvokeEnvelopeKeys) +
+                           "; a payload for the function goes under 'body'");
+}
+
+/// The trigger a manual invoke synthesises. Every field is optional: invoking a
+/// function with no body is the common case ("does it still run?"), so the
+/// defaults have to produce a usable request.
+///
+/// `route` is the function's own declared route, used when the caller names no
+/// path. Takes it as a string rather than the record so this stays pure.
+inline nlohmann::json manualTrigger(const std::string& route, const nlohmann::json& body) {
+    nlohmann::json t;
+    t["method"]  = body.value("method", std::string("POST"));
+    t["path"]    = body.value("path", route);
+    t["params"]  = body.contains("params") && body["params"].is_object()
+                       ? body["params"] : nlohmann::json::object();
+    t["query"]   = body.contains("query") && body["query"].is_object()
+                       ? body["query"] : nlohmann::json::object();
+    t["headers"] = body.contains("headers") && body["headers"].is_object()
+                       ? body["headers"] : nlohmann::json::object();
+    t["body"]    = body.contains("body") ? body["body"] : nlohmann::json();
+    return t;
+}
+
+}  // namespace svapi::functions

+ 14 - 20
src/handlers/functions.cpp

@@ -1,5 +1,6 @@
 #include "errors.hpp"
 #include "function_record.hpp"
+#include "functions/invoke_envelope.hpp"
 #include "json_http.hpp"
 #include "project_settings.hpp"
 #include "query_params.hpp"
@@ -140,23 +141,9 @@ uint32_t limitParam(const httplib::Request& req, uint32_t fallback) {
     return static_cast<uint32_t>(wide);
 }
 
-/// The trigger a manual invoke synthesises. Every field is optional: invoking a
-/// function with no body is the common case ("does it still run?"), so the
-/// defaults have to produce a usable request.
-nlohmann::json manualTrigger(const FunctionRecord& fn, const nlohmann::json& body) {
-    const std::string route =
-        fn.descriptor.is_object() ? fn.descriptor.value("route", std::string()) : std::string();
-    nlohmann::json t;
-    t["method"]  = body.value("method", std::string("POST"));
-    t["path"]    = body.value("path", route);
-    t["params"]  = body.contains("params") && body["params"].is_object()
-                       ? body["params"] : nlohmann::json::object();
-    t["query"]   = body.contains("query") && body["query"].is_object()
-                       ? body["query"] : nlohmann::json::object();
-    t["headers"] = body.contains("headers") && body["headers"].is_object()
-                       ? body["headers"] : nlohmann::json::object();
-    t["body"]    = body.contains("body") ? body["body"] : nlohmann::json();
-    return t;
+/// The function's own declared route, for an invoke that names no path.
+std::string descriptorRoute(const FunctionRecord& fn) {
+    return fn.descriptor.is_object() ? fn.descriptor.value("route", std::string()) : std::string();
 }
 
 nlohmann::json runEnvelope(const std::string& runId, const RunnerRunResult& r) {
@@ -291,17 +278,24 @@ void registerFunctionRoutes(ApiServer& s) {
              [d](const httplib::Request& req, httplib::Response& res) {
         std::string project = req.matches[1], id = req.matches[2];
         requireProjectManage(requireKey(*d, req), project);
+
+        // Authorize, then the REQUEST, then the resource - the one ordering
+        // used across this service. A bad envelope is wrong whether or not the
+        // function exists, so answering 404 first would hide it until the
+        // caller created one, and this particular fault is worth surfacing
+        // early precisely because its old behaviour was a 200.
+        const nlohmann::json body = req.body.empty() ? nlohmann::json::object() : bodyJson(req);
+        functions::requireInvokeEnvelope(body);
+
         auto fn = d->functions.get(project, id);
         if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
         requireRunnable(*fn);
         RunnerPool& pool = requireRunner(*d);
-
-        const nlohmann::json body = req.body.empty() ? nlohmann::json::object() : bodyJson(req);
         // A run id is just a random token with no secret meaning; generateApiKey
         // is reused rather than adding a second hex generator.
         const std::string runId = generateApiKey();
         const uint64_t startedAt = static_cast<uint64_t>(std::time(nullptr));
-        RunnerRunResult r = pool.run(project, id, manualTrigger(*fn, body));
+        RunnerRunResult r = pool.run(project, id, functions::manualTrigger(descriptorRoute(*fn), body));
 
         FunctionRunLog entry;
         entry.runId      = runId;

+ 5 - 0
tests/CMakeLists.txt

@@ -287,6 +287,11 @@ target_link_libraries(test_file_name PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_file_name)
 
 # Document body shaping and the increment deltas: header-only and pure.
+add_executable(test_invoke_envelope test_invoke_envelope.cpp)
+target_include_directories(test_invoke_envelope PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_invoke_envelope PRIVATE nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_invoke_envelope)
+
 add_executable(test_documents_util test_documents_util.cpp)
 target_include_directories(test_documents_util PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_documents_util PRIVATE nlohmann_json::nlohmann_json GTest::gtest_main)

+ 57 - 0
tests/test_api_integration.cpp

@@ -4262,6 +4262,63 @@ TEST_F(ApiFixture, NoListingRouteRefusesAnIncidentalParameter) {
     }
 }
 
+// THE INVOKE ENVELOPE IS REFUSED BEFORE THE FUNCTION IS LOOKED UP, AND BEFORE
+// A RUNNER IS REQUIRED. Both orderings matter and neither is incidental.
+//
+// Before 0.14.0 an unrecognised key was silently discarded and the call
+// answered 200 having run the function with an EMPTY ctx.body, so this is the
+// one route in the service where the OLD behaviour was a success code. Getting
+// the ordering wrong would hide the new refusal behind a 404 for anyone who had
+// not created the function yet, or behind a 503 on any deployment without a
+// runner - and a deployment without a runner is the default, since installing
+// the runner does not enable functions.
+//
+// It therefore also runs on a host with no runner at all, which is what the
+// fixture is: a 422 here PROVES the check precedes `requireRunner`, because a
+// correct envelope on this same path answers 503.
+TEST_F(ApiFixture, TheInvokeEnvelopeIsRefusedBeforeTheFunctionAndTheRunner) {
+    auto c = admin();
+    // Deliberately a function id that does not exist. If the refusal were
+    // placed after the lookup this would be a 404 and the defect would be
+    // invisible to anyone whose function was absent or misnamed.
+    const std::string path =
+        "/api/v1/projects/" + project_ + "/functions/nosuchfn/invoke";
+
+    // The reported shape: the payload at the top level instead of under `body`.
+    auto bare = c.Post(path.c_str(), nlohmann::json{{"day", "2026-10-12"}}.dump(),
+                       "application/json");
+    ASSERT_TRUE(bare);
+    ASSERT_EQ(bare->status, 422) << bare->body;
+    const auto err = nlohmann::json::parse(bare->body)["error"];
+    EXPECT_EQ(err["code"], "unknown_option");
+    EXPECT_NE(err["message"].get<std::string>().find("'day'"), std::string::npos)
+        << err["message"];
+
+    // A body that is not an object at all, which used to reach `value()` on a
+    // non-object.
+    auto str = c.Post(path.c_str(), "\"2026-10-12\"", "application/json");
+    ASSERT_TRUE(str);
+    EXPECT_EQ(str->status, 422) << str->body;
+
+    // THE PAIRING, and the half that proves the ordering rather than the
+    // refusal: a CORRECT envelope on the very same path gets past the envelope
+    // check and is then answered by whatever comes next - the 404 for the
+    // missing function, or a 503 if this host had no runner configured but the
+    // function existed. Either way it is NOT 422, so the refusal above was
+    // about the envelope and not about the route being unreachable.
+    auto good = c.Post(path.c_str(), nlohmann::json{{"body", {{"day", "2026-10-12"}}}}.dump(),
+                       "application/json");
+    ASSERT_TRUE(good);
+    EXPECT_NE(good->status, 422) << good->body;
+    EXPECT_TRUE(good->status == 404 || good->status == 503) << good->status << ": " << good->body;
+
+    // And an EMPTY body stays legal - "does it still run?" is the commonest
+    // invoke. Same reasoning: it must not be 422.
+    auto empty = c.Post(path.c_str(), "", "application/json");
+    ASSERT_TRUE(empty);
+    EXPECT_NE(empty->status, 422) << empty->body;
+}
+
 // A COLLECTION-SCOPED KEY MUST NOT ENUMERATE THE WHOLE PROJECT. Project access
 // alone used to be the only check here, so a key granted exactly one
 // collection could read every collection's name, document count and size -

+ 28 - 0
tests/test_documents_util.cpp

@@ -162,3 +162,31 @@ TEST(DocumentBody, IdBesideDataWrapperIsAllowed) {
     json d = documentBody(json{{"id", "x"}, {"data", {{"name", "a"}}}});
     EXPECT_EQ(d, (json{{"name", "a"}}));
 }
+
+// `_expires_at` is stripped like every other reserved name. It joined the list
+// when database 2.19.0 reserved it, BEFORE our client pin moved, because on the
+// older client a posted `_expires_at` is stored as an ordinary user field and
+// stays there as an invisible shadow copy after the pin does move.
+TEST(DocumentBody, StripsTheReservedExpiryField) {
+    json d = documentBody(json{{"_expires_at", 1760000000000ull}, {"name", "a"}});
+    EXPECT_EQ(d, (json{{"name", "a"}}));
+
+    // Through the `data` wrapper as well, which is the shape a read-modify-write
+    // loop actually produces.
+    json w = documentBody(json{{"data", {{"_expires_at", 1760000000000ull}, {"name", "a"}}}});
+    EXPECT_EQ(w, (json{{"name", "a"}}));
+}
+
+// The pairing. Without it the strip list could have become a blanket refusal of
+// every underscore-prefixed key and the test above would still pass - and that
+// would silently discard a caller's own `_internal_id`, which nothing reserves.
+TEST(DocumentBody, KeepsAnUnderscoreFieldNothingReserves) {
+    json d = documentBody(json{{"_expires_at_display", "soon"},
+                               {"_internal_id", "mine"},
+                               {"expires_at", 7},
+                               {"name", "a"}});
+    EXPECT_EQ(d, (json{{"_expires_at_display", "soon"},
+                       {"_internal_id", "mine"},
+                       {"expires_at", 7},
+                       {"name", "a"}}));
+}

+ 141 - 0
tests/test_invoke_envelope.cpp

@@ -0,0 +1,141 @@
+// The invoke envelope: what `POST /functions/{id}/invoke` accepts, and the
+// trigger it synthesises.
+//
+// These are pure so the refusal can be paired with its own falsification. A
+// test that only asserts "a bad envelope is refused" would pass just as well
+// against a route that refused EVERYTHING, and a route refusing everything is
+// a worse defect than the one being fixed - so the pairing below asserting
+// that a correct `{"body":{...}}` still reaches `ctx.body` is not a courtesy
+// test, it is the one that gives the others meaning.
+#include <gtest/gtest.h>
+
+#include "functions/invoke_envelope.hpp"
+
+using svapi::ApiError;
+using svapi::ErrCode;
+using svapi::functions::manualTrigger;
+using svapi::functions::requireInvokeEnvelope;
+using nlohmann::json;
+
+namespace {
+
+struct Refusal { ErrCode code; std::string slug; std::string message; };
+
+// The refusal, or nullopt when the envelope was accepted.
+std::optional<Refusal> refusalFor(const json& body) {
+    try {
+        requireInvokeEnvelope(body);
+    } catch (const ApiError& e) {
+        return Refusal{e.code, e.slug, e.what()};
+    }
+    return std::nullopt;
+}
+
+}  // namespace
+
+// THE DEFECT, in the shape it was reported. A caller posting the payload at the
+// top level got a 200 and a run that had used an EMPTY body - so the answer
+// looked like a success and described a different input than the one asked for.
+TEST(InvokeEnvelope, RefusesABarePayload) {
+    const auto r = refusalFor(json{{"day", "2026-10-12"}});
+    ASSERT_TRUE(r.has_value());
+    EXPECT_EQ(r->code, ErrCode::Unprocessable);
+    EXPECT_EQ(r->slug, "unknown_option");
+    // Names the offending key AND where a payload belongs: the caller's next
+    // action is to move it, not to delete it.
+    EXPECT_NE(r->message.find("'day'"), std::string::npos) << r->message;
+    EXPECT_NE(r->message.find("'body'"), std::string::npos) << r->message;
+}
+
+// The second reported shape. `json` is a plausible name for "here is my JSON",
+// which is exactly the kind of key that used to be swallowed.
+TEST(InvokeEnvelope, RefusesAWrapperKeyThatIsNotBody) {
+    const auto r = refusalFor(json{{"json", {{"day", "2026-10-12"}}}});
+    ASSERT_TRUE(r.has_value());
+    EXPECT_EQ(r->slug, "unknown_option");
+    EXPECT_NE(r->message.find("'json'"), std::string::npos) << r->message;
+}
+
+// The third. A bare JSON string is the same mistake in a different costume, and
+// it gets the same slug rather than a second one to look up.
+TEST(InvokeEnvelope, RefusesANonObjectBody) {
+    for (const json body : {json("2026-10-12"), json::array({1, 2}), json(7), json(true)}) {
+        const auto r = refusalFor(body);
+        ASSERT_TRUE(r.has_value()) << body.dump();
+        EXPECT_EQ(r->slug, "unknown_option") << body.dump();
+        EXPECT_NE(r->message.find("'body'"), std::string::npos) << r->message;
+    }
+}
+
+// Every unknown key at once, not just the first: a caller fixing one and
+// meeting the same error learns nothing about how many are left.
+TEST(InvokeEnvelope, NamesEveryUnknownKeyAndListsTheAcceptedSet) {
+    const auto r = refusalFor(json{{"day", 1}, {"body", json::object()}, {"dryRun", true}});
+    ASSERT_TRUE(r.has_value());
+    EXPECT_NE(r->message.find("'day'"), std::string::npos) << r->message;
+    EXPECT_NE(r->message.find("'dryRun'"), std::string::npos) << r->message;
+    for (const char* accepted : {"method", "path", "params", "query", "headers", "body"})
+        EXPECT_NE(r->message.find(accepted), std::string::npos) << accepted << ": " << r->message;
+}
+
+// THE PAIRING THAT GIVES THE REFUSALS ABOVE THEIR MEANING: a correct envelope
+// is accepted AND its payload actually arrives. Deliberately falsified while
+// writing it - adding "day" to `kInvokeEnvelopeKeys` turns the three refusal
+// tests red while this one stays green, which is how we know the two halves
+// test different things rather than one shadowing the other.
+TEST(InvokeEnvelope, AcceptsTheDocumentedEnvelopeAndCarriesTheBodyThrough) {
+    const json body = {{"body", {{"day", "2026-10-12"}}}};
+    EXPECT_FALSE(refusalFor(body).has_value());
+
+    const json t = manualTrigger("/report", body);
+    // The payload reaches the trigger's `body`, which is what becomes ctx.body.
+    EXPECT_EQ(t["body"], (json{{"day", "2026-10-12"}}));
+    // And the defaults still produce a usable request.
+    EXPECT_EQ(t["method"], "POST");
+    EXPECT_EQ(t["path"], "/report");
+    EXPECT_TRUE(t["params"].is_object());
+    EXPECT_TRUE(t["query"].is_object());
+    EXPECT_TRUE(t["headers"].is_object());
+}
+
+// An empty envelope stays legal: "does it still run?" is the commonest invoke
+// and must not need a payload. personal-assistant-48 verified exactly this
+// shape and `{"body":{...}}` against their 18 live functions before the change.
+TEST(InvokeEnvelope, AcceptsAnEmptyEnvelope) {
+    EXPECT_FALSE(refusalFor(json::object()).has_value());
+    const json t = manualTrigger("/cron", json::object());
+    EXPECT_EQ(t["method"], "POST");
+    EXPECT_EQ(t["path"], "/cron");
+    // Null rather than an empty object: the function was given no body, and
+    // saying so is different from saying it was given an empty one.
+    EXPECT_TRUE(t["body"].is_null());
+}
+
+// Every documented key is honoured rather than merely tolerated - the other
+// half of "accepted" that a refusal test cannot see. A key that passes the
+// filter and is then dropped by the builder is the original defect again, one
+// layer in.
+TEST(InvokeEnvelope, EveryAcceptedKeyReachesTheTrigger) {
+    const json t = manualTrigger("/declared", json{{"method", "GET"},
+                                                   {"path", "/override"},
+                                                   {"params", {{"id", "7"}}},
+                                                   {"query", {{"q", "x"}}},
+                                                   {"headers", {{"x-test", "1"}}},
+                                                   {"body", {{"n", 1}}}});
+    EXPECT_EQ(t["method"], "GET");
+    EXPECT_EQ(t["path"], "/override");  // the caller's path wins over the descriptor's
+    EXPECT_EQ(t["params"], (json{{"id", "7"}}));
+    EXPECT_EQ(t["query"], (json{{"q", "x"}}));
+    EXPECT_EQ(t["headers"], (json{{"x-test", "1"}}));
+    EXPECT_EQ(t["body"], (json{{"n", 1}}));
+}
+
+// A wrong TYPE on a known key falls back to the default rather than throwing,
+// which is the behaviour that shipped and is deliberately left alone here: the
+// fix is about keys nobody reads, not about retyping a field. Pinned so the
+// next person to touch this sees it was a decision.
+TEST(InvokeEnvelope, AKnownKeyOfTheWrongTypeFallsBackRatherThanThrowing) {
+    EXPECT_FALSE(refusalFor(json{{"params", "not-an-object"}}).has_value());
+    const json t = manualTrigger("/r", json{{"params", "not-an-object"}});
+    EXPECT_EQ(t["params"], json::object());
+}