Parcourir la source

feat(functions): union the egress blocklist with the defaults, and wire it

The SSRF blocklist from settings existed in the design but nothing ever
called it: fromStrings had no caller but withDefaults, so the policy was
always the hard-coded defaults. So the replace-vs-union question was
moot in practice and fixing it meant connecting the feature.

Union, not replace. SsrfPolicy::fromSettings() ADDS an operator's CIDRs
to the built-in defaults, so editing the list can only ever refuse more.
A replacing list meant adding one range silently reopened loopback,
RFC1918 and the cloud metadata endpoint - a footgun with no warning.

function_egress_allow_private is the explicit opt-out, and it relaxes
ONLY privateBlockedCidrs(). 169.254.0.0/16, link-local, multicast,
reserved space and the IPv6 spellings of an IPv4 destination stay blocked
whatever it is set to: NAT64 and 6to4 can express ANY IPv4 address, so
relaxing those would reopen by the back door what the flag relaxes by the
front. The flag does expose loopback, where our own API listens; that is
the operator's call and the UI says so.

Wired end to end, which it was not before:
 - the runner builds the policy from the settings document on first
   ctx.fetch and pins it for the rest of the run, so a hot-reload cannot
   change the rules between two fetches of one function;
 - PUT /api/v1/settings accepts both fields and VALIDATES each CIDR,
   answering 422 invalid_cidr with the offending entry. Validated at the
   boundary rather than at use: a typo in an egress blocklist is a hole in
   the guard, and the operator who typed it is the only person who can fix
   it - a warning in some later run's log reaches nobody;
 - an unparseable entry that somehow survives is reported into that run's
   own console, where the function author will see it.

HostContextConfig gains an optional pre-built policy because of this.
Null in production; set by the egress tests, which point the gateway at a
dead port. An unconnected database client CRASHES rather than throwing,
so "no database" has to mean "do not read one" - the third time that trap
has cost a test in this codebase, now documented where it bites.

7 new net_guard tests, including one asserting the metadata endpoint stays
blocked with allow_private on.
fszontagh il y a 1 mois
Parent
commit
e94b9c471d

+ 9 - 0
runner/include/runner/host_context.hpp

@@ -39,6 +39,15 @@ struct HostContextConfig {
     /// Wall-clock budget left for the whole run, used to bound outbound calls so
     /// one slow provider cannot outlive the run that is waiting for it.
     int64_t deadlineMs = 0;
+
+    /// Pre-built egress policy, used as-is when set.
+    ///
+    /// Null in production, where the policy is built from the settings document
+    /// on the first ctx.fetch. Set by tests, which point the gateway at a dead
+    /// port and must never reach it: an unconnected database client CRASHES
+    /// rather than throwing, so "no database" has to mean "do not read one",
+    /// not "handle the error".
+    std::shared_ptr<const functions::SsrfPolicy> egressPolicy;
 };
 
 /// Installs `ctx` for one run. One instance per run: it holds that run's

+ 31 - 4
runner/src/host_context.cpp

@@ -311,9 +311,11 @@ struct HostContext::Impl {
     /// request too.
     std::unordered_map<std::string, std::optional<CollectionMeta>> metaCache;
 
-    /// Pinned for the whole run so a settings hot-reload cannot change the
-    /// egress rules between two fetches of the same function.
-    std::shared_ptr<const functions::SsrfPolicy> ssrf = functions::currentSsrfPolicy();
+    /// Built from settings on first use, then pinned for the rest of the run so
+    /// a hot-reload cannot change the egress rules between two fetches of one
+    /// function. Lazy because most runs never call ctx.fetch and would
+    /// otherwise pay a settings read for nothing.
+    std::shared_ptr<const functions::SsrfPolicy> ssrfCached;
 
     bool settingsLoaded = false;
     Settings global;
@@ -395,6 +397,30 @@ struct HostContext::Impl {
             projectEmbedding = ProjectSettings::fromJson(*doc);
     }
 
+    /// The egress policy for this run: the built-in defaults UNIONED with the
+    /// operator's extra CIDRs, minus the private ranges only if the settings
+    /// document explicitly opted in. An unparseable entry is reported into the
+    /// run's own log, because a typo in a blocklist is a hole in the guard and
+    /// the author is the one who will see this output.
+    const functions::SsrfPolicy& ssrfPolicy() {
+        if (!ssrfCached) {
+            // An injected policy means no settings read, which is what lets the
+            // egress tests run without a database.
+            if (config.egressPolicy) {
+                ssrfCached = config.egressPolicy;
+                return *ssrfCached;
+            }
+            loadSettings();
+            std::vector<std::string> invalid;
+            ssrfCached = std::make_shared<const functions::SsrfPolicy>(
+                functions::SsrfPolicy::fromSettings(global.functionEgressBlockedCidrs,
+                                                    global.functionEgressAllowPrivate, &invalid));
+            for (const std::string& bad : invalid)
+                addLog("[warn] ignoring unparseable egress blocklist entry: " + bad);
+        }
+        return *ssrfCached;
+    }
+
     /// Embed `text` for a vector op. Mirrors handlers/vectors.cpp: the same
     /// cache, keyed the same way, so a function and an HTTP call that embed the
     /// same string cost one provider call between them.
@@ -644,7 +670,8 @@ struct HostContext::Impl {
             throw ApiError(ErrCode::Forbidden, "egress_blocked", reason);
         }
 
-        auto decision = hostdetail::decideEgress(*parts, *ssrf, hostdetail::resolveWithGetaddrinfo);
+        auto decision =
+            hostdetail::decideEgress(*parts, ssrfPolicy(), hostdetail::resolveWithGetaddrinfo);
         if (!decision.allowed) {
             blocked.push_back(decision.reason);
             throw ApiError(ErrCode::Forbidden, "egress_blocked", decision.reason);

+ 7 - 0
runner/tests/host_context_test.cpp

@@ -20,6 +20,7 @@
 #include <gtest/gtest.h>
 
 #include <functional>
+#include <memory>
 #include <set>
 #include <string>
 #include <vector>
@@ -113,6 +114,12 @@ HostContextConfig httpTrigger(KeyScope policy) {
                    {"body", {{"n", 7}}}};
     cfg.env = {{"PROVIDER_KEY", "s3cret"}};
     cfg.deadlineMs = 2000;
+    // Injected, so ctx.fetch never reads the settings document. This file
+    // points the gateway at a dead port on purpose, and an unconnected database
+    // client CRASHES rather than throwing - so the egress tests have to supply
+    // the policy rather than let it be loaded.
+    cfg.egressPolicy =
+        std::make_shared<const svapi::functions::SsrfPolicy>(svapi::functions::SsrfPolicy::withDefaults());
     return cfg;
 }
 

+ 40 - 0
src/functions/net_guard.cpp

@@ -296,10 +296,50 @@ const std::vector<std::string>& SsrfPolicy::defaultBlockedCidrs() {
     return kDefaults;
 }
 
+const std::vector<std::string>& SsrfPolicy::privateBlockedCidrs() {
+    // What allowPrivate relaxes, and nothing more. 169.254.0.0/16 and fe80::/10
+    // are NOT here: the cloud metadata service is the highest-value target an
+    // SSRF has, and no legitimate function reaches it. Nor are the IPv6
+    // spellings of an IPv4 destination (NAT64, 6to4, ::/96), because relaxing
+    // those would reopen by the back door what this list relaxes by the front.
+    static const std::vector<std::string> kPrivate = {
+        "10.0.0.0/8",       // RFC1918
+        "100.64.0.0/10",    // carrier-grade NAT
+        "127.0.0.0/8",      // loopback - note our own API listens here
+        "172.16.0.0/12",    // RFC1918
+        "192.168.0.0/16",   // RFC1918
+        "::/96",            // unspecified, ::1, deprecated ::127.0.0.1
+        "::1/128",          // loopback
+        "fc00::/7",         // IPv6 unique local
+    };
+    return kPrivate;
+}
+
 SsrfPolicy SsrfPolicy::withDefaults() {
     return fromStrings(defaultBlockedCidrs(), nullptr);
 }
 
+SsrfPolicy SsrfPolicy::fromSettings(const std::vector<std::string>& extraBlocked,
+                                    bool allowPrivate, std::vector<std::string>* invalid) {
+    // Union, not replace. Start from the built-ins so an operator editing the
+    // list can only ever ADD to what is refused.
+    std::vector<std::string> all;
+    const std::vector<std::string>& defaults = defaultBlockedCidrs();
+    if (!allowPrivate) {
+        all = defaults;
+    } else {
+        // Drop only the relaxable subset, by exact text: these are our own
+        // string literals, so an exact match is reliable here and keeps the
+        // relationship between the two lists obvious to a reader.
+        const std::vector<std::string>& relax = privateBlockedCidrs();
+        for (const std::string& d : defaults) {
+            if (std::find(relax.begin(), relax.end(), d) == relax.end()) all.push_back(d);
+        }
+    }
+    all.insert(all.end(), extraBlocked.begin(), extraBlocked.end());
+    return fromStrings(all, invalid);
+}
+
 SsrfPolicy SsrfPolicy::fromStrings(const std::vector<std::string>& cidrs,
                                    std::vector<std::string>* invalid) {
     SsrfPolicy p;

+ 31 - 5
src/functions/net_guard.hpp

@@ -90,17 +90,43 @@ public:
     /// address.
     static const std::vector<std::string>& defaultBlockedCidrs();
 
+    /// The subset of the defaults that `allowPrivate` relaxes: loopback,
+    /// RFC1918, carrier NAT and IPv6 unique-local. Deliberately NOT the
+    /// metadata endpoint or link-local.
+    static const std::vector<std::string>& privateBlockedCidrs();
+
     /// Policy built from the built-in defaults.
     static SsrfPolicy withDefaults();
 
-    /// Policy built from raw config strings. This REPLACES the defaults rather
-    /// than extending them, so an operator can deliberately widen egress.
-    /// Entries that do not parse are skipped and appended to `invalid` (when
-    /// non-null) so the caller can log them: a typo in the blocklist is a hole
-    /// in the guard and must be visible, not silent.
+    /// Policy built from exactly these CIDRs and nothing else. The raw builder:
+    /// withDefaults() and the tests use it. Operator settings go through
+    /// fromSettings(), which unions. Entries that do not parse are skipped and
+    /// appended to `invalid` (when non-null) so the caller can log them: a typo
+    /// in a blocklist is a hole in the guard and must be visible, not silent.
     static SsrfPolicy fromStrings(const std::vector<std::string>& cidrs,
                                   std::vector<std::string>* invalid);
 
+    /// Policy from operator settings.
+    ///
+    /// `extraBlocked` is ADDED to the built-in defaults, never substituted for
+    /// them. An operator adding one CIDR to a blocklist must not silently
+    /// reopen loopback, RFC1918 and the cloud metadata endpoint - which is
+    /// exactly what a replacing list did.
+    ///
+    /// `allowPrivate` is the explicit opt-out, for a function that must reach an
+    /// internal service on purpose. It drops ONLY the private and loopback
+    /// ranges (privateBlockedCidrs()); the metadata endpoint, link-local,
+    /// multicast, reserved space and the IPv6 spellings of an IPv4 destination
+    /// stay blocked whatever it is set to, because almost nothing legitimate
+    /// targets those and 169.254.169.254 is the highest-value prize an SSRF has.
+    /// A separate flag rather than an emergent property of the list, so turning
+    /// it on is a visible decision in the settings document.
+    ///
+    /// Note what allowPrivate permits: loopback is where our own API listens, so
+    /// a function could then call it. That is the operator's call to make.
+    static SsrfPolicy fromSettings(const std::vector<std::string>& extraBlocked,
+                                   bool allowPrivate, std::vector<std::string>* invalid);
+
     /// Is this address literal blocked?
     ///
     /// Returns true - FAIL CLOSED - when `ip` is not a valid IP literal at all.

+ 31 - 0
src/handlers/settings.cpp

@@ -1,4 +1,5 @@
 #include "errors.hpp"
+#include "functions/net_guard.hpp"
 #include "json_http.hpp"
 #include "server.hpp"
 namespace svapi {
@@ -54,6 +55,36 @@ void registerSettingsRoutes(ApiServer& s) {
             updated.embeddingCacheNormalize = body["embedding_cache_normalize"].get<bool>();
         if (body.contains("embedding_client_pool_size"))
             updated.embeddingClientPoolSize = body["embedding_client_pool_size"].get<uint32_t>();
+        if (body.contains("function_egress_blocked_cidrs")) {
+            const nlohmann::json& raw = body["function_egress_blocked_cidrs"];
+            if (!raw.is_array())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "function_egress_blocked_cidrs must be an array of CIDR strings");
+            std::vector<std::string> cidrs;
+            for (const auto& e : raw) {
+                if (!e.is_string())
+                    throw ApiError(ErrCode::Unprocessable, "validation",
+                                   "function_egress_blocked_cidrs must contain only strings");
+                const std::string c = e.get<std::string>();
+                if (c.empty()) continue;
+                // Validated HERE, not when a function first calls out. A typo in
+                // an egress blocklist is a hole in the guard, and the operator
+                // who typed it is the only person able to fix it - telling them
+                // now beats a warning in some later run's log.
+                if (!functions::parseCidr(c).has_value())
+                    throw ApiError(ErrCode::Unprocessable, "invalid_cidr",
+                                   "not a valid CIDR or address: '" + c + "'",
+                                   {{"entry", c}});
+                cidrs.push_back(c);
+            }
+            updated.functionEgressBlockedCidrs = std::move(cidrs);
+        }
+        if (body.contains("function_egress_allow_private")) {
+            if (!body["function_egress_allow_private"].is_boolean())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "function_egress_allow_private must be a boolean");
+            updated.functionEgressAllowPrivate = body["function_egress_allow_private"].get<bool>();
+        }
         if (body.contains("captcha_provider"))
             updated.captchaProvider = body["captcha_provider"].get<std::string>();
         // Only overwrite the secret if a non-empty string is supplied (mirror openai_api_key handling).

+ 12 - 0
src/settings.cpp

@@ -19,6 +19,16 @@ Settings Settings::fromJson(const nlohmann::json& j) {
     s.embeddingCacheMaxBytes     = j.value("embedding_cache_max_bytes",   s.embeddingCacheMaxBytes);
     s.embeddingCacheNormalize    = j.value("embedding_cache_normalize",   s.embeddingCacheNormalize);
     s.embeddingClientPoolSize    = j.value("embedding_client_pool_size",  s.embeddingClientPoolSize);
+    if (j.contains("function_egress_blocked_cidrs") && j["function_egress_blocked_cidrs"].is_array()) {
+        // Bind before iterating: a range-for over a temporary subobject of a
+        // parsed document dangles (CLAUDE.md).
+        const nlohmann::json& cidrs = j["function_egress_blocked_cidrs"];
+        for (const auto& c : cidrs)
+            if (c.is_string() && !c.get<std::string>().empty())
+                s.functionEgressBlockedCidrs.push_back(c.get<std::string>());
+    }
+    s.functionEgressAllowPrivate =
+        j.value("function_egress_allow_private", s.functionEgressAllowPrivate);
     s.captchaProvider            = j.value("captcha_provider",   s.captchaProvider);
     s.captchaSecret              = j.value("captcha_secret",     s.captchaSecret);
     s.captchaVerifyUrl           = j.value("captcha_verify_url", s.captchaVerifyUrl);
@@ -37,6 +47,8 @@ nlohmann::json Settings::toJson() const {
             {"embedding_cache_max_bytes",   embeddingCacheMaxBytes},
             {"embedding_cache_normalize",   embeddingCacheNormalize},
             {"embedding_client_pool_size",  embeddingClientPoolSize},
+            {"function_egress_blocked_cidrs", functionEgressBlockedCidrs},
+            {"function_egress_allow_private", functionEgressAllowPrivate},
             {"captcha_provider",   captchaProvider},
             {"captcha_secret",     captchaSecret},
             {"captcha_verify_url", captchaVerifyUrl}};

+ 9 - 0
src/settings.hpp

@@ -22,6 +22,15 @@ struct Settings {
     bool        embeddingCacheNormalize    = false;      // opt-in trim+lowercase
     uint32_t    embeddingClientPoolSize    = 4;          // keep-alive clients per upstream origin
 
+    /// Extra CIDRs a function's ctx.fetch may not reach. ADDED to the built-in
+    /// defaults, never substituted for them - see SsrfPolicy::fromSettings.
+    std::vector<std::string> functionEgressBlockedCidrs;
+    /// Explicit opt-out letting a function reach private and loopback
+    /// addresses. Leaves the cloud metadata endpoint and link-local blocked
+    /// regardless. Off by default, and turning it on means a function can call
+    /// our own API on loopback.
+    bool functionEgressAllowPrivate = false;
+
     std::string captchaProvider;   // "" = disabled | "turnstile" | "hcaptcha"
     std::string captchaSecret;     // masked in GET
     std::string captchaVerifyUrl;  // full verify endpoint

+ 62 - 0
tests/test_functions_net_guard.cpp

@@ -455,3 +455,65 @@ TEST(SsrfBlockReason, ReasonNamesTheOffendingAddressAndRange) {
     EXPECT_NE(why->find("10.0.0.5"), std::string::npos);
     EXPECT_NE(why->find("mixed.example"), std::string::npos);
 }
+
+// ------------------------------------------- settings: union, not replace
+
+TEST(SsrfFromSettings, AddsToTheDefaultsRatherThanReplacingThem) {
+    // The whole point of this entry point. A replacing list meant an operator
+    // adding one CIDR silently reopened loopback, RFC1918 and the cloud
+    // metadata endpoint - a footgun with no warning attached.
+    const SsrfPolicy p = SsrfPolicy::fromSettings({"203.0.55.0/24"}, false, nullptr);
+    EXPECT_TRUE(p.isBlocked("203.0.55.9")) << "the operator's own entry must apply";
+    EXPECT_TRUE(p.isBlocked("127.0.0.1")) << "loopback was silently unblocked";
+    EXPECT_TRUE(p.isBlocked("10.1.2.3")) << "RFC1918 was silently unblocked";
+    EXPECT_TRUE(p.isBlocked("169.254.169.254")) << "the metadata endpoint was unblocked";
+}
+
+TEST(SsrfFromSettings, AnEmptySettingsListIsExactlyTheDefaults) {
+    const SsrfPolicy p = SsrfPolicy::fromSettings({}, false, nullptr);
+    EXPECT_EQ(p.size(), SsrfPolicy::withDefaults().size());
+}
+
+TEST(SsrfFromSettings, AllowPrivateRelaxesPrivateAndLoopbackOnly) {
+    const SsrfPolicy p = SsrfPolicy::fromSettings({}, /*allowPrivate*/ true, nullptr);
+    EXPECT_FALSE(p.isBlocked("127.0.0.1")) << "loopback should be reachable when opted in";
+    EXPECT_FALSE(p.isBlocked("10.1.2.3"));
+    EXPECT_FALSE(p.isBlocked("192.168.1.10"));
+    EXPECT_FALSE(p.isBlocked("172.16.0.5"));
+    EXPECT_FALSE(p.isBlocked("fc00::1"));
+    EXPECT_FALSE(p.isBlocked("::1"));
+}
+
+TEST(SsrfFromSettings, AllowPrivateStillBlocksTheMetadataEndpoint) {
+    // The highest-value prize an SSRF has, and nothing legitimate targets it.
+    // Opting into private egress must not hand it over.
+    const SsrfPolicy p = SsrfPolicy::fromSettings({}, /*allowPrivate*/ true, nullptr);
+    EXPECT_TRUE(p.isBlocked("169.254.169.254"));
+    EXPECT_TRUE(p.isBlocked("169.254.0.1"));
+    EXPECT_TRUE(p.isBlocked("fe80::1")) << "IPv6 link-local is the same exposure";
+}
+
+TEST(SsrfFromSettings, AllowPrivateDoesNotReopenTheIpv6SpellingsOfIpv4) {
+    // Relaxing these would reopen by the back door what allowPrivate relaxes by
+    // the front, and worse: NAT64 and 6to4 can express ANY IPv4 destination.
+    const SsrfPolicy p = SsrfPolicy::fromSettings({}, /*allowPrivate*/ true, nullptr);
+    EXPECT_TRUE(p.isBlocked("64:ff9b::1"))  << "NAT64 prefix";
+    EXPECT_TRUE(p.isBlocked("2002::1"))     << "6to4 prefix";
+    EXPECT_TRUE(p.isBlocked("ff02::1"))     << "multicast";
+    EXPECT_TRUE(p.isBlocked("240.0.0.1"))   << "reserved";
+}
+
+TEST(SsrfFromSettings, AllowPrivateStillHonoursTheOperatorsOwnEntries) {
+    const SsrfPolicy p = SsrfPolicy::fromSettings({"10.9.0.0/16"}, /*allowPrivate*/ true, nullptr);
+    EXPECT_TRUE(p.isBlocked("10.9.1.1")) << "an explicit block must survive allowPrivate";
+    EXPECT_FALSE(p.isBlocked("10.8.1.1")) << "the rest of RFC1918 is relaxed as asked";
+}
+
+TEST(SsrfFromSettings, ReportsUnparseableEntriesWithoutDroppingTheDefaults) {
+    std::vector<std::string> invalid;
+    const SsrfPolicy p = SsrfPolicy::fromSettings({"not-a-cidr", "10.9.0.0/16"}, false, &invalid);
+    ASSERT_EQ(invalid.size(), 1u);
+    EXPECT_EQ(invalid[0], "not-a-cidr");
+    EXPECT_TRUE(p.isBlocked("127.0.0.1")) << "a typo must not take the defaults with it";
+    EXPECT_TRUE(p.isBlocked("10.9.1.1"));
+}