Prechádzať zdrojové kódy

fix(functions): network_egress was written by the wrong handler

0.10.1 shipped the network_egress write inside the /settings/embeddings
PUT instead of the /settings/functions PUT. A scripted edit replaced the
first match of a line both handlers share, and I did not check which one
it landed in.

Two consequences, and the second is the serious one:

- On its documented route (/settings/functions, requireAdmin) the key was
  IGNORED. A `deny` answered 200 with "allow", and an unrecognised value
  answered 200 instead of 422 - a typo in an admin-only control looked
  like it had applied.
- On /settings/embeddings (requireProjectManage, NOT admin) it was
  WRITABLE. A project-manage key could therefore have re-enabled egress
  that an admin had denied, defeating the control.

Nothing was exploiting it: the default is allow and no project had a
value stored, so there was no live `deny` to undo. Found by the prod
acceptance checks for 0.10.1, not by the suite - nothing in the suite
drove the route, which is the actual gap.

Five integration tests, four of which fail against the shipped
arrangement and pass against this one. They assert that a deny persists
and is visible in the PUT's own response, that an unknown value is 422,
that the embeddings route cannot touch the key, and that clearing an
embedding override does not drop it.

A settings key is not finished until a test drives its ROUTE. And when
patching one of several near-identical handlers, assert which one the
edit reached.
fszontagh 1 mesiac pred
rodič
commit
5ee60ef2e9
5 zmenil súbory, kde vykonal 113 pridanie a 5 odobranie
  1. 1 0
      CLAUDE.md
  2. 1 1
      VERSION
  3. 1 1
      api/openapi.json
  4. 8 3
      src/handlers/project_settings.cpp
  5. 102 0
      tests/test_api_integration.cpp

+ 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.
+- **`network_egress` belongs to the `/settings/functions` PUT, which is `requireAdmin` - NOT the `/settings/embeddings` PUT, which is `requireProjectManage`.** It shipped in the wrong one in 0.10.1: a scripted edit replaced the first match of a line both handlers share, so an admin-only control was silently ignored on its documented route AND writable on a non-admin one, which would have let a project-manage key re-enable egress an admin had denied. The suite did not catch it because no test exercised the route at all; **prod acceptance did**, by noticing that a `deny` PUT answered `"allow"` and that an invalid value answered 200 instead of 422. Five integration tests now pin it, including that the embeddings route cannot touch it and that clearing an embedding override does not drop it. Two lessons: a settings key is not done until a test drives its ROUTE, and when patching one of several near-identical handlers, assert WHICH one the edit landed in.
 - **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.
 

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.10.1
+0.10.2

+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.10.1",
+    "version": "0.10.2",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {

+ 8 - 3
src/handlers/project_settings.cpp

@@ -179,9 +179,6 @@ 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");
@@ -239,6 +236,14 @@ void registerProjectSettingsRoutes(ApiServer& s) {
             }
         }
 
+        // THIS handler, not the embeddings one. The block was briefly in the
+        // embeddings PUT, which is requireProjectManage rather than
+        // requireAdmin - so an admin-only control was ignored on its own route
+        // and writable on a non-admin one, letting a project-manage key undo an
+        // admin's `deny`. Tests below pin both halves.
+        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");

+ 102 - 0
tests/test_api_integration.cpp

@@ -1303,6 +1303,108 @@ std::string projSettingsPath(const std::string& project) {
 }
 }  // namespace
 
+// --- network egress: an ADMIN-ONLY control on the FUNCTIONS route -----------
+//
+// These exist because the write landed in the wrong handler and shipped that
+// way. The embeddings PUT is requireProjectManage, the functions PUT is
+// requireAdmin, so the block being in the first one meant the control was
+// ignored on its documented route AND writable by a non-admin - which would
+// have let a project-manage key undo an admin's `deny`. Acceptance caught it on
+// prod; nothing in the suite did, because no test exercised the route.
+
+namespace {
+std::string fnSettingsPath(const std::string& project) {
+    return "/api/v1/projects/" + project + "/settings/functions";
+}
+}  // namespace
+
+TEST_F(ApiFixture, NetworkEgressDefaultsToAllowAndSaysItIsNotSet) {
+    auto c = admin();
+    auto r = c.Get(fnSettingsPath(project_).c_str());
+    ASSERT_EQ(r->status, 200);
+    auto j = nlohmann::json::parse(r->body);
+    EXPECT_EQ(j["network_egress"], "allow");
+    EXPECT_FALSE(j["network_egress_set"].get<bool>());
+}
+
+TEST_F(ApiFixture, NetworkEgressDenyActuallyPersistsOnTheFunctionsRoute) {
+    auto c = admin();
+    auto put = c.Put(fnSettingsPath(project_).c_str(),
+                     nlohmann::json{{"network_egress", "deny"}}.dump(), "application/json");
+    ASSERT_EQ(put->status, 200) << put->body;
+    // The PUT's own response must already show it - it returned "allow" while
+    // silently discarding the write, which is how this got to prod.
+    auto pj = nlohmann::json::parse(put->body);
+    EXPECT_EQ(pj["network_egress"], "deny") << put->body;
+    EXPECT_TRUE(pj["network_egress_set"].get<bool>());
+    // And it must still be there on a fresh read.
+    auto j = nlohmann::json::parse(c.Get(fnSettingsPath(project_).c_str())->body);
+    EXPECT_EQ(j["network_egress"], "deny");
+    EXPECT_TRUE(j["network_egress_set"].get<bool>());
+
+    // null clears it back to inherit.
+    ASSERT_EQ(c.Put(fnSettingsPath(project_).c_str(),
+                    nlohmann::json{{"network_egress", nullptr}}.dump(),
+                    "application/json")->status, 200);
+    auto j2 = nlohmann::json::parse(c.Get(fnSettingsPath(project_).c_str())->body);
+    EXPECT_EQ(j2["network_egress"], "allow");
+    EXPECT_FALSE(j2["network_egress_set"].get<bool>());
+}
+
+TEST_F(ApiFixture, NetworkEgressRejectsAValueItDoesNotUnderstand) {
+    auto c = admin();
+    auto r = c.Put(fnSettingsPath(project_).c_str(),
+                   nlohmann::json{{"network_egress", "maybe"}}.dump(), "application/json");
+    // 200 here means the key was ignored, which is exactly the failure that
+    // shipped: a typo in an admin-only control must not look like it applied.
+    EXPECT_EQ(r->status, 422) << r->body;
+}
+
+TEST_F(ApiFixture, TheEmbeddingsRouteCannotTouchNetworkEgress) {
+    // The security half. The embeddings route is project-manage, so if it
+    // honoured this key a tenant could re-enable egress an admin had denied.
+    auto c = admin();
+    ASSERT_EQ(c.Put(fnSettingsPath(project_).c_str(),
+                    nlohmann::json{{"network_egress", "deny"}}.dump(),
+                    "application/json")->status, 200);
+
+    auto put = c.Put(projSettingsPath(project_).c_str(),
+                     nlohmann::json{{"network_egress", "allow"},
+                                    {"default_embedding_model", "text-embedding-3-large"}}
+                         .dump(),
+                     "application/json");
+    ASSERT_EQ(put->status, 200) << put->body;
+
+    // The embedding override applied; the egress key was ignored, and the
+    // admin's deny SURVIVED rather than being overwritten.
+    auto j = nlohmann::json::parse(c.Get(fnSettingsPath(project_).c_str())->body);
+    EXPECT_EQ(j["network_egress"], "deny") << "the embeddings route overwrote an admin-only control";
+    EXPECT_TRUE(j["network_egress_set"].get<bool>());
+
+    c.Put(fnSettingsPath(project_).c_str(), nlohmann::json{{"network_egress", nullptr}}.dump(),
+          "application/json");
+    c.Delete(projSettingsPath(project_).c_str());
+}
+
+TEST_F(ApiFixture, ClearingAnEmbeddingOverrideDoesNotDropNetworkEgress) {
+    // DELETE /settings/embeddings clears the EMBEDDING fields only. It used to
+    // delete the whole document, which silently dropped a function policy; the
+    // egress switch lives in the same document and must survive too.
+    auto c = admin();
+    ASSERT_EQ(c.Put(fnSettingsPath(project_).c_str(),
+                    nlohmann::json{{"network_egress", "deny"}}.dump(),
+                    "application/json")->status, 200);
+    ASSERT_EQ(c.Put(projSettingsPath(project_).c_str(),
+                    nlohmann::json{{"default_embedding_model", "text-embedding-3-large"}}.dump(),
+                    "application/json")->status, 200);
+    ASSERT_EQ(c.Delete(projSettingsPath(project_).c_str())->status, 200);
+
+    auto j = nlohmann::json::parse(c.Get(fnSettingsPath(project_).c_str())->body);
+    EXPECT_EQ(j["network_egress"], "deny") << "clearing embeddings took the egress setting with it";
+    c.Put(fnSettingsPath(project_).c_str(), nlohmann::json{{"network_egress", nullptr}}.dump(),
+          "application/json");
+}
+
 TEST_F(ApiFixture, ProjectSettingsDefaultToInherited) {
     auto c = admin();
     auto r = c.Get(projSettingsPath(project_).c_str());