Ver Fonte

feat(runner): ctx.env from runner.env, scoped per project

Function secrets live in the runner's own environment, which systemd
loads from /etc/smartbotic-vectorapi/runner.env - a file an operator can
hold at 0640, rather than the settings document, which every
project-manage caller can read back over the API.

One runner serves every project, so the project is part of each
variable's name:

    SVAPI_FN_<project>__<NAME>=value   ->   ctx.env.<NAME>

A flat namespace would hand every tenant's key to every script, which is
why the scoping is in the name rather than in a convention. Nothing
outside the SVAPI_FN_ prefix is ever copied in: the runner's own
environment holds its database address and its auth token, and a function
has no business reading either.

Matched exactly and case-sensitively, because a case-folded match would
let two distinct projects share secrets, and a prefix match would let
"acme" read "acme2"'s. The split is at the FIRST "__", so a project whose
name contains "__" cannot carry secrets - documented rather than guarded,
because every alternative encoding has a worse ambiguity somewhere.

Pure, taking the environment as "NAME=VALUE" strings, so the tenancy
boundary is testable without touching the process environment. 10 tests,
most of them about what must NOT be visible.
fszontagh há 1 mês atrás
pai
commit
097acbbd2d
3 ficheiros alterados com 173 adições e 0 exclusões
  1. 31 0
      runner/src/function_env.cpp
  2. 38 0
      runner/src/function_env.hpp
  3. 104 0
      runner/tests/function_env_test.cpp

+ 31 - 0
runner/src/function_env.cpp

@@ -0,0 +1,31 @@
+#include "function_env.hpp"
+#include <cstring>
+
+extern char** environ;
+
+namespace svapi::runner {
+
+nlohmann::json functionEnvFor(const std::string& project,
+                              const std::vector<std::string>& environment) {
+    nlohmann::json out = nlohmann::json::object();
+    const std::string prefix = std::string(kFunctionEnvPrefix) + project + "__";
+    for (const std::string& entry : environment) {
+        const std::size_t eq = entry.find('=');
+        if (eq == std::string::npos) continue;          // not an assignment
+        const std::string name = entry.substr(0, eq);
+        if (name.size() <= prefix.size()) continue;     // prefix only, no variable name
+        if (name.compare(0, prefix.size(), prefix) != 0) continue;
+        // Another project's secret, or one of the runner's own variables.
+        out[name.substr(prefix.size())] = entry.substr(eq + 1);
+    }
+    return out;
+}
+
+std::vector<std::string> processEnvironment() {
+    std::vector<std::string> out;
+    if (environ == nullptr) return out;
+    for (char** e = environ; *e != nullptr; ++e) out.emplace_back(*e);
+    return out;
+}
+
+} // namespace svapi::runner

+ 38 - 0
runner/src/function_env.hpp

@@ -0,0 +1,38 @@
+#pragma once
+#include <nlohmann/json.hpp>
+#include <string>
+#include <vector>
+
+namespace svapi::runner {
+
+/// The prefix marking an environment variable as a function secret.
+constexpr const char* kFunctionEnvPrefix = "SVAPI_FN_";
+
+/// The secrets one project's functions may read, as `ctx.env`.
+///
+/// Secrets live in the runner's own environment, which systemd loads from
+/// /etc/smartbotic-vectorapi/runner.env - a file an operator can lock down,
+/// rather than the settings document, which every project-manage caller can
+/// read back over the API.
+///
+/// A variable is named `SVAPI_FN_<project>__<NAME>` and reaches the function as
+/// `ctx.env.<NAME>`. The project is part of the NAME on purpose: one runner
+/// serves every project, so without it every function would see every tenant's
+/// secrets. Nothing outside the prefix is ever exposed - the runner's own
+/// environment holds its database address and its auth token, and a function
+/// has no business reading either.
+///
+/// `project` is matched exactly, case-sensitively, as the database stores it.
+/// The split is at the FIRST `__` after the prefix, so a project whose name
+/// contains `__` cannot carry secrets; that is documented rather than guarded,
+/// because the alternative encodings all have a worse ambiguity somewhere.
+///
+/// Pure: takes the environment as "NAME=VALUE" strings so the mapping is
+/// testable without touching the process environment.
+nlohmann::json functionEnvFor(const std::string& project,
+                              const std::vector<std::string>& environment);
+
+/// The current process environment as "NAME=VALUE" strings.
+std::vector<std::string> processEnvironment();
+
+} // namespace svapi::runner

+ 104 - 0
runner/tests/function_env_test.cpp

@@ -0,0 +1,104 @@
+// What a function may read as ctx.env.
+//
+// This is a tenancy boundary: one runner serves every project, so a mistake
+// here hands one customer's API key to another customer's script. Every test
+// below is about what must NOT be visible.
+#include <gtest/gtest.h>
+#include "function_env.hpp"
+
+using svapi::runner::functionEnvFor;
+
+namespace {
+const std::vector<std::string> kEnv = {
+    "SVAPI_FN_acme__OPENAI_KEY=sk-acme",
+    "SVAPI_FN_acme__WEBHOOK_URL=https://acme.example/hook",
+    "SVAPI_FN_novitax__OPENAI_KEY=sk-novitax",
+    // The runner's own configuration, which no function may read.
+    "SVAPI_RUNNER_TOKEN=shared-secret",
+    "DATABASE_ADDRESS=localhost:9004",
+    "PATH=/usr/bin",
+    "HOME=/var/lib/smartbotic-vectorapi",
+};
+}  // namespace
+
+TEST(FunctionEnv, ExposesOnlyTheProjectsOwnSecrets) {
+    const nlohmann::json env = functionEnvFor("acme", kEnv);
+    EXPECT_EQ(env.at("OPENAI_KEY"), "sk-acme");
+    EXPECT_EQ(env.at("WEBHOOK_URL"), "https://acme.example/hook");
+    EXPECT_EQ(env.size(), 2u) << "something leaked in beyond acme's two secrets";
+}
+
+TEST(FunctionEnv, NeverExposesAnotherProjectsSecret) {
+    // The whole reason the project is part of the variable name.
+    const nlohmann::json env = functionEnvFor("acme", kEnv);
+    for (const auto& [name, value] : env.items())
+        EXPECT_NE(value, "sk-novitax") << "novitax's key reached acme via " << name;
+    EXPECT_FALSE(env.contains("novitax__OPENAI_KEY"));
+}
+
+TEST(FunctionEnv, NeverExposesTheRunnersOwnEnvironment) {
+    // The runner's environment holds its auth token and its database address.
+    // A function has no business reading either, so nothing without the prefix
+    // is ever copied in.
+    const nlohmann::json env = functionEnvFor("acme", kEnv);
+    EXPECT_FALSE(env.contains("SVAPI_RUNNER_TOKEN"));
+    EXPECT_FALSE(env.contains("RUNNER_TOKEN"));
+    EXPECT_FALSE(env.contains("PATH"));
+    EXPECT_FALSE(env.contains("HOME"));
+    EXPECT_FALSE(env.contains("DATABASE_ADDRESS"));
+}
+
+TEST(FunctionEnv, AProjectWithNoSecretsGetsAnEmptyObject) {
+    const nlohmann::json env = functionEnvFor("unknown", kEnv);
+    EXPECT_TRUE(env.is_object()) << "ctx.env must always be an object to read from";
+    EXPECT_TRUE(env.empty());
+}
+
+TEST(FunctionEnv, ProjectNamesAreMatchedExactlyNotByPrefix) {
+    // "acme" must not pick up "acme2"'s secrets just because one name starts
+    // with the other. The trailing "__" in the match is what prevents it.
+    const std::vector<std::string> env = {"SVAPI_FN_acme2__KEY=sk-acme2",
+                                          "SVAPI_FN_acme__KEY=sk-acme"};
+    EXPECT_EQ(functionEnvFor("acme", env).at("KEY"), "sk-acme");
+    EXPECT_EQ(functionEnvFor("acme2", env).at("KEY"), "sk-acme2");
+    EXPECT_EQ(functionEnvFor("acme", env).size(), 1u);
+}
+
+TEST(FunctionEnv, IsCaseSensitiveLikeTheProjectNamesThemselves) {
+    const std::vector<std::string> env = {"SVAPI_FN_Acme__KEY=upper"};
+    EXPECT_TRUE(functionEnvFor("acme", env).empty())
+        << "a case-folded match would let two distinct projects share secrets";
+    EXPECT_EQ(functionEnvFor("Acme", env).at("KEY"), "upper");
+}
+
+TEST(FunctionEnv, AVariableNameMayContainUnderscoresIncludingDoubled) {
+    // The split is at the FIRST "__" after the prefix, so everything after it
+    // is the name, doubled underscores and all.
+    const std::vector<std::string> env = {"SVAPI_FN_acme__MY__NESTED_NAME=v"};
+    EXPECT_EQ(functionEnvFor("acme", env).at("MY__NESTED_NAME"), "v");
+}
+
+TEST(FunctionEnv, SkipsAPrefixWithNoVariableName) {
+    const std::vector<std::string> env = {"SVAPI_FN_acme__=empty-name"};
+    EXPECT_TRUE(functionEnvFor("acme", env).empty());
+}
+
+TEST(FunctionEnv, KeepsAnEmptyValueAndAValueContainingEquals) {
+    // A secret may legitimately be empty, and base64 and connection strings
+    // contain "=" - splitting on the last one would corrupt them.
+    const std::vector<std::string> env = {"SVAPI_FN_acme__EMPTY=",
+                                          "SVAPI_FN_acme__B64=YWJj==",
+                                          "SVAPI_FN_acme__DSN=k=v;x=y"};
+    const nlohmann::json out = functionEnvFor("acme", env);
+    EXPECT_EQ(out.at("EMPTY"), "");
+    EXPECT_EQ(out.at("B64"), "YWJj==");
+    EXPECT_EQ(out.at("DSN"), "k=v;x=y");
+}
+
+TEST(FunctionEnv, IgnoresMalformedEntries) {
+    const std::vector<std::string> env = {"SVAPI_FN_acme_NO_DOUBLE_UNDERSCORE=x",
+                                          "SVAPI_FN_acme__OK=y", "no-equals-at-all", ""};
+    const nlohmann::json out = functionEnvFor("acme", env);
+    EXPECT_EQ(out.size(), 1u);
+    EXPECT_EQ(out.at("OK"), "y");
+}