Parcourir la source

feat(runner): authenticate the runner, and fail closed without a token

The runner executes arbitrary JavaScript against the database and holds
no credential of its own, so an unauthenticated runner reachable over the
network is a remote code execution endpoint. It now authenticates a
shared bearer token that vectorapi presents.

The important part is the startup refusal: no token plus a bind address
that is not loopback means the process REFUSES TO START, naming the
address. Not a warning in a log nobody reads. Loopback without a token
stays allowed, because that is the single-host default and nothing else
can reach the port. isLoopbackBind() answers "not loopback" for anything
it does not recognise, so an address it cannot parse produces the
refusal: fail-closed has to be the default branch, not a special case.

The comparison is constant-time. A plain == returns at the first
differing byte, which leaks the matching prefix length to anyone who can
time the response - a practical attack on a long-lived shared secret, and
the fix costs nothing. An empty expected token is never satisfiable, so
"authentication disabled" cannot degrade into "presenting nothing
authenticates you"; whether to allow that at all is startupRefusal's
decision, not the comparison's.

/health is authenticated too: it is what vectorapi uses to decide a
runner is usable and it reports pool state, neither of which belongs to
an anonymous caller.

Both sides prefer SVAPI_RUNNER_TOKEN in the .env over the config file,
because runner.json and config.json are conffiles and tend to be
world-readable, and a secret in a dpkg-managed file can be clobbered by
an upgrade.

Also fixes a real startup bug found while packaging: the runner sent
sd_notify(READY=1) straight after spawning the listener thread, so under
Type=notify systemd would consider a runner ready whose bind was still
pending or had already failed - and a failed bind still returned 0, so
Restart=on-failure never fired. It now binds synchronously before
notifying and returns non-zero when the listener fails.

8 tests on the pure decision logic.
fszontagh il y a 1 mois
Parent
commit
222f5ef5d4

+ 12 - 1
runner/CMakeLists.txt

@@ -83,7 +83,10 @@ set(SVAPI_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../src")
 
 # /run, /validate and /health as JSON in, JSON out: no transport, no database,
 # which is what keeps the protocol testable on the dev host.
-add_library(runner_protocol STATIC src/run_service.cpp)
+add_library(runner_protocol STATIC
+    src/run_service.cpp
+    src/function_env.cpp
+    src/runner_auth.cpp)
 target_include_directories(runner_protocol PUBLIC
     ${CMAKE_CURRENT_SOURCE_DIR}/src
     ${SVAPI_SRC_DIR})
@@ -124,6 +127,14 @@ if(BUILD_TESTS)
     target_link_libraries(test_run_service PRIVATE
         runner_protocol OpenSSL::Crypto GTest::gtest_main)
     gtest_discover_tests(test_run_service PROPERTIES TIMEOUT 120)
+
+    # ctx.env scoping and the runner's own authentication: both pure, and both
+    # tenancy boundaries, so they are tested without an engine or a database.
+    add_executable(test_runner_env_auth
+        tests/function_env_test.cpp
+        tests/runner_auth_test.cpp)
+    target_link_libraries(test_runner_env_auth PRIVATE runner_protocol GTest::gtest_main)
+    gtest_discover_tests(test_runner_env_auth)
 endif()
 
 # The host bindings: the ctx.* surface. A SEPARATE target from runner_core

+ 1 - 1
runner/config/runner.json

@@ -1,6 +1,6 @@
 {
   "log_level": "info",
-  "http": { "bind_address": "127.0.0.1", "port": 8090, "read_timeout_sec": 30 },
+  "http": { "bind_address": "127.0.0.1", "port": 8090, "read_timeout_sec": 30, "auth_token": "" },
   "database": { "address": "localhost:9004" },
   "runtime": {
     "pool_size": 4,

+ 75 - 14
runner/src/main.cpp

@@ -11,7 +11,9 @@
 // database client, which is what keeps run_service testable on a host where
 // that client cannot compile at all (CLAUDE.md).
 #include "db_gateway.hpp"
+#include "function_env.hpp"
 #include "function_record.hpp"
+#include "runner_auth.hpp"
 #include "function_registry.hpp"
 #include "run_service.hpp"
 #include "runner/host_context.hpp"
@@ -53,11 +55,14 @@ void onSignal(int) { g_running = false; }
 /// in the database, not here.
 struct RunnerConfig {
     std::string logLevel = "info";
-    /// Loopback by default. The runner has no authentication of its own - the
-    /// protocol vectorapi speaks to it carries no credential - so it must not
-    /// be reachable from anywhere an attacker is. Widening this bind address is
-    /// a decision about network placement, and it should be a deliberate one.
+    /// Loopback by default: the single-host deployment, where no token is
+    /// needed because nothing else can reach the port. Binding anywhere else
+    /// REQUIRES a token - see startupRefusal().
     std::string httpBind = "127.0.0.1";
+    /// Shared secret vectorapi presents as `Authorization: Bearer`. Prefer
+    /// SVAPI_RUNNER_TOKEN in runner.env, which can be mode 0640; this config
+    /// file is a conffile and tends to be world-readable.
+    std::string authToken;
     uint16_t httpPort = 8090;
     std::string dbAddress = "localhost:9004";
 
@@ -81,6 +86,7 @@ struct RunnerConfig {
             c.httpBind = h.value("bind_address", c.httpBind);
             c.httpPort = h.value("port", c.httpPort);
             c.readTimeoutSec = h.value("read_timeout_sec", c.readTimeoutSec);
+            c.authToken = h.value("auth_token", c.authToken);
         }
         if (j.contains("database") && j["database"].is_object())
             c.dbAddress = j["database"].value("address", c.dbAddress);
@@ -146,7 +152,8 @@ private:
 /// RunService's ctx seam, over the real HostContext.
 class GatewayHostBindings : public svapi::runner::HostBindingsFactory {
 public:
-    explicit GatewayHostBindings(svapi::DbGateway& db) : db_(db) {}
+    GatewayHostBindings(svapi::DbGateway& db, std::vector<std::string> environment)
+        : db_(db), environment_(std::move(environment)) {}
 
     bool create(const Request& request, svapi::runner::HostBindingsLease& out,
                 std::string& error) override {
@@ -156,9 +163,11 @@ public:
         cfg.policy = request.policy;
         cfg.trigger = request.trigger;
         cfg.deadlineMs = request.deadlineMs;
-        // cfg.env stays empty: ctx.env is secrets, and nothing has yet decided
-        // where a project's secrets are stored or who may read them. An empty
-        // env is the only answer that cannot leak one.
+        // Only this project's secrets, from the runner's own environment
+        // (systemd loads runner.env). The project is part of each variable's
+        // name, because one runner serves every project and nothing else would
+        // keep one tenant's key away from another's script.
+        cfg.env = svapi::runner::functionEnvFor(request.project, environment_);
         try {
             auto host = std::make_unique<svapi::runner::HostContext>(db_, std::move(cfg));
             svapi::runner::HostContext* raw = host.get();
@@ -181,6 +190,7 @@ public:
 
 private:
     svapi::DbGateway& db_;
+    std::vector<std::string> environment_;
 };
 
 /// Parse a request body, or answer 400 with the same error envelope the rest of
@@ -251,9 +261,27 @@ int main(int argc, char** argv) {
     options.version = svapi::VERSION;
 
     RegistryFunctionSource source(registry);
-    GatewayHostBindings host(db);
+    // Snapshot the environment once: it does not change under a running
+    // process, and re-reading it per run would be work for no gain.
+    GatewayHostBindings host(db, svapi::runner::processEnvironment());
     svapi::runner::RunService service(source, options, &host);
 
+    // The environment wins over the config file: a secret belongs in
+    // runner.env, which systemd can keep at mode 0640, not in a conffile.
+    std::string authToken = cfg.authToken;
+    if (const char* fromEnv = std::getenv(svapi::runner::kRunnerTokenEnvVar);
+        fromEnv != nullptr && *fromEnv != '\0') {
+        authToken = fromEnv;
+    }
+    if (const auto refusal = svapi::runner::startupRefusal(cfg.httpBind, authToken)) {
+        spdlog::critical("{}", *refusal);
+        return 1;
+    }
+    if (authToken.empty()) {
+        spdlog::warn("no runner token set; serving unauthenticated on {} - safe only"
+                     " because nothing off this host can reach it", cfg.httpBind);
+    }
+
     httplib::Server server;
     server.set_read_timeout(cfg.readTimeoutSec, 0);
     server.set_write_timeout(cfg.readTimeoutSec, 0);
@@ -264,6 +292,24 @@ int main(int argc, char** argv) {
         return new httplib::ThreadPool(static_cast<size_t>(cfg.poolSize) + 2);
     };
 
+    // Authenticate everything, /health included. The health check is what
+    // vectorapi uses to decide a runner is usable, and it reports the pool's
+    // state - neither is something an unauthenticated caller should see.
+    if (!authToken.empty()) {
+        server.set_pre_routing_handler(
+            [&authToken](const httplib::Request& req, httplib::Response& res) {
+                const std::string presented =
+                    svapi::runner::bearerToken(req.get_header_value("Authorization"));
+                if (svapi::runner::tokenMatches(authToken, presented))
+                    return httplib::Server::HandlerResponse::Unhandled;
+                res.status = 401;
+                res.set_content(R"({"error":{"code":"unauthorized","message":)"
+                                R"("missing or invalid runner token"}})",
+                                "application/json");
+                return httplib::Server::HandlerResponse::Handled;
+            });
+    }
+
     server.Post("/run", [&service](const httplib::Request& req, httplib::Response& res) {
         nlohmann::json body;
         if (!readJsonBody(req, res, body)) return;
@@ -293,18 +339,33 @@ int main(int argc, char** argv) {
         res.set_content(nlohmann::json{{"ok", false}, {"error", what}}.dump(), "application/json");
     });
 
+    // Bind BEFORE notifying, on this thread. listen() binds and serves in one
+    // call, so notifying after merely spawning the thread would tell systemd we
+    // are ready while the bind was still pending - or had already failed. Under
+    // Type=notify that makes a runner that is about to exit look started, and
+    // anything ordered after it would briefly see success.
+    if (!server.bind_to_port(cfg.httpBind, cfg.httpPort)) {
+        spdlog::critical("cannot bind {}:{} - address in use, or not permitted", cfg.httpBind,
+                         cfg.httpPort);
+        return 1;
+    }
+
+    std::atomic<bool> serveFailed{false};
     std::thread http([&] {
-        spdlog::info("runner listening on {}:{} (pool {}, wall limit {}ms)", cfg.httpBind,
-                     cfg.httpPort, cfg.poolSize, cfg.maxWallTimeMs);
-        if (!server.listen(cfg.httpBind, cfg.httpPort)) {
-            spdlog::error("bind failed");
+        if (!server.listen_after_bind()) {
+            spdlog::error("the listener stopped unexpectedly");
+            serveFailed = true;
             g_running = false;
         }
     });
+    spdlog::info("runner listening on {}:{} (pool {}, wall limit {}ms)", cfg.httpBind, cfg.httpPort,
+                 cfg.poolSize, cfg.maxWallTimeMs);
     sd_notify(0, "READY=1");
     while (g_running) { sd_notify(0, "WATCHDOG=1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }
     sd_notify(0, "STOPPING=1");
     server.stop();
     if (http.joinable()) http.join();
-    return 0;
+    // Non-zero on a listener failure, so Restart=on-failure actually fires. A
+    // signal-driven shutdown is a clean exit.
+    return serveFailed ? 1 : 0;
 }

+ 61 - 0
runner/src/runner_auth.cpp

@@ -0,0 +1,61 @@
+#include "runner_auth.hpp"
+#include <algorithm>
+#include <cctype>
+
+namespace svapi::runner {
+namespace {
+constexpr const char* kBearer = "bearer ";
+}  // namespace
+
+std::string bearerToken(const std::string& authorizationHeader) {
+    if (authorizationHeader.size() <= 7) return {};
+    std::string scheme = authorizationHeader.substr(0, 7);
+    std::transform(scheme.begin(), scheme.end(), scheme.begin(),
+                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
+    if (scheme != kBearer) return {};
+    // Trim surrounding whitespace only; a token is otherwise taken verbatim,
+    // since trimming inside it would silently accept a corrupted secret.
+    std::string token = authorizationHeader.substr(7);
+    const auto notSpace = [](unsigned char c) { return std::isspace(c) == 0; };
+    const auto b = std::find_if(token.begin(), token.end(), notSpace);
+    const auto e = std::find_if(token.rbegin(), token.rend(), notSpace).base();
+    return (b < e) ? std::string(b, e) : std::string();
+}
+
+bool tokenMatches(const std::string& expected, const std::string& presented) {
+    // An empty expected token means authentication is disabled; callers decide
+    // whether that is allowed. It must never be something a caller can satisfy
+    // by presenting nothing.
+    if (expected.empty()) return false;
+    // Compare over the longer of the two so the loop count does not depend on
+    // the presented length, and fold the length difference into the result.
+    const std::size_t n = std::max(expected.size(), presented.size());
+    unsigned char diff = static_cast<unsigned char>(expected.size() ^ presented.size());
+    for (std::size_t i = 0; i < n; ++i) {
+        const unsigned char a = i < expected.size() ? static_cast<unsigned char>(expected[i]) : 0;
+        const unsigned char b = i < presented.size() ? static_cast<unsigned char>(presented[i]) : 0;
+        diff |= static_cast<unsigned char>(a ^ b);
+    }
+    return diff == 0;
+}
+
+bool isLoopbackBind(const std::string& bindAddress) {
+    if (bindAddress == "localhost" || bindAddress == "::1") return true;
+    // Any 127.0.0.0/8 literal. Textual rather than parsed because this decides
+    // whether to REFUSE: an address this function does not understand must come
+    // out "not loopback", so the refusal is the default.
+    return bindAddress.rfind("127.", 0) == 0;
+}
+
+std::optional<std::string> startupRefusal(const std::string& bindAddress,
+                                          const std::string& token) {
+    if (!token.empty()) return std::nullopt;
+    if (isLoopbackBind(bindAddress)) return std::nullopt;
+    return "refusing to start: no runner token is set (" + std::string(kRunnerTokenEnvVar) +
+           " or http.auth_token) while bound to " + bindAddress +
+           ", which is reachable from other hosts. An unauthenticated runner runs"
+           " arbitrary JavaScript against the database for anyone who can reach"
+           " it. Set a token, or bind 127.0.0.1.";
+}
+
+} // namespace svapi::runner

+ 38 - 0
runner/src/runner_auth.hpp

@@ -0,0 +1,38 @@
+#pragma once
+#include <optional>
+#include <string>
+
+namespace svapi::runner {
+
+/// The environment variable holding the shared token. Preferred over the config
+/// file: runner.json is a conffile an operator may well leave world-readable,
+/// while runner.env is loaded by systemd and can be mode 0640.
+constexpr const char* kRunnerTokenEnvVar = "SVAPI_RUNNER_TOKEN";
+
+/// Extract the token from an `Authorization: Bearer <token>` header value.
+/// Returns an empty string for anything else, including a bare token with no
+/// scheme - accepting both would mean two code paths to keep in agreement.
+std::string bearerToken(const std::string& authorizationHeader);
+
+/// Constant-time comparison.
+///
+/// A plain `==` returns as soon as two bytes differ, which leaks the length of
+/// the matching prefix to anyone who can time the response. That is a practical
+/// attack against a long-lived shared secret, and the fix costs nothing.
+bool tokenMatches(const std::string& expected, const std::string& presented);
+
+/// Whether this bind address is reachable only from the local host.
+bool isLoopbackBind(const std::string& bindAddress);
+
+/// Why the runner must refuse to start, or nullopt when the configuration is
+/// safe.
+///
+/// The runner executes user JavaScript against the database with no credential
+/// of its own, so an unauthenticated runner on a routable address is a remote
+/// code execution endpoint. It is allowed WITHOUT a token only while bound to
+/// loopback, which is the single-host default. Binding anywhere else without
+/// one is refused at startup rather than logged as a warning nobody reads.
+std::optional<std::string> startupRefusal(const std::string& bindAddress,
+                                          const std::string& token);
+
+} // namespace svapi::runner

+ 75 - 0
runner/tests/runner_auth_test.cpp

@@ -0,0 +1,75 @@
+// The runner's own authentication.
+//
+// The runner runs user JavaScript against the database and holds no credential
+// of its own, so an unauthenticated runner reachable over the network is a
+// remote code execution endpoint. These tests are about refusing that.
+#include <gtest/gtest.h>
+#include "runner_auth.hpp"
+
+using svapi::runner::bearerToken;
+using svapi::runner::isLoopbackBind;
+using svapi::runner::startupRefusal;
+using svapi::runner::tokenMatches;
+
+TEST(RunnerAuth, ReadsABearerTokenCaseInsensitivelyInTheScheme) {
+    EXPECT_EQ(bearerToken("Bearer abc123"), "abc123");
+    EXPECT_EQ(bearerToken("bearer abc123"), "abc123");
+    EXPECT_EQ(bearerToken("BEARER abc123"), "abc123");
+    EXPECT_EQ(bearerToken("Bearer   abc123  "), "abc123");
+}
+
+TEST(RunnerAuth, RejectsAnythingThatIsNotABearerHeader) {
+    EXPECT_EQ(bearerToken(""), "");
+    EXPECT_EQ(bearerToken("abc123"), "") << "a bare token would be a second code path";
+    EXPECT_EQ(bearerToken("Basic abc123"), "");
+    EXPECT_EQ(bearerToken("Bearer"), "");
+    EXPECT_EQ(bearerToken("Bearer "), "");
+}
+
+TEST(RunnerAuth, MatchesOnlyAnExactToken) {
+    EXPECT_TRUE(tokenMatches("s3cret", "s3cret"));
+    EXPECT_FALSE(tokenMatches("s3cret", "s3cre"));
+    EXPECT_FALSE(tokenMatches("s3cret", "s3cretx"));
+    EXPECT_FALSE(tokenMatches("s3cret", "S3CRET"));
+    EXPECT_FALSE(tokenMatches("s3cret", ""));
+}
+
+TEST(RunnerAuth, AnEmptyExpectedTokenIsNeverSatisfied) {
+    // Authentication being disabled must not turn into "anyone presenting
+    // nothing is authenticated". The decision to allow unauthenticated access
+    // belongs to startupRefusal, not to the comparison.
+    EXPECT_FALSE(tokenMatches("", ""));
+    EXPECT_FALSE(tokenMatches("", "anything"));
+}
+
+TEST(RunnerAuth, LoopbackIsRecognisedAndAnythingUnknownIsNot) {
+    EXPECT_TRUE(isLoopbackBind("127.0.0.1"));
+    EXPECT_TRUE(isLoopbackBind("127.1.2.3"));
+    EXPECT_TRUE(isLoopbackBind("localhost"));
+    EXPECT_TRUE(isLoopbackBind("::1"));
+    // Must come out false, because false is what causes the refusal.
+    EXPECT_FALSE(isLoopbackBind("0.0.0.0"));
+    EXPECT_FALSE(isLoopbackBind("::"));
+    EXPECT_FALSE(isLoopbackBind("192.168.1.10"));
+    EXPECT_FALSE(isLoopbackBind(""));
+    EXPECT_FALSE(isLoopbackBind("127"));
+    EXPECT_FALSE(isLoopbackBind("not-an-address"));
+}
+
+TEST(RunnerAuth, StartsUnauthenticatedOnlyOnLoopback) {
+    EXPECT_FALSE(startupRefusal("127.0.0.1", "").has_value());
+    EXPECT_FALSE(startupRefusal("localhost", "").has_value());
+}
+
+TEST(RunnerAuth, RefusesToStartUnauthenticatedOnARoutableAddress) {
+    const auto why = startupRefusal("0.0.0.0", "");
+    ASSERT_TRUE(why.has_value()) << "an open runner on 0.0.0.0 is remote code execution";
+    EXPECT_NE(why->find("0.0.0.0"), std::string::npos) << "the message must name the address";
+    EXPECT_TRUE(startupRefusal("192.168.1.10", "").has_value())
+        << "a private LAN address is still reachable from other hosts";
+}
+
+TEST(RunnerAuth, ATokenAllowsAnyBindAddress) {
+    EXPECT_FALSE(startupRefusal("0.0.0.0", "s3cret").has_value());
+    EXPECT_FALSE(startupRefusal("192.168.1.10", "s3cret").has_value());
+}

+ 1 - 0
src/config.cpp

@@ -26,6 +26,7 @@ Config Config::fromJson(const nlohmann::json& j) {
                     c.runnerEndpoints.push_back(e.get<std::string>());
         }
         c.functionRunsKept = f.value("runs_kept", c.functionRunsKept);
+        c.runnerToken = f.value("runner_token", c.runnerToken);
     }
     return c;
 }

+ 4 - 0
src/config.hpp

@@ -23,6 +23,10 @@ struct Config {
     /// Runs kept per function. There is no scheduler to prune them yet, so the
     /// log is trimmed on write; unbounded, a busy function fills the database.
     uint32_t functionRunsKept = 50;
+    /// Shared secret presented to the runners. Prefer SVAPI_RUNNER_TOKEN in
+    /// vectorapi.env over config.json, which is a conffile and tends to be
+    /// world-readable. Empty is valid only for a loopback runner.
+    std::string runnerToken;
 
     static Config fromJson(const nlohmann::json& j);
     static Config load(const std::string& path);  // reads file then fromJson

+ 7 - 0
src/main.cpp

@@ -92,6 +92,13 @@ int main(int argc, char** argv) {
     if (!cfg.runnerEndpoints.empty()) {
         svapi::RunnerPool::Options ro;
         ro.endpoints = cfg.runnerEndpoints;
+        // Environment over config file: the token is a secret, and
+        // vectorapi.env can be mode 0640 where config.json is a conffile.
+        ro.authToken = cfg.runnerToken;
+        if (const std::string fromEnv = envOr("SVAPI_RUNNER_TOKEN"); !fromEnv.empty())
+            ro.authToken = fromEnv;
+        if (ro.authToken.empty())
+            spdlog::warn("no runner token configured - only a loopback runner will accept us");
         runners = std::make_unique<svapi::RunnerPool>(ro);
         spdlog::info("function runners configured: {}", cfg.runnerEndpoints.size());
     } else {

+ 4 - 0
src/runner_client.cpp

@@ -25,6 +25,10 @@ void configureClient(httplib::Client& cli, const Opts& o) {
     // turn a compromised or misconfigured runner into an SSRF primitive.
     cli.set_follow_location(false);
     cli.set_keep_alive(true);
+    // The runner authenticates every route, /health included. Empty only for a
+    // loopback runner, which is the one case it serves unauthenticated.
+    if (!o.authToken.empty())
+        cli.set_default_headers({{"Authorization", "Bearer " + o.authToken}});
 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
     cli.enable_server_certificate_verification(true);
 #endif

+ 4 - 0
src/runner_client.hpp

@@ -59,6 +59,10 @@ public:
         uint32_t readTimeoutSec = 30;
         /// How long a failed runner is skipped before being retried.
         uint32_t unhealthyBackoffSec = 10;
+        /// Shared secret presented as `Authorization: Bearer`. Empty is valid
+        /// only for a loopback runner, which refuses to start on any other
+        /// address without one.
+        std::string authToken;
     };
 
     explicit RunnerPool(Options opts);