Переглянути джерело

feat(functions): let an admin deny a project the network, both surfaces

An operator could narrow where a function may go (the egress CIDR
blocklist is global) but could not say "this tenant may not reach the
network at all". network_egress on PUT /projects/{p}/settings/functions
is that switch: "allow", "deny" or null to inherit, admin only.

ONE gate for ctx.fetch AND ctx.mail. Gating one and not the other would
let an operator believe a tenant was offline while the other surface
stayed open, and mail is the one carrying credentials.

Checked before the SSRF classifier and before any name resolution, so a
denied project emits no DNS query either - a lookup is an observable
side effect and a channel of its own.

Deliberately NOT a `_network` pseudo-collection scope rule. A scope rule
answers "may this principal touch that data of ours", which is why
_files is one; reaching a third party the tenant already holds
credentials for is a capability, not an access decision. A
pseudo-collection would also put it in range of a `*` rule, which is
exactly the widening that had to be fixed once already.

The default is ALLOW, for compatibility rather than preference:
ctx.fetch shipped with no gate, so a default of deny would stop every
already-deployed function that makes an outbound call at the moment this
field arrived - an outage caused by adding a control, which is not an
acceptable way to introduce one. The control that was missing is the
ability to revoke, and that is what this provides.
kFunctionNetworkEgressDefault is pinned by a test so flipping it has to
be deliberate, the same reason builtinDefaultFunctionPolicy() has one.

The runner needed its own test seam. Riding on egressPolicy would not
do: that flag means "there is no database to read", so a test setting it
would SKIP this gate while appearing to exercise it, leaving it with no
coverage at all.

Eleven tests, in pairs: each denial is matched by a case proving the
surface still works when allowed, including a real socket and a real
IMAP login - a gate that refused everything would pass every denial test
while taking the feature offline.

GET also returns network_egress_set, so a UI can tell "chosen here" from
"inherited" and render three states rather than two.

1189/1189 green.
fszontagh 1 місяць тому
батько
коміт
e5a1af6259

+ 1 - 0
CLAUDE.md

@@ -80,6 +80,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **The runner's `runtime` ceilings are boot-time only**, unlike every hot-reloading setting in the server: QuickJS fixes a runtime's memory limit at creation, so changing one live would mean draining and recreating the whole pool. Editing them means restarting the runner - cheap, because vectorapi answers 503 for that moment and stores nothing unvalidated. By contrast `function_egress_blocked_cidrs` / `function_egress_allow_private` DO hot-reload, because they are read per run.
 - **`ctx.env` comes from the runner's environment, scoped per project**: `SVAPI_FN_<project>__<NAME>` in `/etc/smartbotic-vectorapi/runner.env` reaches that project's functions as `ctx.env.<NAME>`. The project is part of the variable name because one runner serves every project; nothing outside the `SVAPI_FN_` prefix is ever exposed, so the runner's own token and database address stay invisible to functions. Matched exactly and case-sensitively; the split is at the **first** `__`, so a project whose name contains `__` cannot carry secrets.
 - **The runner authenticates a shared bearer token and fails closed.** No token plus a non-loopback bind address means it **refuses to start**. `isLoopbackBind()` answers "not loopback" for anything it cannot parse, so an unrecognised address produces the refusal. The comparison is constant-time, `/health` is authenticated too, and both sides prefer `SVAPI_RUNNER_TOKEN` in the `.env` over the conffile.
+- **A project can be denied the network outright, and ONE setting covers both outbound surfaces.** `network_egress` on `PUT /projects/{p}/settings/functions` (admin only, stored as `function_network_egress`) gates `ctx.fetch` AND `ctx.mail` through one `requireNetworkEgress()`, checked **before the SSRF classifier and before any resolution** - a denied project must not emit a DNS query either, since a lookup is an observable side effect and a channel of its own. Gating one surface and not the other would let an operator believe a tenant was offline while the other stayed open, and mail is the one carrying credentials. **It is NOT a `_network` pseudo-collection scope rule**: a scope rule answers "may this principal touch that data of ours", which is why `_files` is one, whereas reaching a third party the tenant already has credentials for is a capability rather than an access decision - and a pseudo-collection would put it in range of a `*` rule, exactly the widening that had to be fixed once already. **The default is ALLOW** (`kFunctionNetworkEgressDefault`, pinned by a test): `ctx.fetch` shipped ungated, so a default of deny would break every deployed function that fetches the moment the setting appeared, which is an outage caused by ADDING a control. The control that was missing is the ability to revoke. Note the runner needs its own test seam (`HostContextConfig::networkEgress`) rather than riding on `egressPolicy`, because that one means "there is no database to read" and a test setting it would skip the gate while appearing to exercise it.
 - **`ctx.fetch` egress goes through the SSRF guard** (`functions/net_guard.hpp`): fail closed on anything unparseable, and classify **every** address a name resolves to, not the first. A settings blocklist is **UNIONED** with the built-in defaults by `SsrfPolicy::fromSettings()`, never substituted for them - an operator adding one CIDR must not silently reopen loopback, RFC1918 and the metadata endpoint. `function_egress_allow_private` is the explicit opt-out and relaxes **only** `privateBlockedCidrs()`; 169.254.0.0/16, link-local, multicast, reserved space and the IPv6 spellings of an IPv4 destination (NAT64, 6to4, `::/96`) stay blocked whatever it is set to. Note the opt-out does expose loopback, where our own API listens.
 
 ## Mail surface (`ctx.mail`, IMAP + SMTP)

+ 1 - 0
api/llms.txt

@@ -228,6 +228,7 @@ 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 project can be denied the network entirely.** `PUT /api/v1/projects/{p}/settings/functions` with `{"network_egress":"deny"}` (admin only) stops **both** `ctx.fetch` and `ctx.mail` for that project, refused as `egress_blocked` **before any name is resolved** - so a denied project emits no DNS query either. `"allow"` restores it, `null` inherits. The GET returns the effective value plus `network_egress_set`, which says whether it was chosen for the project or inherited. The default is **allow**, for compatibility rather than preference: `ctx.fetch` shipped with no gate, so defaulting to deny would have stopped every already-deployed function that makes an outbound call. One setting covers both surfaces on purpose - gating one and not the other would let an operator believe a tenant was offline while the other stayed open.
 - **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.

+ 5 - 5
api/openapi.json

@@ -2943,8 +2943,8 @@
         "tags": [
           "Settings"
         ],
-        "summary": "Per-project function limits",
-        "description": "The project's wall-time cap, per run kind: {\"max_wall_time_ms\": {\"http\": n|null, \"job\": n|null}}. Always the object form - a single number cannot express \"10s for routes, 60s for jobs\", and keeping the old scalar would let a client that reads only it see null (no cap) while a cap was in force.",
+        "summary": "Per-project function limits and network egress",
+        "description": "The project's wall-time cap, per run kind, and whether its functions may reach the network: {\"max_wall_time_ms\": {\"http\": n|null, \"job\": n|null}, \"network_egress\": \"allow\"|\"deny\", \"network_egress_set\": bool}. max_wall_time_ms is always the object form - a single number cannot express \"10s for routes, 60s for jobs\", and keeping the old scalar would let a client that reads only it see null (no cap) while a cap was in force. network_egress is the EFFECTIVE value and never null, because an admin asking whether a project can reach the network wants the answer rather than \"nothing is stored\"; network_egress_set says whether it was chosen for this project or inherited, which is what a tri-state control needs.",
         "parameters": [
           {
             "name": "project",
@@ -2975,8 +2975,8 @@
         "tags": [
           "Settings"
         ],
-        "summary": "Set the per-project function wall-time cap",
-        "description": "Admin only, because it decides how long one project may hold a pooled runtime - and therefore how long it can delay every other project's interactive routes. Send null to inherit.",
+        "summary": "Set the per-project function wall-time cap or network egress",
+        "description": "Admin only. The wall-time cap decides how long one project may hold a pooled runtime, and therefore how long it can delay every other project's interactive routes. network_egress takes \"allow\", \"deny\" or null (inherit) and governs BOTH outbound surfaces, ctx.fetch and ctx.mail - gating one and not the other would let an operator believe a tenant was offline while the other stayed open. It is refused before any name is resolved, so a denied project emits no DNS query either. The default when nothing is stored is \"allow\", for compatibility: ctx.fetch shipped ungated, so a default of deny would have stopped every already-deployed function that makes an outbound call. Send null to inherit.",
         "parameters": [
           {
             "name": "project",
@@ -4821,4 +4821,4 @@
       }
     }
   }
-}
+}

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

@@ -88,6 +88,15 @@ struct HostContextConfig {
     /// not "handle the error".
     std::shared_ptr<const functions::SsrfPolicy> egressPolicy;
 
+    /// Whether this project may reach the network at all, when known already.
+    ///
+    /// Null in production, where the answer comes from the project's settings
+    /// document. It needs a seam of its OWN rather than riding on
+    /// `egressPolicy`: that one means "do not read a database", and a test
+    /// setting it would silently skip this gate instead of exercising it - so
+    /// the gate would have no coverage at all while looking as though it had.
+    std::optional<bool> networkEgress;
+
     /// Where ctx.jobs.enqueue goes. NULL means functions cannot enqueue, and
     /// ctx.jobs.enqueue refuses with `jobs_unavailable` - the same posture as a
     /// runner installed with no endpoints configured: a capability that was

+ 33 - 0
runner/src/host_context.cpp

@@ -1545,6 +1545,37 @@ struct HostContext::Impl {
     /// 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.
+    /// Refuse the whole outbound surface when the project's settings say so.
+    ///
+    /// Checked BEFORE the SSRF classifier and before any name resolution: a
+    /// project that may not reach the network must not even emit a DNS query,
+    /// which is itself an observable side effect and a channel.
+    ///
+    /// One gate for `ctx.fetch` AND `ctx.mail`, deliberately. Gating only one
+    /// would let an operator believe a tenant was offline while the other
+    /// surface stayed open, and the newer surface is not the more dangerous
+    /// one. An injected egress policy means the tests run without a database,
+    /// so that path skips the settings read exactly as `ssrfPolicy()` does.
+    void requireNetworkEgress(const std::string& host) {
+        bool allowed = kFunctionNetworkEgressDefault;
+        if (config.networkEgress) {
+            allowed = *config.networkEgress;
+        } else if (config.egressPolicy) {
+            // An injected policy means "there is no database to read", so the
+            // stored setting is unreachable and the default stands.
+            return;
+        } else {
+            loadSettings();
+            allowed = functionNetworkEgressAllowed(projectEmbedding ? &*projectEmbedding : nullptr);
+        }
+        if (allowed) return;
+        const std::string reason = "this project's functions may not reach the network "
+                                   "(network_egress is set to deny for project '" +
+                                   config.project + "'); refused before resolving '" + host + "'";
+        blocked.push_back(reason);
+        throw ApiError(ErrCode::Forbidden, "egress_blocked", reason);
+    }
+
     const functions::SsrfPolicy& ssrfPolicy() {
         if (!ssrfCached) {
             // An injected policy means no settings read, which is what lets the
@@ -2001,6 +2032,7 @@ struct HostContext::Impl {
             throw ApiError(ErrCode::Forbidden, "egress_blocked", reason);
         }
 
+        requireNetworkEgress(parts->host);
         auto decision =
             hostdetail::decideEgress(parts->host, ssrfPolicy(), hostdetail::resolveWithGetaddrinfo);
         if (!decision.allowed) {
@@ -2432,6 +2464,7 @@ struct HostContext::Impl {
         // directly, a name is resolved EXACTLY ONCE and every address it returns
         // is classified. The approved address is then pinned for the transport,
         // because re-resolving IS the rebinding window.
+        requireNetworkEgress(s.account.host);
         auto decision = hostdetail::decideEgress(s.account.host, ssrfPolicy(),
                                                  hostdetail::resolveWithGetaddrinfo);
         if (!decision.allowed) {

+ 90 - 0
runner/tests/host_context_test.cpp

@@ -1900,3 +1900,93 @@ TEST(HostContextMail, AnHonestBodyEndingInAParenAndCrlfIsStillDelivered) {
     EXPECT_NE(value.dump().find("as it should"), std::string::npos) << value.dump();
     server.stop();
 }
+
+// ------------------------------------------------- the network egress gate
+//
+// One gate for BOTH outbound surfaces. The tests come in pairs on purpose: a
+// gate is only proven by showing it refuses when set to deny AND lets the call
+// through when it is not, because a gate that refused everything would pass
+// every denial test while taking the whole feature offline.
+
+TEST(HostContextEgressGate, CtxFetchIsRefusedWhenTheProjectMayNotReachTheNetwork) {
+    HostContextConfig cfg = httpTrigger({});
+    cfg.networkEgress = false;
+    auto out = runScript(std::move(cfg),
+                         catching("ctx.fetch('https://example.com/')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), true) << out.result.value.dump();
+    EXPECT_EQ(out.result.value.at("code"), "egress_blocked") << out.result.value.dump();
+    EXPECT_NE(out.result.value.at("message").get<std::string>().find("network_egress"),
+              std::string::npos)
+        << out.result.value.dump();
+}
+
+TEST(HostContextEgressGate, CtxMailIsRefusedByTheSameGate) {
+    // The point of the shared gate: an operator who denies a tenant the network
+    // must not find the OTHER outbound surface still open. Gating only
+    // ctx.fetch would let the two drift, and mail carries credentials.
+    HostContextConfig cfg = mailTrigger();
+    cfg.networkEgress = false;
+    auto out = runScript(std::move(cfg),
+                         catching("ctx.mail.read({ host: '127.0.0.1', port: 1143,"
+                                  "  tls: false, user: 'u', password: 'p' })"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), true) << out.result.value.dump();
+    EXPECT_EQ(out.result.value.at("code"), "egress_blocked") << out.result.value.dump();
+    EXPECT_NE(out.result.value.at("message").get<std::string>().find("network_egress"),
+              std::string::npos)
+        << out.result.value.dump();
+}
+
+TEST(HostContextEgressGate, TheRefusalHappensBeforeAnyNameIsResolved) {
+    // A project that may not reach the network must not emit a DNS query
+    // either: a lookup is an observable side effect and a channel of its own.
+    // A hostname that cannot resolve would report a resolution failure if the
+    // gate ran too late, so the slug tells the two apart.
+    HostContextConfig cfg = httpTrigger({});
+    cfg.networkEgress = false;
+    auto out = runScript(
+        std::move(cfg),
+        catching("ctx.fetch('https://this-name-does-not-exist.invalid/')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), true) << out.result.value.dump();
+    EXPECT_EQ(out.result.value.at("code"), "egress_blocked") << out.result.value.dump();
+    EXPECT_NE(out.result.value.at("message").get<std::string>().find("refused before resolving"),
+              std::string::npos)
+        << out.result.value.dump();
+}
+
+TEST(HostContextEgressGate, MailStillWorksWhenEgressIsAllowed) {
+    // The falsifying half, and the one that matters most: `allow` must leave
+    // the surface fully working. Asserted against a real socket and a real
+    // login rather than by checking an error message changed.
+    svapi::testing::FakeImapServer server;
+    ASSERT_TRUE(server.start());
+    HostContextConfig cfg = mailTrigger();
+    cfg.networkEgress = true;
+    auto out = runScript(std::move(cfg),
+                         withPort(catching("ctx.mail.read({ host: '127.0.0.1', port: %PORT%,"
+                                           "  tls: false, user: 'u', password: 'p' })"),
+                                  server.port()));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), false) << out.result.value.dump();
+    server.stop();
+}
+
+TEST(HostContextEgressGate, AnUnsetGateLeavesTheSsrfGuardAsTheOnlyRefusal) {
+    // With no project setting, behaviour must be exactly what shipped: the
+    // SSRF classifier still refuses a private address, and the refusal must be
+    // ITS reason rather than the new gate's - otherwise the default would have
+    // quietly become deny.
+    HostContextConfig cfg = httpTrigger({});
+    cfg.egressPolicy = std::make_shared<const svapi::functions::SsrfPolicy>(
+        svapi::functions::SsrfPolicy::withDefaults());
+    ASSERT_FALSE(cfg.networkEgress.has_value());
+    auto out = runScript(std::move(cfg), catching("ctx.fetch('http://169.254.169.254/latest/')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(out.result.value.at("threw"), true) << out.result.value.dump();
+    EXPECT_EQ(out.result.value.at("code"), "egress_blocked") << out.result.value.dump();
+    EXPECT_EQ(out.result.value.at("message").get<std::string>().find("network_egress"),
+              std::string::npos)
+        << "the default must not be deny: " << out.result.value.dump();
+}

+ 26 - 1
src/handlers/project_settings.cpp

@@ -95,7 +95,29 @@ nlohmann::json budgetJson(const ProjectSettings* p) {
     // shape changed is better than being told the wrong answer.
     return {{"max_wall_time_ms",
              {{"http", httpMs > 0 ? nlohmann::json(httpMs) : nlohmann::json(nullptr)},
-              {"job", jobMs > 0 ? nlohmann::json(jobMs) : nlohmann::json(nullptr)}}}};
+              {"job", jobMs > 0 ? nlohmann::json(jobMs) : nlohmann::json(nullptr)}}},
+            // The EFFECTIVE value, never null: an admin asking whether this
+            // project can reach the network wants the answer, not "nothing is
+            // stored". `network_egress_set` says whether it was chosen here or
+            // inherited, which is the part a UI needs to render a tri-state.
+            {"network_egress", functionNetworkEgressAllowed(p) ? "allow" : "deny"},
+            {"network_egress_set", p != nullptr && p->functionNetworkEgress.has_value()}};
+}
+
+/// Read `network_egress` out of a PUT body. nullopt means "clear it".
+///
+/// A string rather than a bool, because `false` reads as a value and `"deny"`
+/// reads as an instruction - and because the pair allow/deny cannot be
+/// misremembered the way a bool named for one side can.
+std::optional<bool> egressFromJson(const nlohmann::json& v) {
+    if (v.is_null()) return std::nullopt;
+    if (v.is_string()) {
+        const std::string s = v.get<std::string>();
+        if (s == "allow") return true;
+        if (s == "deny") return false;
+    }
+    throw ApiError(ErrCode::Unprocessable, "validation",
+                   "network_egress must be \"allow\", \"deny\" or null");
 }
 
 /// Read one kind's cap out of a PUT body value. Returns nullopt for "clear it".
@@ -157,6 +179,9 @@ void registerProjectSettingsRoutes(ApiServer& s) {
         // Nothing stored at all: drop the document so the project plainly
         // inherits. hasAnyOverrides, not hasEmbeddingOverrides - clearing an
         // embedding override must not take a function policy with it.
+        if (body.contains("network_egress"))
+            updated.functionNetworkEgress = egressFromJson(body.at("network_egress"));
+
         if (!updated.hasAnyOverrides()) d->settings.removeProject(project);
         else if (!d->settings.saveProject(updated))
             throw ApiError(ErrCode::Unavailable, "db_error", "could not save project settings");

+ 10 - 0
src/project_settings.cpp

@@ -44,6 +44,10 @@ ProjectSettings ProjectSettings::fromJson(const nlohmann::json& j) {
     if (j.contains("max_function_wall_time_job_ms") &&
         j.at("max_function_wall_time_job_ms").is_number_integer())
         p.maxFunctionWallTimeJobMs = j.at("max_function_wall_time_job_ms").get<int64_t>();
+    // Absent stays absent, which reads as the default rather than as a denial:
+    // an older stored document must not come back meaning "no network".
+    if (j.contains("function_network_egress") && j.at("function_network_egress").is_boolean())
+        p.functionNetworkEgress = j.at("function_network_egress").get<bool>();
     return p;
 }
 
@@ -64,6 +68,7 @@ nlohmann::json ProjectSettings::toJson() const {
     // enforcing none. Deliberately the tighter one: a rollback that loosens a
     // limit an admin set is the failure worth avoiding, and an over-tight job
     // budget is visible and complained about, where an over-loose one is not.
+    if (functionNetworkEgress) j["function_network_egress"] = *functionNetworkEgress;
     if (maxFunctionWallTimeHttpMs && maxFunctionWallTimeJobMs)
         j["max_function_wall_time_ms"] =
             std::min(*maxFunctionWallTimeHttpMs, *maxFunctionWallTimeJobMs);
@@ -74,6 +79,11 @@ nlohmann::json ProjectSettings::toJson() const {
     return j;
 }
 
+bool functionNetworkEgressAllowed(const ProjectSettings* proj) {
+    if (proj == nullptr || !proj->functionNetworkEgress) return kFunctionNetworkEgressDefault;
+    return *proj->functionNetworkEgress;
+}
+
 std::string projectSettingsDocId(const std::string& project) { return "project_" + project; }
 
 ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectSettings* proj,

+ 44 - 1
src/project_settings.hpp

@@ -59,6 +59,28 @@ struct ProjectSettings {
     std::optional<int64_t> maxFunctionWallTimeHttpMs;
     std::optional<int64_t> maxFunctionWallTimeJobMs;
 
+    /// Whether this project's functions may reach the network at all.
+    ///
+    /// Unset means ALLOWED, which is deliberate and is the only answer that
+    /// does not break what is already deployed: `ctx.fetch` has shipped
+    /// ungated, so a default of deny would stop every existing function that
+    /// makes an outbound call the moment this field arrived. A capability that
+    /// is on and revocable is the honest shape for that - see
+    /// `kFunctionNetworkEgressDefault`, which a test pins so that changing the
+    /// floor has to be a deliberate act rather than a side effect.
+    ///
+    /// It is a SEPARATE setting rather than a `_network` pseudo-collection
+    /// scope rule. A scope rule answers "may this principal touch that data of
+    /// ours", which is why `_files` is one; reaching a third party the tenant
+    /// already holds credentials for is a capability, not an access decision,
+    /// and expressing it as a pseudo-collection would also put it in range of a
+    /// `*` rule - exactly the widening that had to be fixed once already.
+    ///
+    /// Admin-only, and it governs BOTH outbound surfaces - `ctx.fetch` and
+    /// `ctx.mail`. Gating only one of them would let the two drift, and the
+    /// newer surface is not the more dangerous one.
+    std::optional<bool> functionNetworkEgress;
+
     /// True when at least one EMBEDDING field overrides the global value.
     bool hasEmbeddingOverrides() const {
         return !openaiApiBase.empty() || !openaiApiKey.empty() || !defaultEmbeddingModel.empty() ||
@@ -71,7 +93,8 @@ struct ProjectSettings {
     /// function policy the moment someone cleared an embedding override.
     bool hasAnyOverrides() const {
         return hasEmbeddingOverrides() || defaultFunctionPolicy.has_value() ||
-               maxFunctionWallTimeHttpMs.has_value() || maxFunctionWallTimeJobMs.has_value();
+               maxFunctionWallTimeHttpMs.has_value() || maxFunctionWallTimeJobMs.has_value() ||
+               functionNetworkEgress.has_value();
     }
 
     /// A project base URL must carry its own API key, otherwise the global
@@ -83,6 +106,26 @@ struct ProjectSettings {
     nlohmann::json toJson() const;
 };
 
+/// Whether a function may make an outbound call when no project says otherwise.
+///
+/// TRUE, and the reason is compatibility rather than preference: `ctx.fetch`
+/// shipped with no gate, so a default of false would break every deployed
+/// function that fetches at the moment this setting appeared - an outage caused
+/// by adding a control, which is not an acceptable way to introduce one. The
+/// control an operator was missing is the ability to REVOKE, and that is what
+/// this provides.
+///
+/// A test asserts this value. Flipping it is a security-posture change for
+/// every existing deployment and must be a deliberate act with a migration,
+/// never a quiet edit - the same reason `builtinDefaultFunctionPolicy()` has a
+/// test pinning its floor.
+inline constexpr bool kFunctionNetworkEgressDefault = true;
+
+/// Whether `proj` allows its functions to reach the network. Null is the
+/// default, so a project with no stored settings behaves as it did before the
+/// setting existed.
+bool functionNetworkEgressAllowed(const ProjectSettings* proj);
+
 /// Document id holding `project`'s overrides. Prefixed so it can never collide
 /// with the global settings document ("current").
 std::string projectSettingsDocId(const std::string& project);

+ 59 - 0
tests/test_project_settings.cpp

@@ -392,3 +392,62 @@ TEST(MaxFunctionWallTime, ABudgetOnlyProjectIsNotTreatedAsEmpty) {
     EXPECT_TRUE(job.hasAnyOverrides());
     EXPECT_FALSE(job.hasEmbeddingOverrides());
 }
+
+// --------------------------------------------------- function network egress
+
+TEST(ProjectSettingsEgress, TheDefaultIsAllowAndThatIsPinnedOnPurpose) {
+    // This value is a security posture for EVERY existing deployment. It is
+    // true for compatibility, not preference: ctx.fetch shipped with no gate,
+    // so a default of deny would break every deployed function that fetches at
+    // the moment the setting appeared - an outage caused by ADDING a control.
+    //
+    // Flipping it must therefore be a deliberate act with a migration, never a
+    // quiet edit, which is what this assertion is for. The same reason
+    // builtinDefaultFunctionPolicy() has a test pinning its floor.
+    EXPECT_TRUE(svapi::kFunctionNetworkEgressDefault);
+}
+
+TEST(ProjectSettingsEgress, AProjectWithNoSettingsBehavesAsItDidBefore) {
+    EXPECT_TRUE(svapi::functionNetworkEgressAllowed(nullptr));
+    svapi::ProjectSettings p;
+    EXPECT_TRUE(svapi::functionNetworkEgressAllowed(&p));
+}
+
+TEST(ProjectSettingsEgress, DenyAndAllowAreBothHonoured) {
+    svapi::ProjectSettings p;
+    p.functionNetworkEgress = false;
+    EXPECT_FALSE(svapi::functionNetworkEgressAllowed(&p));
+    p.functionNetworkEgress = true;
+    EXPECT_TRUE(svapi::functionNetworkEgressAllowed(&p));
+}
+
+TEST(ProjectSettingsEgress, ItSurvivesARoundTripThroughJson) {
+    svapi::ProjectSettings p;
+    p.project = "acme";
+    p.functionNetworkEgress = false;
+    const svapi::ProjectSettings back = svapi::ProjectSettings::fromJson(p.toJson());
+    ASSERT_TRUE(back.functionNetworkEgress.has_value());
+    EXPECT_FALSE(*back.functionNetworkEgress);
+}
+
+TEST(ProjectSettingsEgress, AnUnsetValueIsNotWrittenAndComesBackUnset) {
+    // An absent key must read as "inherit", never as "deny": a document stored
+    // before this setting existed must not come back meaning no network.
+    svapi::ProjectSettings p;
+    p.project = "acme";
+    EXPECT_FALSE(p.toJson().contains("function_network_egress"));
+    const svapi::ProjectSettings back = svapi::ProjectSettings::fromJson(p.toJson());
+    EXPECT_FALSE(back.functionNetworkEgress.has_value());
+    EXPECT_TRUE(svapi::functionNetworkEgressAllowed(&back));
+}
+
+TEST(ProjectSettingsEgress, SettingItAloneCountsAsAnOverrideSoTheDocumentIsKept) {
+    // hasAnyOverrides() decides whether the settings document is DELETED, so a
+    // field missing from it is a setting that silently vanishes.
+    svapi::ProjectSettings p;
+    EXPECT_FALSE(p.hasAnyOverrides());
+    p.functionNetworkEgress = false;
+    EXPECT_TRUE(p.hasAnyOverrides());
+    // ...and it is not an embedding override, so clearing those must not drop it.
+    EXPECT_FALSE(p.hasEmbeddingOverrides());
+}