Эх сурвалжийг харах

build: cpp-httplib v0.46.0 -> v0.59.0, and tell a fetch timeout from a fault

The library serving our public HTTP surface and every outbound call was 17
releases behind, with security fixes in most of them, and nobody had looked.

The pin now carries its reasoning, limited to fixes this service can actually
reach: `chunked` matched only as the whole Transfer-Encoding value (a
request-smuggling shape, and we sit behind nginx), an out-of-range
Content-Length cast to size_t and silently truncated, control characters
accepted in the chunk-size line, a Range first-byte-pos overflow that reaches
us because we serve static files, a static mount point compared as a byte
prefix rather than on a path-segment boundary, and the listen backlog going
from 5 to 128.

I led with the wrong reason and the comment records that: v0.53.1's stack
overflow in RegexMatcher::match() is real but was never reachable here.
CPPHTTPLIB_REQUEST_URI_MAX_LENGTH is 8192 in v0.46.0 too and is enforced
BEFORE routing, so a long path is answered 414 and never reaches the matcher.
Measured on both versions rather than read off a changelog: escalating paths up
to 2 MB against the unauthenticated /fn/ route return 414 with the server
still up.

Not v0.60.0: its security fix is Mbed TLS hostname verification and we build
against OpenSSL, and its bug fixes are redirect behaviour, which
applyOutboundDefaults() turns off. It was also released the same day.

Also here, from a consumer report of a 40% ctx.fetch failure rate they had
diagnosed as a stale keep-alive pool - which ctx.fetch does not have, since
every call builds its own client:

ctx.fetch sets connect, read and write timeouts to the run's REMAINING budget,
so a provider slower than that is cut off by US, and httplib words it as
"Failed to read connection" - indistinguishable from a network fault, which is
exactly why the diagnosis went wrong. Exceeding the budget is now 504
`fetch_timeout`, the message says how long the call took and how long it was
allowed, and it names the fix (raise timeoutMs, or move the work to a job
trigger). Their own run log confirmed it: "asked for 55000ms and was given
15000ms by the runner's wall-time ceiling".

A failed ctx.fetch also left NO operator trace - the same hole I fixed on the
embedding path earlier and not here - so a failing provider was visible only
to the tenant while the journal said nothing. It now warns with method, host,
elapsed, budget, project and function.

llms.txt gains the ctx.fetch options it never documented: `responseType:
'base64'` for a binary response (the consumer was using it undocumented),
`timeoutMs`, the no-pooling note, and that a binary REQUEST body is not
supported yet.

849/849 natively and 849/849 in the Debian container on v0.59.0.
fszontagh 1 сар өмнө
parent
commit
8d935880ee

+ 1 - 0
CLAUDE.md

@@ -113,6 +113,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **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.
 - **`/etc/smartbotic-vectorapi` must stay mode 0751, not 0750.** The runner runs as its own user and needs `+x` to traverse the directory to `runner.json`; it still cannot list it, and the server's `0640` files stay unreadable to it. Both `server.postinst` and `runner.postinst` set it, and a server upgrade resetting it to `0750` breaks the runner on its **next restart** - a failure that surfaces weeks later with no obvious cause.
 - **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`.
+- **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 and never reaches the regex matcher, so the headline regex stack-overflow fix was never our exposure, 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`.
 

+ 5 - 1
api/llms.txt

@@ -218,7 +218,11 @@ export default async function (ctx) {
 - 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.
 - **`embedTimeoutMs` bounds the whole embedding call, connect phase included**, and is narrowing only - it cannot exceed what is left of the run's budget. 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.
 - **A blocking host call cannot be interrupted.** The run's wall budget is enforced between bytecode operations, so while an embedding or `ctx.fetch` request is in flight the deadline cannot be noticed - the budget ends the run once the call returns. Host calls are bounded by giving them timeouts that already fit the remaining budget (connect **and** read together), not by preemption. For a hard latency ceiling, catch the error and have a fallback path.
-- `ctx.fetch(url, {method, headers, body})` - outbound HTTP, **SSRF-guarded**: loopback, private and link-local destinations are refused, which means a function cannot call this API back. The refusal is reported in the run's console rather than as a network error.
+- `ctx.fetch(url, {method, headers, body, timeoutMs, responseType})` - outbound HTTP, **SSRF-guarded**: loopback, private and link-local destinations are refused, which means a function cannot call this API back. The refusal is reported in the run's console rather than as a network error.
+- **`responseType: 'base64'` returns a BINARY response body** as base64. Needed for anything that is not text: the value handed to the engine is serialised as JSON, and a JSON string cannot hold a byte outside a valid UTF-8 sequence, so a non-text body is either base64 or it is refused. The refusal names this fix rather than surfacing a raw UTF-8 decode error.
+- **`timeoutMs` narrows the call, never widens it**, and is capped by what is left of the run's budget. There is no connection pooling: every call builds its own client, so there is no keep-alive socket to go stale.
+- **Exceeding the budget is 504 `fetch_timeout`, not `fetch_failed`.** The connect, read and write timeouts are set to the run's REMAINING budget, so a provider slower than that is cut off by us - and the underlying library words that as "Failed to read connection", which reads like a network fault. The error says how long the call took and how long it was allowed, so the two are distinguishable. A long provider call belongs on a **job** trigger, whose ceiling is far higher than an HTTP run's.
+- Sending a binary REQUEST body is not supported yet: `body` is a string.
 - `ctx.env.<NAME>` - secrets for THIS project only, from two merged sources: the project's own secrets set over the API (see "Project secrets") and the runner's environment (`SVAPI_FN_<project>__<NAME>` in `runner.env`). A host variable wins over a stored secret of the same name. Never another project's, and never the runner's own configuration.
 - `ctx.log(...)` - captured into the run's `console`, bounded.
 

+ 36 - 1
cmake/Dependencies.cmake

@@ -1,7 +1,42 @@
 include(FetchContent)
 set(HTTPLIB_REQUIRE_OPENSSL ON CACHE BOOL "" FORCE)
 set(HTTPLIB_USE_OPENSSL_IF_AVAILABLE ON CACHE BOOL "" FORCE)
+# Pinned, and the pin is a decision rather than a default.
+#
+# v0.46.0 -> v0.59.0 closes 17 releases. What made it worth doing, limited to
+# fixes that are actually REACHABLE through this service's surface - every
+# route here is a regex route, /fn/{project}/* is unauthenticated, and the web
+# UI is served from a static mount point:
+#   v0.51.0  `chunked` matched only as the WHOLE Transfer-Encoding value, so a
+#            final-coding spelling slipped past it - a request-smuggling shape,
+#            and we sit behind nginx, which is where that class bites.
+#   v0.51.0  an out-of-range Content-Length was cast straight to size_t and
+#            silently truncated instead of being refused.
+#   v0.57.0  control characters accepted in the chunk-size line.
+#   v0.56.0  a Range first-byte-pos that overflows ssize_t now answers 416;
+#            it reaches us because we serve static files.
+#   v0.53.0  a static mount point was compared as a byte PREFIX rather than on
+#            a path-segment boundary.
+#   v0.52.0  listen backlog raised from 5 to 128, which five pending
+#            connections overflow under ordinary churn.
+#
+# NOT the reason, and recorded because it was my first one and it was wrong:
+# v0.53.1's stack overflow in RegexMatcher::match() is real but was never
+# reachable here. CPPHTTPLIB_REQUEST_URI_MAX_LENGTH is 8192 in v0.46.0 too and
+# is enforced BEFORE routing, so a path long enough to overflow the stack is
+# answered 414 and never reaches the matcher. Measured on both versions rather
+# than taken from the changelog: escalating paths up to 2 MB against /fn/ get
+# 414 and the server stays up.
+#
+# Other fixes in the range apply to code paths this project does not use -
+# multipart SENDING, chunked response trailers, WebSockets, Mbed TLS - so they
+# are not part of the case either.
+#
+# NOT v0.60.0, deliberately: its security fix is Mbed TLS hostname
+# verification and we build against OpenSSL, and its bug fixes are all
+# redirect behaviour, which applyOutboundDefaults() turns off. It buys this
+# project nothing and it was released the same day it was considered.
 FetchContent_Declare(httplib
     GIT_REPOSITORY https://github.com/yhirose/cpp-httplib.git
-    GIT_TAG        v0.46.0)
+    GIT_TAG        v0.59.0)
 FetchContent_MakeAvailable(httplib)

+ 30 - 3
runner/src/host_context.cpp

@@ -1515,10 +1515,37 @@ struct HostContext::Impl {
                                 options.at("responseType").is_string() &&
                                 options.at("responseType").get<std::string>() == "base64";
 
+        const int64_t beforeMs = elapsedMs();
         auto result = cli.send(req);
-        if (!result)
-            throw ApiError(ErrCode::Unavailable, "fetch_failed",
-                           "request to '" + parts->host + "' failed: " + httplib::to_string(result.error()));
+        if (!result) {
+            const int64_t tookMs = elapsedMs() - beforeMs;
+            // The timeouts handed to the client are the run's REMAINING budget,
+            // so a provider slower than that budget fails as a read error -
+            // which httplib words as "Failed to read connection" and which
+            // reads like a network fault. It is not: it is our own deadline.
+            // Saying how long the call was allowed, and how long it took,
+            // makes the two distinguishable without guessing. A consumer
+            // diagnosed exactly this as a stale keep-alive pool, which
+            // ctx.fetch does not even have - every call builds its own client.
+            const bool likelyTimeout = tookMs >= (budget - 1000);
+            const std::string detail =
+                "request to '" + parts->host + "' failed after " + std::to_string(tookMs) +
+                "ms of the " + std::to_string(budget) + "ms this run could still allow it: " +
+                httplib::to_string(result.error());
+            // An operator trace, which this path had none of: a failing
+            // provider was visible ONLY to the tenant, inside their function,
+            // while the journal said nothing. Same hole as the embedding path.
+            spdlog::warn("ctx.fetch {} {} failed after {}ms (budget {}ms, project {}, fn {}) - {}{}",
+                         req.method, parts->host, tookMs, budget, config.project,
+                         config.functionId, httplib::to_string(result.error()),
+                         likelyTimeout ? " [the budget, not the network]" : "");
+            if (likelyTimeout)
+                throw ApiError(ErrCode::GatewayTimeout, "fetch_timeout",
+                               detail + " - this is the run's time budget, not the network; "
+                                        "raise the function's timeoutMs, or move the work to a "
+                                        "job trigger, whose ceiling is far higher");
+            throw ApiError(ErrCode::Unavailable, "fetch_failed", detail);
+        }
 
         nlohmann::json headers = nlohmann::json::object();
         for (const auto& [name, value] : result->headers) headers[name] = value;