Kaynağa Gözat

test: pin that credential collections are encrypted at rest

The database team found that their built-in sensitive-FIELD patterns
(`*.password`, `*.api_key`, `*.secret`, ...) require a dot before the
name, so a TOP-LEVEL field of those names is stored in plaintext. We
store `{"value": ...}` and `{"key": ...}` at the top level, and `key` is
not in those patterns at any nesting - so if we had relied on field
matching, every API key and project secret we hold would be readable
from a stolen data directory.

We do not: each store creates its collection with the COLLECTION-level
encrypted flag, which is independent of field names. This test pins
that, because it is one boolean in one line and the consequence of it
flipping is silent and total.

Each store is pointed at a FRESH collection rather than asserting on the
long-lived shared ones, because `encrypted` is a creation-time option -
asserting on pre-existing collections tests the history of a particular
database rather than the behaviour of this code. The falsifying half
asserts the function registry is NOT encrypted, so the test is detecting
the flag rather than finding everything encrypted for some other reason.

AND IT TURNED UP AN OPEN QUESTION, filed as #66. On the long-lived dev
database `default:vectorapi_settings` reports encrypted = false while
`default:vectorapi_keys` reports true - same kind of call, same flag,
added in the same commit. Since the flag is creation-time, some earlier
path or server version did not honour it and no later code change
repairs it. So whether PROD's vectorapi_settings - which holds the
global openai_api_key - is encrypted is unknown. It could not be settled
here: our API exposes the flag on no route, prod has no db-cli, and a
standalone probe segfaults on DbGateway construction.

1249/1249 green.
fszontagh 1 ay önce
ebeveyn
işleme
0f7c490c42
2 değiştirilmiş dosya ile 57 ekleme ve 0 silme
  1. 2 0
      CLAUDE.md
  2. 55 0
      tests/test_api_integration.cpp

+ 2 - 0
CLAUDE.md

@@ -83,6 +83,8 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **Files answer to the scope rules under the reserved `_files` pseudo-collection**, so `requireCapabilityCore` is the one implementation and file access cannot drift from collection access. The leading underscore makes it unshadowable - collection-create rejects `_`-prefixed names. `ctx.files` is **read only**: writing a tenant's asset is a management act and the HTTP route requires project-manage for it.
 - **Two different file size caps, answering two different questions.** `max_file_bytes` (global settings, default 2 MiB) bounds what can be STORED; `kCtxFileMaxBytes` (1 MiB) bounds what one function run may LOAD. A file stored when the limit was generous must not be able to pull megabytes into a 64 MiB JS heap on every run afterwards. The database imposes a cap of its own (`storage.files.max_file_size_mb`, default 500), which is far above either.
 - **A file upload does NOT replace by name at the database layer** - two uploads of one name leave two records - so `FileStore::put` deletes the previous ones itself, uploading FIRST so a failure leaves the old file intact. Reads take the NEWEST record, because an interrupted put can leave two and a read that picked arbitrarily would serve stale bytes some of the time.
+- **CREDENTIALS ARE PROTECTED BY COLLECTION-LEVEL ENCRYPTION, NOT BY FIELD NAMES, and that distinction saved us.** `vectorapi_keys`, `vectorapi_settings` and `<project>:vectorapi_secrets` are each created with `createCollection(..., encrypted=true, ...)`. The database also has built-in sensitive-FIELD patterns (`*.password`, `*.api_key`, `*.secret`, ...) - but they require a dot before the name, so a TOP-LEVEL field of those names is stored in PLAINTEXT, and we store `{"value": ...}` and `{"key": ...}` at the top level with `key` not in that list at any nesting. Had we relied on field matching, every API key and project secret would be readable from a stolen data directory. `EverySecretBearingSTOREcreatesANEncryptedCollection` pins the real mechanism by creating fresh collections through each store and asserting the flag, with a falsifying half asserting the function registry is plaintext.
+  **`encrypted` is a CREATION-TIME option, so this guarantee covers collections this code created and nothing else.** Measured on the long-lived dev database: `default:vectorapi_settings` reports `encrypted = false` while `default:vectorapi_keys` reports true, from the same kind of call with the same flag, added in the same commit - so some earlier path or server version did not honour it, and no later code change repairs an existing collection. **Whether PROD's `vectorapi_settings` (which holds the global `openai_api_key`) is encrypted is OPEN - see task #66.** Our API exposes the flag on no route, which is why it could not be answered over HTTP.
 - **Project secrets** live in `<project>:vectorapi_secrets`, encrypted and deliberately NOT in the collection registry - so the documents API and `ctx.collections` both 404 it, and even a policy granting every collection cannot read it. Writes are admin-only; no GET ever returns a value. A `SVAPI_FN_<project>__<NAME>` host variable WINS over a stored secret of the same name, which is the break-glass a stolen API credential cannot shadow.
 - **The runner SUBSCRIBES to project settings; it does not poll.** `ProjectWallMax` wraps a `SettingsStore` with `reloadAll()` plus `startWatch()`, so a changed cap reaches the next run immediately. It used to be a hand-rolled cache on a `project_budget_ttl_sec` TTL, which made clearing a cap look broken for up to 15 s and produced a false bug report. **`reloadAll()`, never `bootstrap()`** - bootstrap WRITES, seeding the settings document, and a runner must never author configuration it only reads.
 - **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.

+ 55 - 0
tests/test_api_integration.cpp

@@ -3597,3 +3597,58 @@ TEST_F(ApiFixture, AFilteredSearchREPORTSWhichPathAnsweredIt) {
     EXPECT_FALSE(j.at("scan_capped").get<bool>()) << j.dump();
     EXPECT_EQ(j.at("scanned"), 0) << j.dump();
 }
+
+TEST_F(ApiFixture, EverySecretBearingSTOREcreatesANEncryptedCollection) {
+    // Prompted by the database team finding that their built-in
+    // sensitive-FIELD patterns (`*.password`, `*.api_key`, `*.secret`, ...)
+    // need a dot before the name, so a TOP-LEVEL field of those names is
+    // stored in plaintext. We store `{"value": ...}` and `{"key": ...}` at the
+    // top level, and `key` is not in those patterns at any nesting - so if we
+    // relied on field matching, every credential we hold would be plaintext.
+    //
+    // We do not: each store creates its collection with the COLLECTION-level
+    // encrypted flag, which is independent of field names. This pins that,
+    // because it is one boolean in one line and the consequence of it flipping
+    // is every API key and project secret readable from a stolen data
+    // directory.
+    //
+    // Each store is pointed at a FRESH collection name rather than asserting
+    // on the long-lived shared ones. `encrypted` is a CREATION-TIME option, so
+    // a collection made before a store passed the flag - or by a database that
+    // ignored it - stays plaintext forever, and asserting on those would test
+    // the history of this dev database rather than the behaviour of this code.
+    // See the note below about the pre-existing one that is NOT encrypted.
+    const std::string suffix = std::to_string(::time(nullptr));
+
+    // bootstrap() is the creating call in each store. It writes a seed row,
+    // which is fine here: these collections are dropped below.
+    svapi::KeyStore keys(*db_, "enc_probe_keys_" + suffix);
+    keys.bootstrap("");
+    svapi::SettingsStore settings(*db_, "enc_probe_settings_" + suffix, "current");
+    settings.bootstrap("");
+
+    for (const auto& name : {"enc_probe_keys_" + suffix, "enc_probe_settings_" + suffix}) {
+        const auto info = db_->client().getCollectionInfo(svapi::qualify("default", name));
+        ASSERT_TRUE(info.has_value()) << name << " was not created";
+        EXPECT_TRUE(info->encrypted) << name << " holds credentials and is NOT encrypted at rest";
+        db_->client().dropCollection(svapi::qualify("default", name));
+    }
+
+    // The project secret store, through the real API so the route is covered
+    // too. Its collection is created per project by the fixture's own project.
+    auto c = admin();
+    const std::string secrets = "/api/v1/projects/" + project_ + "/secrets/PROBE_SECRET";
+    ASSERT_EQ(c.Put(secrets.c_str(), nlohmann::json{{"value","s3cret"}}.dump(),
+                    "application/json")->status / 100, 2);
+    const auto sec = db_->client().getCollectionInfo(svapi::qualify(project_, "vectorapi_secrets"));
+    ASSERT_TRUE(sec.has_value());
+    EXPECT_TRUE(sec->encrypted)
+        << "project secrets, including mail passwords, are NOT encrypted at rest";
+    c.Delete(secrets.c_str());
+
+    // The falsifying half: a collection with no credentials in it is NOT
+    // encrypted, so this is detecting the flag rather than finding everything
+    // encrypted for some unrelated reason.
+    const auto plain = db_->client().getCollectionInfo(svapi::qualify(project_, "vectorapi_functions"));
+    if (plain) EXPECT_FALSE(plain->encrypted) << "the function registry should be plaintext";
+}