Răsfoiți Sursa

fix(search): refuse an unknown option instead of silently ignoring it

Measured on prod, every one of these answered 200:

    top_k: 3     -> 3 rows   (correct)
    topK: 3      -> 5 rows   the DEFAULT, for a caller who asked for three
    minScore: .99-> rows     where the correct min_score: .99 returns none
    filter: [..] -> rows     the caller meant to EXCLUDE

The third is why this is a defect rather than an ergonomic wish. A filter
is frequently a tenancy or confidentiality boundary in the caller's
mind, and silently dropping it returns exactly the data they intended to
keep out, with a success status.

Now 422 `unknown_option`, naming every unrecognised key at once - a
caller who fixes one typo and gets the same error again learns nothing
about how many are left - and listing the accepted set, because the
usual cause is a plausible spelling of a real option rather than an
invented one.

Matching is exact and case-sensitive deliberately: 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 refuse an unknown option by
name. This brings the HTTP surface in line rather than inventing a
policy, and closes the last place in the service that still accepted
an option and did nothing with it - the same failure embedTimeoutMs had
for a whole release.

NOTE this is a behaviour change a consumer could hit: a body carrying a
stray key gets 422 where it used to get 200. Asking the consumers
whether any of them send extra keys before this ships; it is queued
behind the database release anyway.

Also records a review of both upstream pins against what this service
actually reaches:
- curl 8.23.0 (2026-10-14) fixes 22 CVEs including CVE-2026-92392 rated
  HIGH, embargoed until release, so a bump is required and cannot be
  judged in advance. Two disclosed ones are outside our build: the proxy
  credential leak needs PROXY, which is compiled out, and the pinning
  one needs peer verification disabled, which it never is.
- cpp-httplib 0.60.0/0.60.1 exist and NONE of their security fixes are
  our exposure - Mbed TLS, redirects, WebSockets and SSE, all either
  unused or disabled here. The 0.59.0 pin stays deliberately.

1231/1231 green.
fszontagh 1 lună în urmă
părinte
comite
feaf42fd31
7 a modificat fișierele cu 164 adăugiri și 1 ștergeri
  1. 4 0
      CLAUDE.md
  2. 1 0
      api/llms.txt
  3. 1 1
      api/openapi.json
  4. 66 0
      src/functions/known_keys.hpp
  5. 12 0
      src/handlers/vectors.cpp
  6. 5 0
      tests/CMakeLists.txt
  7. 75 0
      tests/test_known_keys.cpp

+ 4 - 0
CLAUDE.md

@@ -65,6 +65,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **Triggers:** `http` (a route), `cron` (a schedule, with an IANA `tz` validated against the host tz database at PUSH time - an unknown zone is refused, never silently UTC), `db` (an INSERT/UPDATE/DELETE on a watched collection) and `job` (reached only by being enqueued, which is where slow work belongs). The scheduler and the event watcher live in **vectorapi**, because there must be exactly one of each; N runners each firing every cron is the obvious bug.
 - **A blocking host call cannot be interrupted, so host timeouts ARE the enforcement.** The wall budget is enforced by a QuickJS interrupt handler that fires between bytecode ops; while an embedding or `ctx.fetch` request is in flight the engine never regains control, so the deadline is noticed only once the call returns. Bounding a host call therefore means handing the HTTP client timeouts that already fit the remaining budget - which is what `resolveEmbedBudget()` (`functions/embed_budget.hpp`, pure) does. It exists because a 10 s-budget run took **14314 ms**: the READ timeout was clamped to the budget and the CONNECT timeout was not, and the two are additive, so a connect stall burned the full `embedding_connect_timeout_sec` outside the budget. Connect gets at most HALF the available time (a reachable provider connects in well under a second, and a large connect allowance only starves the read phase). Below a 2 s budget the 1 s floor on each phase dominates and the worst case is 2 s - bounded, and stated rather than glossed over.
 - **Embedding timeouts are per-project and NARROWING ONLY**, resolved by the same `resolveEmbedding()` that picks the endpoint, so a project's override applies identically to a function and to an HTTP vector route. The effective value is `min(project, global)`: these govern a shared provider connection and a pooled runtime waiting on it, so an override that could RAISE them would let one tenant hold both longer than the operator allowed. A stored value above the global is kept rather than refused - it becomes effective if the global is later lowered. A zero override is "unset", never "no timeout", because 0 means no timeout to the HTTP client and that is precisely the unbounded call the split prevents.
+- **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.
 - **`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.
 - **Job runs draw from their OWN pool lane.** A lease is held for a run's whole duration, every `ctx.fetch` included, so without a lane N slow jobs leave one runtime for every interactive route and the second overlapping HTTP run blocks until the read timeout fires - a 503 from a healthy runner. Worst-case memory is `(pool + job_pool) x memory_limit_bytes`, so the two lanes ADD.
@@ -152,6 +153,9 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **The dev host's clang and the release GCC disagree about overload ambiguity, and the release toolchain is the only one that counts.** A braced list passed to `imapUidFetch` is viable for BOTH overloads - `{7, 9}` is either the set `7,9` or the single range `7:9`, and `{uid}` is either one uid or the range `uid:0` - so the two readings are DIFFERENT COMMANDS. clang silently picks one, GCC refuses the call, and the whole mail surface therefore compiled cleanly on the host for days and then failed the first release build it ever saw. Call such an overload set with an explicit vector type. The lesson is bigger than the call: `scripts/host-build.sh` passing is not evidence that the `.deb` will build, so a feature is not finished until the Docker path has compiled it.
 - **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.
+  - **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.
 - systemd unit is `Type=notify`; the binary must be built with `libsystemd` (it is, when `libsystemd-dev` is present) or change to `Type=exec`.

+ 1 - 0
api/llms.txt

@@ -234,6 +234,7 @@ export default async function (ctx) {
 - `ctx.collections(name)` - a chainable builder. `.filter('field:op:value')`, `.limit(n)`, `.offset(n)`, `.sort('field')` or `.sort('-field')` for descending, then a terminal: `.find()` returns an **array**, `.get(id)` returns the document or **null**, `.insert(doc)` returns `{id}`, `.update(id, doc)` returns `{id}`, `.patch(id, fields)` returns `{id, version}`, `.increment(id, {field: n})` returns the **new values** object (the same atomic increment as the HTTP route, needing the `update` grant; a missing document throws), `.delete(id)` returns `{deleted}`. Filters use the same `field:op:value` grammar as `?filter=`, parsed by the same code and evaluated by the database, so a filter means the same thing here as over HTTP.
 - **Write options**, previously undocumented. `ttl_seconds` is accepted by `.insert()`, `.update()`, `.patch()` and `.store()`; it sets or clears a document's expiry, and **absent is not zero** - omitting it leaves an existing expiry untouched while `0` clears it, so a plain `.patch()` cannot accidentally make a temporary document permanent. **`ifVersion: n`** makes the write conditional on the document still being at version `n` (as returned in `_version`); a lost race is **409** `version_conflict` carrying `current_version`, which means "someone else has it" and should be handled by dropping the work or re-reading, never by retrying the same write. `ifVersion` must be a positive integer - version 0 does not exist, since a first write produces 1. It is accepted by **`.update()` and `.patch()` only**: `.insert()` refuses it by name, because there is no existing version for a document that does not yet exist. `ttl_seconds` together with `ifVersion` is refused (`unsupported_combination`) rather than silently dropping one. A conditional `.update()` returns `{id, version}`; the unconditional form returns `{id}`.
 - Vector collections additionally take `.search({query_text|query_vector, top_k, min_score, filters, embedTimeoutMs?})`, returning an **array** of hits, and `.store({text|vector, metadata, embedTimeoutMs?})`. Embedding resolves through the normal precedence, so a project's provider override applies.
+- **An UNKNOWN option on a vector `/search` body is now refused with 422 `unknown_option`, naming every unrecognised key.** It used to be accepted and ignored, which produced silently wrong answers rather than errors. Measured on prod before the fix: `topK: 3` (the camelCase misspelling) returned **five** rows, the default, so a caller asking for three got five and was told nothing; `minScore: 0.99` returned rows where the correct `min_score: 0.99` returns none; and **`filter:` in the singular returned the rows the caller meant to EXCLUDE**. The accepted set is `query_text`, `query_vector`, `top_k`, `min_score`, `filters`, `embedTimeoutMs`. Matching is exact and case-sensitive, so `Top_K` is refused rather than quietly accepted as a second spelling.
 - **`embedTimeoutMs` bounds the whole embedding call, connect phase included**, and is narrowing only - it cannot exceed what is left of the run's budget. It applies identically to `.search()` and `.store()`: both resolve their vector through the same code, so there is no asymmetry between them. Exceeding it is **504** `embedding_timeout`. A non-integer or non-positive value is **422**: it is validated rather than ignored, because an option that is accepted and does nothing is worse than one that is refused.
 - **Its RESOLUTION IS ONE SECOND, and the effective floor is 1 s per phase.** The HTTP client underneath takes whole seconds and treats 0 as "no timeout", so every value below 1000 ms resolves to the same thing: 1 s to connect plus 1 s to read. `embedTimeoutMs: 1` therefore allows up to **2 s**, not 1 ms, and a provider that answers inside that second succeeds normally - which reads exactly like the option being ignored. It is not: a value of 1 and a value of 999 are genuinely indistinguishable, and tuning inside that range does nothing. Ask for **2000 or more** if you want the split to be meaningful, and expect a timeout to surface at a whole-second boundary rather than at the millisecond you named. Connect never takes more than HALF the available time, so a 4000 ms ask becomes roughly 2 s connect + 2 s read.
 - **A blocking host call cannot be interrupted.** The run's wall budget is enforced between bytecode operations, so while an embedding or `ctx.fetch` request is in flight the deadline cannot be noticed - the budget ends the run once the call returns. Host calls are bounded by giving them timeouts that already fit the remaining budget (connect **and** read together), not by preemption. For a hard latency ceiling, catch the error and have a fallback path.

+ 1 - 1
api/openapi.json

@@ -2688,7 +2688,7 @@
             "description": "Collection not found"
           },
           "422": {
-            "description": "Validation error"
+            "description": "Unknown option in the body (`unknown_option`), a missing query_text/query_vector, or a dimension mismatch. An unrecognised key is REFUSED rather than ignored: a misspelled `filters` previously returned the rows the caller meant to exclude, with a 200."
           },
           "429": {
             "description": "Too Many Requests (rate-limited scoped key)"

+ 66 - 0
src/functions/known_keys.hpp

@@ -0,0 +1,66 @@
+#pragma once
+
+#include <nlohmann/json.hpp>
+
+#include <initializer_list>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace svapi::functions {
+
+/// The unknown keys in `body`, in the order they appear.
+///
+/// Pure, so the decision is testable without a request or a database.
+///
+/// This exists because an option that is accepted and silently does nothing is
+/// worse than one that is refused, and the HTTP vector routes were the last
+/// place in this service that still did the former. Measured on prod before
+/// the fix: `topK: 3` (the camelCase misspelling of `top_k`) answered 200 with
+/// FIVE rows - the default - so a caller asking for three got five and was
+/// told nothing; `minScore: 0.99` answered 200 with rows, where the correct
+/// `min_score: 0.99` returns none; and **`filter:` (singular) answered 200
+/// with the rows the caller meant to EXCLUDE.** That last one is the reason
+/// this is a defect rather than an ergonomic wish: a filter is frequently a
+/// tenancy or confidentiality boundary in the caller's mind, and silently
+/// dropping it returns data they intended to keep out.
+///
+/// `ctx.fetch`, `ctx.mail` and `ctx.jobs` already refuse an unknown option by
+/// name. This brings the HTTP surface in line rather than inventing a policy.
+inline std::vector<std::string> unknownKeys(const nlohmann::json& body,
+                                            std::initializer_list<std::string_view> known) {
+    std::vector<std::string> out;
+    if (!body.is_object()) return out;
+    for (auto it = body.begin(); it != body.end(); ++it) {
+        bool found = false;
+        for (const std::string_view k : known)
+            if (it.key() == k) { found = true; break; }
+        if (!found) out.push_back(it.key());
+    }
+    return out;
+}
+
+/// A message naming every unknown key and what was expected, for a 422.
+///
+/// Names them ALL rather than only the first: a caller fixing one typo and
+/// getting the same error again learns nothing about how many are left. And
+/// the accepted set is listed, because the commonest cause is a plausible
+/// spelling of a real option rather than an invented one.
+inline std::string unknownKeyMessage(const std::vector<std::string>& unknown,
+                                     std::initializer_list<std::string_view> known) {
+    std::string msg = unknown.size() == 1 ? "unknown option '" : "unknown options '";
+    for (std::size_t i = 0; i < unknown.size(); ++i) {
+        if (i > 0) msg += i + 1 == unknown.size() ? "' and '" : "', '";
+        msg += unknown[i];
+    }
+    msg += "'; accepted: ";
+    bool first = true;
+    for (const std::string_view k : known) {
+        if (!first) msg += ", ";
+        msg.append(k);
+        first = false;
+    }
+    return msg;
+}
+
+}  // namespace svapi::functions

+ 12 - 0
src/handlers/vectors.cpp

@@ -7,6 +7,7 @@
 #include "project_settings.hpp"
 #include "json_http.hpp"
 #include "server.hpp"
+#include "functions/known_keys.hpp"
 #include "vector_search.hpp"
 #include <algorithm>
 namespace svapi {
@@ -110,6 +111,17 @@ void registerVectorRoutes(ApiServer& s) {
         std::string project, name; CollectionMeta meta = requireVectorCollection(d, req, project, name, KeyOp::Search);
         auto body = bodyJson(req);
         std::vector<float> q = resolveVector(d, project, meta, body, "query_vector", "query_text", wantsNoStore(req));
+        // Refuse an unknown key rather than ignore it. Measured on prod before
+        // this existed: `topK` answered 200 with the DEFAULT five rows, and
+        // `filter` (singular) answered 200 with the rows the caller meant to
+        // exclude. A dropped filter is the dangerous one - it is often a
+        // tenancy boundary in the caller's mind.
+        static constexpr std::initializer_list<std::string_view> kSearchKeys = {
+            "query_text", "query_vector", "top_k", "min_score", "filters", "embedTimeoutMs"};
+        if (const auto unknown = functions::unknownKeys(body, kSearchKeys); !unknown.empty())
+            throw ApiError(ErrCode::Unprocessable, "unknown_option",
+                           functions::unknownKeyMessage(unknown, kSearchKeys));
+
         uint32_t topK = body.value("top_k", 5u);
         float minScore = body.value("min_score", 0.0f);
         auto filters = parseSearchFilters(body);

+ 5 - 0
tests/CMakeLists.txt

@@ -253,6 +253,11 @@ target_include_directories(test_header_fields PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_header_fields PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_header_fields)
 
+add_executable(test_known_keys test_known_keys.cpp)
+target_include_directories(test_known_keys PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_known_keys PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_known_keys)
+
 add_executable(test_vector_scan test_vector_scan.cpp)
 target_include_directories(test_vector_scan PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_vector_scan PRIVATE vectorapi_core GTest::gtest_main)

+ 75 - 0
tests/test_known_keys.cpp

@@ -0,0 +1,75 @@
+#include <gtest/gtest.h>
+
+#include <nlohmann/json.hpp>
+
+#include "functions/known_keys.hpp"
+
+using svapi::functions::unknownKeyMessage;
+using svapi::functions::unknownKeys;
+
+namespace {
+constexpr std::initializer_list<std::string_view> kSearch = {
+    "query_text", "query_vector", "top_k", "min_score", "filters", "embedTimeoutMs"};
+}
+
+TEST(KnownKeys, AValidBodyHasNoUnknownKeys) {
+    const nlohmann::json body = {{"query_text", "x"}, {"top_k", 3}, {"min_score", 0.5}};
+    EXPECT_TRUE(unknownKeys(body, kSearch).empty());
+}
+
+TEST(KnownKeys, THEThreeMisspellingsMEASUREDOnProd) {
+    // Each of these answered 200 before the fix, and each was wrong in its own
+    // way: topK gave the DEFAULT five rows for a caller asking three, minScore
+    // dropped a quality threshold, and `filter` returned the rows the caller
+    // meant to exclude.
+    EXPECT_EQ(unknownKeys({{"query_text", "x"}, {"topK", 3}}, kSearch),
+              std::vector<std::string>{"topK"});
+    EXPECT_EQ(unknownKeys({{"query_text", "x"}, {"minScore", 0.99}}, kSearch),
+              std::vector<std::string>{"minScore"});
+    EXPECT_EQ(unknownKeys({{"query_text", "x"}, {"filter", nlohmann::json::array()}}, kSearch),
+              std::vector<std::string>{"filter"});
+}
+
+TEST(KnownKeys, EVERYUnknownKeyIsNamedNotJustTheFirst) {
+    // A caller who fixes one typo and gets the same error again learns nothing
+    // about how many are left.
+    const nlohmann::json body = {{"query_text", "x"}, {"topK", 1}, {"minScore", 2}, {"rerank", true}};
+    const auto unknown = unknownKeys(body, kSearch);
+    EXPECT_EQ(unknown.size(), 3u);
+    const std::string msg = unknownKeyMessage(unknown, kSearch);
+    for (const char* k : {"topK", "minScore", "rerank"})
+        EXPECT_NE(msg.find(k), std::string::npos) << msg;
+    // And the accepted set is listed, because the usual cause is a plausible
+    // spelling of a real option rather than an invented one.
+    EXPECT_NE(msg.find("top_k"), std::string::npos) << msg;
+    EXPECT_NE(msg.find("min_score"), std::string::npos) << msg;
+}
+
+TEST(KnownKeys, TheMessageReadsCorrectlyForOneAndForMany) {
+    EXPECT_NE(unknownKeyMessage({"topK"}, kSearch).find("unknown option 'topK'"),
+              std::string::npos);
+    const std::string two = unknownKeyMessage({"a", "b"}, kSearch);
+    EXPECT_NE(two.find("unknown options 'a' and 'b'"), std::string::npos) << two;
+    const std::string three = unknownKeyMessage({"a", "b", "c"}, kSearch);
+    EXPECT_NE(three.find("'a', 'b' and 'c'"), std::string::npos) << three;
+}
+
+TEST(KnownKeys, ANonObjectBodyIsNotAnUnknownKeyProblem) {
+    // It has its own error elsewhere; this must not turn an array body into a
+    // confusing list of "unknown keys".
+    EXPECT_TRUE(unknownKeys(nlohmann::json::array({1, 2}), kSearch).empty());
+    EXPECT_TRUE(unknownKeys(nlohmann::json(nullptr), kSearch).empty());
+    EXPECT_TRUE(unknownKeys(nlohmann::json("a string"), kSearch).empty());
+}
+
+TEST(KnownKeys, MatchingIsExactAndCaseSensitive) {
+    // `Top_K` is not `top_k`. Accepting case variants would mean the service
+    // has two spellings for one option, which is how the next drift starts.
+    EXPECT_FALSE(unknownKeys({{"Top_K", 1}}, kSearch).empty());
+    EXPECT_FALSE(unknownKeys({{"TOP_K", 1}}, kSearch).empty());
+    EXPECT_TRUE(unknownKeys({{"top_k", 1}}, kSearch).empty());
+}
+
+TEST(KnownKeys, AnEmptyBodyIsFine) {
+    EXPECT_TRUE(unknownKeys(nlohmann::json::object(), kSearch).empty());
+}