Parcourir la source

fix(fn): offer a binary request body as base64 instead of a 500

nlohmann::json stores invalid UTF-8 in a string without complaint and
throws type_error.316 only when the value is serialised. A binary body
POSTed to /fn/* therefore travelled all the way into the run request and
blew up at dump(), which reached the caller as a 500 with nothing
pointing at the body - and the function never ran at all.

Measured: `{"body": "\x89PNG\r\n\x1a\n"}` stores 8 bytes happily and
then dump() throws `invalid UTF-8 byte at index 0: 0x89`.

Bytes that cannot be serialised are now offered as base64 under their
OWN keys: `body` stays null, `bodyBase64` carries them, `bodyEncoding`
is "base64". NOT base64 inside `body`, deliberately - that would hand a
function which knows nothing of binary a plausible-looking string that
is not the body that was sent, and silent corruption is a worse outcome
than a visible null. `bodyEncoding` is absent for a text body, so the
trigger shape an existing function receives does not change.

The bytes decide, not the header: a body declared application/json that
cannot be a JSON string is still offered as base64.

isValidUtf8() has to agree with nlohmann's decoder rather than with a
reading of RFC 3629 - a sequence it accepted and nlohmann rejected would
move the 500 rather than remove it. So the tests cross-check it against
a real dump() over every single byte and all 65536 two-byte sequences,
which covers the whole overlong and truncated-sequence space, instead of
trusting either implementation alone.

The decision is pure and testable (functions/trigger_body.hpp): the
dispatch handler had no test coverage at all, and the helper was in an
anonymous namespace where nothing could reach it.

Requested by a consumer who had deprioritised it as non-blocking.
1178/1178 green.
fszontagh il y a 1 mois
Parent
commit
aa651c07e9

+ 1 - 0
CLAUDE.md

@@ -131,6 +131,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`Client::get` returns nullopt for BOTH "absent" and "transport failed"** - it throws only for PERMISSION_DENIED - so a registry lookup cannot tell them apart from the return value. Unhandled, that reaches a caller as 404 "no such collection" for a collection that exists, and a 404 is unretryable BY DESIGN for a careful client, because adding it to a retry set would retry every genuine absence. A consumer lost a 6-minute ingest of an 8 GB mailbox to exactly this. `CollectionRegistry::get` therefore **retries once** (a transient failure usually succeeds, and logs a warning saying so) and then asks `healthCheck()` before reporting absence, throwing **503** when the database is unreachable. Reported upstream too: the client should distinguish, the way it already does for a permission denial.
 - **A filtered vector search can return FEWER hits than match, and the response now says so.** The walk goes only `kVectorFilterScanCap` (10000) deep into the ranking, so on a larger collection a filter whose matches lie deeper is silently short - measured at 455 returned of 553 true matches on 12448 rows. `VectorSearchResult::scanCapped` is set ONLY when the walk hit the cap while still short of `topK` and the ranking was not exhausted, so a filter that merely matches fewer rows than `top_k` is correctly reported as complete rather than crying wolf. The HTTP route adds `scan_capped`/`scanned`; `ctx...search()` keeps its ARRAY return and warns in the run console instead.
 - **Database failures keep their classification** (`db_errors.hpp`, client 2.11.4). `Client::Error::code()` on the throwing calls and the `Failure&` overloads on `update`/`patch`/`remove` feed one `translate()`: AlreadyExists → 409 `duplicate_values`, or `duplicate_id` when `reason` says so (database 2.12.1: a taken document id and a taken unique field value are the same code but different remedies), FailedPrecondition → 422 `relation_violation`, NotFound → 404, Unavailable/DeadlineExceeded/Unknown → 503, everything else → 500. **`ErrorCode::Ok` on a call that returned false means "did not apply", not an error** - map it to 404, or a plain missing document becomes a 500 with an empty message.
+- **`nlohmann::json` STORES invalid UTF-8 and throws only when you serialise it.** A binary `/fn` request body therefore reached the run request intact and blew up at `dump()` with `type_error.316`, which surfaced as a **500 with nothing pointing at the body** while the function never ran. `triggerBodyFields()` (`functions/trigger_body.hpp`, pure) now offers unserialisable bytes as base64 under their OWN keys - `body` stays `null`, `bodyBase64` carries them, `bodyEncoding` is `"base64"` - because base64 placed in `body` would hand an unprepared function a plausible-looking string that is not what was sent, and silent corruption is worse than a visible `null`. `bodyEncoding` is absent for a text body, so an existing function's trigger shape is unchanged. **`isValidUtf8()` (`utf8_text.hpp`) must agree with nlohmann's own decoder, not with a reading of RFC 3629** - a sequence it accepted and nlohmann rejected would only move the 500 - so it refuses overlongs, the surrogate range and anything past U+10FFFF, and the tests cross-check it against a real `dump()` over every single byte and all 65536 two-byte sequences rather than trusting either side alone.
 - **Document write bodies accept two shapes, via one reader.** `documentBody()` in `handlers/documents.cpp` is used by POST, PUT and PATCH: it unwraps `{"data":{...}}`, strips `id` (the document's identity, from the body on POST and from the URL on PUT/PATCH), and rejects `data` alongside any other top-level key with **422** `ambiguous_body`. Before 0.3.3 only POST unwrapped, so a `{"data":...}` PUT stored the wrapper as a literal field and a `data`-plus-siblings POST dropped the siblings silently. A literal top-level `data` field is still writable as `{"data":{"data":...}}`.
 - **QuickJS is pinned to an exact quickjs-ng tag** (`SVAPI_QUICKJS_TAG`, `runner/CMakeLists.txt`). QuickJS bytecode carries **no version stamp**, so a silent upgrade makes a cached blob *misread* rather than fail. quickjs-ng, not Bellard's tree: the module/promise/stack entry points the core needs (`JS_GetModuleNamespace`, `JS_PromiseState`, `JS_SetMaxStackSize`, `JS_IsJobPending`) are public API there. `JsBytecode` is an in-process cache only - never persist it without a QuickJS build fingerprint.
 - **QuickJS's job queue belongs to the `JSRuntime`, not the `JSContext`.** A fresh context per run is therefore *not* enough to isolate tenants: a run that times out mid-microtask leaves its jobs queued, and they would execute inside the next tenant's run. The core flushes them with the deadline forced into the past and marks the runtime `poisoned()` if anything survives; the pool destroys a poisoned runtime instead of leasing it out. An OOM poisons it too.

+ 2 - 0
api/llms.txt

@@ -228,6 +228,8 @@ export default async function (ctx) {
 
 `ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
 
+- **A BINARY request body arrives as base64, not in `ctx.body`.** When the bytes are not valid UTF-8 - an image, a PDF, a protobuf - `ctx.body` is **`null`**, `ctx.bodyBase64` carries the bytes and `ctx.bodyEncoding` is `"base64"`. They go under their own keys rather than into `ctx.body` on purpose: base64 in `ctx.body` would hand a function that knows nothing of binary a plausible-looking string that is not the body that was sent, and silent corruption is worse than an obvious `null`. `ctx.bodyEncoding` is **absent** for a text body, so a function written before this behaves exactly as it did. Note the bytes decide and the content type does not: a body declared `application/json` that cannot be a JSON string is still offered as base64.
+
 - `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.

+ 68 - 0
src/functions/trigger_body.hpp

@@ -0,0 +1,68 @@
+#pragma once
+
+#include <nlohmann/json.hpp>
+
+#include <string>
+#include <string_view>
+
+#include "functions/mime_base64.hpp"
+#include "utf8_text.hpp"
+
+namespace svapi::functions {
+
+/// The body fields of an HTTP trigger: `body`, plus `bodyBase64` and
+/// `bodyEncoding` when the bytes cannot live in a JSON string.
+///
+/// Pure, and separated from the dispatch handler for the usual reason in this
+/// codebase: the decision is worth testing on its own, and it needs neither an
+/// `httplib::Request` nor a runner to make.
+///
+/// JSON when the request says JSON and it parses, the raw string otherwise,
+/// null when there is no body. A parse failure is NOT an error: the function
+/// may legitimately accept text with a wrong content type, and guessing on its
+/// behalf would make `/fn/*` stricter than the function it fronts.
+///
+/// BINARY is the case this exists for. `nlohmann::json` stores arbitrary bytes
+/// in a string without complaint and then throws `type_error.316` when the
+/// value is serialised, so a request body that was not valid UTF-8 travelled
+/// into the run request intact and blew up at `dump()`. The caller got a 500
+/// with nothing pointing at the body, and the function never ran at all.
+///
+/// Bytes that cannot be serialised are therefore offered as base64 under their
+/// OWN key, never in `body`. Putting base64 in `body` would hand every existing
+/// function a plausible-looking string that is not the body it asked for, which
+/// is silent corruption in place of a loud failure - the wrong trade. A script
+/// that knows nothing of binary sees `body: null` and can say so; one that
+/// wants the bytes reads `bodyBase64`. `bodyEncoding` is ABSENT for a text
+/// body, so the shape an existing function already receives is unchanged.
+inline nlohmann::json triggerBodyFields(std::string_view body, std::string_view contentType) {
+    nlohmann::json out = nlohmann::json::object();
+    if (body.empty()) {
+        out["body"] = nullptr;
+        return out;
+    }
+    if (!isValidUtf8(body)) {
+        // The bytes decide, not the header: a content type claiming JSON over
+        // bytes that cannot be a JSON string is simply wrong.
+        out["body"] = nullptr;
+        out["bodyBase64"] = mimeBase64Encode(std::string(body));
+        out["bodyEncoding"] = "base64";
+        return out;
+    }
+    std::string lowered;
+    lowered.reserve(contentType.size());
+    for (const char c : contentType)
+        lowered.push_back(static_cast<char>(::tolower(static_cast<unsigned char>(c))));
+    if (lowered.find("json") != std::string::npos) {
+        try {
+            out["body"] = nlohmann::json::parse(body);
+            return out;
+        } catch (const std::exception&) {
+            // fall through to the raw string
+        }
+    }
+    out["body"] = std::string(body);
+    return out;
+}
+
+}  // namespace svapi::functions

+ 12 - 21
src/handlers/function_dispatch.cpp

@@ -9,6 +9,7 @@
 // Because it is public, everything below treats the request path as hostile.
 #include "auth.hpp"
 #include "errors.hpp"
+#include "functions/trigger_body.hpp"
 #include "functions/descriptor.hpp"
 #include "json_http.hpp"
 #include "server.hpp"
@@ -152,21 +153,11 @@ nlohmann::json queryJson(const httplib::Request& req) {
     return out;
 }
 
-/// JSON when the request says JSON and it parses, the raw string otherwise,
-/// null when there is no body. A parse failure is NOT a 400: the function may
-/// legitimately accept text with a wrong content type, and guessing on its
-/// behalf would make /fn/* stricter than the function it fronts.
-nlohmann::json triggerBody(const httplib::Request& req) {
-    if (req.body.empty()) return nullptr;
-    const std::string ct = lowerCase(req.get_header_value("Content-Type"));
-    if (ct.find("json") != std::string::npos) {
-        try {
-            return nlohmann::json::parse(req.body);
-        } catch (const std::exception&) {
-            // fall through to the raw string
-        }
-    }
-    return req.body;
+/// The body fields of a trigger. The decision itself is pure and lives in
+/// `functions/trigger_body.hpp`, which is also where its reasoning is recorded;
+/// this only unwraps the httplib request.
+void applyTriggerBody(nlohmann::json& t, const httplib::Request& req) {
+    t.update(functions::triggerBodyFields(req.body, req.get_header_value("Content-Type")));
 }
 
 nlohmann::json routeParamsJson(const functions::RouteParams& params) {
@@ -297,12 +288,12 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
         return;
     }
 
-    const nlohmann::json trigger{{"method", req.method},
-                                 {"path", path},
-                                 {"params", routeParamsJson(match.params)},
-                                 {"query", queryJson(req)},
-                                 {"headers", headerJson(req)},
-                                 {"body", triggerBody(req)}};
+    nlohmann::json trigger{{"method", req.method},
+                           {"path", path},
+                           {"params", routeParamsJson(match.params)},
+                           {"query", queryJson(req)},
+                           {"headers", headerJson(req)}};
+    applyTriggerBody(trigger, req);
 
     const RunnerRunResult r = d.runners->run(project, functionId, trigger);
 

+ 74 - 0
src/utf8_text.hpp

@@ -0,0 +1,74 @@
+#pragma once
+
+#include <cstddef>
+#include <string_view>
+
+namespace svapi {
+
+/// True when `bytes` is well-formed UTF-8 as RFC 3629 defines it.
+///
+/// This exists because `nlohmann::json` STORES arbitrary bytes in a string
+/// happily and then throws `type_error.316` when the value is serialised. A
+/// binary request body therefore travelled all the way into the run request and
+/// blew up at `dump()`, which surfaced to the caller as a 500 with no clue that
+/// the body was the cause.
+///
+/// It must agree with nlohmann's own decoder, not merely with a loose reading
+/// of the spec: a byte sequence this accepts and nlohmann rejects would move
+/// the 500 rather than remove it. So overlong encodings, the UTF-16 surrogate
+/// range and anything above U+10FFFF are all refused here, and a test
+/// cross-checks this function against an actual `dump()` over the awkward
+/// cases rather than trusting either implementation alone.
+///
+/// A NUL byte is VALID: it is legal UTF-8, `dump()` escapes it as `\u0000`, and
+/// a JS string holds it without trouble. Rejecting it would refuse bodies that
+/// work today.
+inline bool isValidUtf8(std::string_view bytes) {
+    const auto* p = reinterpret_cast<const unsigned char*>(bytes.data());
+    const std::size_t n = bytes.size();
+    std::size_t i = 0;
+    while (i < n) {
+        const unsigned char c = p[i];
+        std::size_t extra = 0;
+        unsigned char lo = 0x80;  // the allowed range of the FIRST continuation
+        unsigned char hi = 0xBF;  // byte, which is what rules out overlongs
+                                  // and surrogates
+        if (c <= 0x7F) {
+            i += 1;
+            continue;
+        } else if (c >= 0xC2 && c <= 0xDF) {
+            extra = 1;
+        } else if (c == 0xE0) {
+            extra = 2;
+            lo = 0xA0;  // below this the value fits in two bytes: overlong
+        } else if (c >= 0xE1 && c <= 0xEC) {
+            extra = 2;
+        } else if (c == 0xED) {
+            extra = 2;
+            hi = 0x9F;  // above this is the UTF-16 surrogate range
+        } else if (c >= 0xEE && c <= 0xEF) {
+            extra = 2;
+        } else if (c == 0xF0) {
+            extra = 3;
+            lo = 0x90;  // below this is overlong
+        } else if (c >= 0xF1 && c <= 0xF3) {
+            extra = 3;
+        } else if (c == 0xF4) {
+            extra = 3;
+            hi = 0x8F;  // above this is past U+10FFFF
+        } else {
+            // 0x80-0xC1 (a stray continuation, or an overlong two-byte lead)
+            // and 0xF5-0xFF (past the end of Unicode) are never a lead byte.
+            return false;
+        }
+
+        if (i + extra >= n) return false;  // truncated sequence
+        if (p[i + 1] < lo || p[i + 1] > hi) return false;
+        for (std::size_t k = 2; k <= extra; ++k)
+            if (p[i + k] < 0x80 || p[i + k] > 0xBF) return false;
+        i += extra + 1;
+    }
+    return true;
+}
+
+}  // namespace svapi

+ 12 - 0
tests/CMakeLists.txt

@@ -236,6 +236,18 @@ gtest_discover_tests(test_db_await)
 # Pure: no curl, no sockets, no mail server. The awkward cases - a literal
 # containing CRLF, parens, NUL - are exactly the ones a real server produces
 # and a line-based parser gets wrong.
+# Pure header, so it needs no library - but it DOES need nlohmann, because the
+# tests cross-check the validator against nlohmann's own dump().
+add_executable(test_utf8_text test_utf8_text.cpp)
+target_include_directories(test_utf8_text PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_utf8_text PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_utf8_text)
+
+add_executable(test_trigger_body test_trigger_body.cpp)
+target_include_directories(test_trigger_body PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_trigger_body PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_trigger_body)
+
 add_executable(test_imap_reader test_imap_reader.cpp)
 target_include_directories(test_imap_reader PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_imap_reader PRIVATE GTest::gtest_main)

+ 92 - 0
tests/test_trigger_body.cpp

@@ -0,0 +1,92 @@
+#include <gtest/gtest.h>
+
+#include <nlohmann/json.hpp>
+
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "functions/trigger_body.hpp"
+
+
+
+using svapi::functions::triggerBodyFields;
+
+TEST(TriggerBody, NoBodyIsNull) {
+    const nlohmann::json t = triggerBodyFields("", "");
+    EXPECT_TRUE(t.at("body").is_null());
+    EXPECT_FALSE(t.contains("bodyEncoding"));
+}
+
+TEST(TriggerBody, JsonIsParsedWhenTheContentTypeSaysSo) {
+    const nlohmann::json t = triggerBodyFields(R"({"a":1})", "application/json");
+    EXPECT_EQ(t.at("body").at("a"), 1);
+    EXPECT_FALSE(t.contains("bodyEncoding"));
+}
+
+TEST(TriggerBody, TheContentTypeMatchIsCaseInsensitive) {
+    const nlohmann::json t = triggerBodyFields(R"({"a":1})", "Application/JSON; charset=utf-8");
+    EXPECT_EQ(t.at("body").at("a"), 1);
+}
+
+TEST(TriggerBody, UnparseableJsonArrivesAsTheRawStringRatherThanAnError) {
+    // Deliberate: a function may accept text sent with the wrong content type,
+    // and refusing it here would make /fn/* stricter than the function.
+    const nlohmann::json t = triggerBodyFields("not json at all", "application/json");
+    EXPECT_EQ(t.at("body"), "not json at all");
+}
+
+TEST(TriggerBody, TextIsTheRawStringWithNoEncodingMarker) {
+    const nlohmann::json t = triggerBodyFields("hello", "text/plain");
+    EXPECT_EQ(t.at("body"), "hello");
+    // The shape an existing function receives must not change.
+    EXPECT_FALSE(t.contains("bodyBase64"));
+    EXPECT_FALSE(t.contains("bodyEncoding"));
+}
+
+TEST(TriggerBody, AccentedTextIsNotMistakenForBinary) {
+    // Valid UTF-8 multibyte text stays a string. Getting this wrong would send
+    // every Hungarian webhook body through base64.
+    const std::string hu = "\xc3\xa1rv\xc3\xadzt\xc5\xb1r\xc5\x91";
+    const nlohmann::json t = triggerBodyFields(hu, "text/plain");
+    EXPECT_EQ(t.at("body"), hu);
+    EXPECT_FALSE(t.contains("bodyEncoding"));
+}
+
+TEST(TriggerBody, BinaryIsOfferedAsBase64AndNeverInBody) {
+    const std::string png("\x89PNG\r\n\x1a\n\x00\xff", 10);
+    const nlohmann::json t = triggerBodyFields(png, "image/png");
+    // `body` must be NULL, not the base64: a function that has not been taught
+    // about binary must see "there is no text body", not a plausible-looking
+    // string that is not what was sent.
+    EXPECT_TRUE(t.at("body").is_null()) << t.dump();
+    EXPECT_EQ(t.at("bodyEncoding"), "base64");
+    EXPECT_EQ(svapi::functions::mimeBase64Decode(t.at("bodyBase64").get<std::string>()), png);
+}
+
+TEST(TriggerBody, BinaryClaimingToBeJsonIsStillBase64) {
+    // The bytes decide, not the header. A content type claiming JSON over
+    // bytes that cannot be a JSON string is simply wrong.
+    const std::string bytes("\xff\xfe{\"a\":1}", 10);
+    const nlohmann::json t = triggerBodyFields(bytes, "application/json");
+    EXPECT_TRUE(t.at("body").is_null());
+    EXPECT_EQ(t.at("bodyEncoding"), "base64");
+}
+
+TEST(TriggerBody, EveryShapeItProducesCanActuallyBeSerialised) {
+    // The whole point of the fix, asserted directly: the run request is built
+    // by dumping this object, and dumping it is what used to throw.
+    const std::vector<std::pair<std::string, std::string>> cases = {
+        {"", ""},
+        {"hello", "text/plain"},
+        {R"({"a":1})", "application/json"},
+        {std::string("\x89PNG\r\n\x1a\n", 8), "image/png"},
+        {std::string("\xff", 1), "application/json"},
+        {"\xc3\xa1rv\xc3\xadz", "text/plain"},
+    };
+    for (const auto& [body, ct] : cases) {
+        nlohmann::json trigger{{"method", "POST"}, {"path", "/x"}};
+        trigger.update(triggerBodyFields(body, ct));
+        EXPECT_NO_THROW({ (void)trigger.dump(); }) << "content-type " << ct;
+    }
+}

+ 104 - 0
tests/test_utf8_text.cpp

@@ -0,0 +1,104 @@
+#include <gtest/gtest.h>
+
+#include <nlohmann/json.hpp>
+
+#include "utf8_text.hpp"
+#include "functions/mime_base64.hpp"
+
+using svapi::isValidUtf8;
+
+namespace {
+
+/// nlohmann's OWN verdict on whether a byte string can be serialised.
+///
+/// The point of the cross-check: `isValidUtf8` exists to predict this, so the
+/// tests compare it against the real thing rather than against my reading of
+/// RFC 3629. If the two ever disagree, the 500 this guard removes would simply
+/// come back from a different line.
+bool nlohmannCanSerialise(const std::string& bytes) {
+    nlohmann::json j;
+    j["body"] = bytes;
+    try {
+        (void)j.dump();
+        return true;
+    } catch (const std::exception&) {
+        return false;
+    }
+}
+
+/// Every awkward case worth naming, good and bad together.
+const std::vector<std::pair<const char*, std::string>>& corpus() {
+    static const std::vector<std::pair<const char*, std::string>> c = {
+        // --- must be accepted
+        {"empty", ""},
+        {"ascii", "hello world"},
+        {"a NUL byte is legal UTF-8", std::string("a\0b", 3)},
+        {"hungarian", "\xc3\xa1rv\xc3\xadzt\xc5\xb1r\xc5\x91"},
+        {"two-byte lowest", "\xc2\x80"},
+        {"three-byte lowest", "\xe0\xa0\x80"},
+        {"four-byte lowest", "\xf0\x90\x80\x80"},
+        {"largest code point U+10FFFF", "\xf4\x8f\xbf\xbf"},
+        {"just below the surrogates", "\xed\x9f\xbf"},
+        {"just above the surrogates", "\xee\x80\x80"},
+        // --- must be refused
+        {"a PNG header", std::string("\x89PNG\r\n\x1a\n", 8)},
+        {"a lone continuation byte", "\x80"},
+        {"an overlong two-byte NUL", "\xc0\x80"},
+        {"an overlong C1", "\xc1\xbf"},
+        {"an overlong three-byte", "\xe0\x80\x80"},
+        {"an overlong four-byte", "\xf0\x80\x80\x80"},
+        {"a UTF-16 surrogate half", "\xed\xa0\x80"},
+        {"past U+10FFFF", "\xf4\x90\x80\x80"},
+        {"an F5 lead byte", "\xf5\x80\x80\x80"},
+        {"an FF byte", "\xff"},
+        {"a truncated two-byte", "\xc3"},
+        {"a truncated three-byte", "\xe0\xa0"},
+        {"a truncated four-byte", "\xf0\x90\x80"},
+        {"a good prefix then a bad byte", "ok then \xff"},
+    };
+    return c;
+}
+
+}  // namespace
+
+TEST(Utf8Text, AgreesWithNlohmannOnEveryAwkwardCase) {
+    // The cross-check, and the only test here that could catch my own
+    // misreading of the spec: two independent implementations, compared.
+    for (const auto& [name, bytes] : corpus())
+        EXPECT_EQ(isValidUtf8(bytes), nlohmannCanSerialise(bytes))
+            << name << " (" << bytes.size() << " bytes)";
+}
+
+TEST(Utf8Text, AgreesWithNlohmannOnEverySingleByte) {
+    // Exhaustive over one byte: a lead-byte table is easy to get wrong in one
+    // row, and a hand-picked list would not notice.
+    for (int b = 0; b <= 0xFF; ++b) {
+        const std::string one(1, static_cast<char>(b));
+        EXPECT_EQ(isValidUtf8(one), nlohmannCanSerialise(one)) << "byte 0x" << std::hex << b;
+    }
+}
+
+TEST(Utf8Text, AgreesWithNlohmannOnEveryTwoByteSequence) {
+    // Exhaustive over two bytes: 65536 cases, which covers the whole overlong
+    // and truncated-sequence space for the two-byte forms.
+    for (int a = 0; a <= 0xFF; ++a)
+        for (int b = 0; b <= 0xFF; ++b) {
+            std::string two;
+            two.push_back(static_cast<char>(a));
+            two.push_back(static_cast<char>(b));
+            ASSERT_EQ(isValidUtf8(two), nlohmannCanSerialise(two))
+                << "bytes 0x" << std::hex << a << " 0x" << b;
+        }
+}
+
+TEST(Utf8Text, ABinaryBodyRoundTripsThroughBase64) {
+    // The other half of the fix: what cannot go in a JSON string goes in as
+    // base64, and must come back byte-identical.
+    const std::string png("\x89PNG\r\n\x1a\n\x00\x01\xfe\xff", 12);
+    ASSERT_FALSE(isValidUtf8(png));
+    const std::string encoded = svapi::functions::mimeBase64Encode(png);
+    // The encoded form must itself be safe to serialise, or nothing was gained.
+    EXPECT_TRUE(isValidUtf8(encoded));
+    EXPECT_TRUE(nlohmannCanSerialise(encoded));
+    EXPECT_EQ(svapi::functions::mimeBase64Decode(encoded), png);
+}