Procházet zdrojové kódy

fix(security): the encrypted flag was asked for and never applied

KeyStore::bootstrap and SettingsStore::bootstrap guarded their
createCollection with "does this collection already exist", which skipped
it in exactly the case that needed it: a collection created implicitly by
an earlier write, carrying the default flag of false. Measured on the dev
database, vectorapi_keys and vectorapi_settings report encrypted: no while
both call sites read as though they had asked for true.

That is about to matter. Database 2.17.0 encrypts a collection's rows from
this flag, and the built-in sensitive-name patterns cannot cover for it
because they match a whole path segment while the secrets are stored under
'key' and 'openai_api_key'. A collection left plain would stay plaintext
through the migration and afterwards.

Both bootstraps now call createCollection unconditionally. Re-issuing it
switches encryption on for an existing collection from 2.17.0 and can never
switch it off; older servers treat it as a no-op. Checked rather than
assumed before shipping: the existing-collection path acts only on a vector
dimension above zero and on the default TTL, we pass zero for every option
but the flag, and the upgrade only ever flips false to true.

ProjectSecretStore::ensure keeps its guard deliberately, and the stale
comment claiming the flag is fixed at creation is corrected. It runs on
every secret read and CreateCollection is refused by a read-only database,
so making it unconditional would turn a function run into a 503 during
recovery. Its collection is measured encrypted: yes already.

The new test carries a control collection that is never bootstrapped, so
the assertion cannot pass for an unrelated reason, and it asserts the
pre-existing row survives the re-call. It skips with an explicit message on
a server that cannot perform the upgrade, since that half is the database's
behaviour and not ours.

Also recorded: a tenant can now reach encrypted_field through the index
route, where the refusal arrives as success=false with the reason
discarded, so we answer 503 for something no retry can fix.

1253/1253 green.
fszontagh před 1 měsícem
rodič
revize
3d4a8483e8

+ 5 - 1
CLAUDE.md

@@ -90,7 +90,11 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   Until the database ships encryption at rest, the only reliable protection is encrypting CLIENT-SIDE before the value is stored.
   **THE COMING FIX IS SAFE FOR US, and the reason is worth keeping because it is not obvious: NOTHING queries a credential collection by value.** The database asked before releasing, because full-value encryption uses a random IV, so a FILTER on an encrypted field never matches and an INDEX on one indexes ciphertext. Audited: `KeyStore::lookup()` scans an IN-MEMORY snapshot (`k.key == key`) loaded by a `find()` carrying only a limit, so authentication is a full read compared in process - it never asks the database to match a key. Settings and project secrets are addressed by DOCUMENT ID throughout (the secret's NAME is its id). The global settings document is told apart from the per-project ones by `p.project.empty()`, evaluated in our process after a full read, which LOOKS like a value query and is not. `opts.filters` is set in exactly three places service-wide - `vector_search.cpp`, `function_run_log.cpp` (`function_id`) and `host_context.cpp` (`ctx.collections`) - none of them a credential collection, and no index is declared on any of the three.
   **The adjacent hazard that WOULD break: `vectorapi_function_runs` is filtered by `function_id`.** It, the job queue, the function registry and the collection registry are all deliberately `encrypted=false`, and user collections are always created `encrypted=false` (`handlers/collections.cpp:74`) so a user's index is never over ciphertext. If anyone ever flips the flag on those, that filter stops matching silently.
-  Our startup already calls `createCollection(..., encrypted=true, ...)` unconditionally, so once the database lets that switch the flag on an EXISTING collection, the three repair themselves on the next restart - by accident rather than by design, so verify it with the canary rather than assuming it.
+  **THE FLAG WAS ASKED FOR AND NEVER APPLIED, AND THIS NOTE USED TO CLAIM THE OPPOSITE.** It said our startup calls `createCollection(..., encrypted=true, ...)` "unconditionally", so the three stores would "repair themselves on the next restart". Both halves were false. Every call site was guarded by `if (!getCollectionInfo(...).has_value())`, so the create was skipped for a collection that ALREADY EXISTED - which is exactly the case that needed it, because the collection had been created implicitly by an earlier write, with the default flag of `false`. Measured on the dev database: `vectorapi_keys` and `vectorapi_settings` report `encrypted: no` while the code reads as though it had asked for `true`, and only `<project>:vectorapi_secrets` (a later store, whose collection our code did create) reports `yes`. A guard that skips the repair in precisely the broken case is worse than no guard, and the suite could not see it because the flag test deliberately points each store at a FRESH collection name - correct for testing the creating path, and the reason it was blind to this one.
+  **So `KeyStore::bootstrap` and `SettingsStore::bootstrap` now call `createCollection` UNCONDITIONALLY, which is what makes 2.17.0 able to fix us.** Re-issuing it against an existing collection switches encryption ON (never off), encrypting the stored rows and their history; against an older server it is a no-op, so it is safe on every version we support. Verified safe before shipping, not reasoned about: `MemoryStore::createCollection`'s existing-collection path only acts on a `vectorDimension > 0` and on `defaultTtlSeconds`, and we pass 0 for every option but the flag, while `upgradeEncryptionOptions` only ever flips false to true and appends sensitive fields. `BootstrapAsksForEncryptionOnAnAlreadyEXISTINGCollection` pins it with a CONTROL collection that is never bootstrapped, so the assertion cannot pass for an unrelated reason, and it asserts the pre-existing row survives the re-call.
+  **`ProjectSecretStore::ensure` deliberately KEEPS its guard**, and the difference is the call path rather than the intent: it runs on every secret READ (the runner builds `ctx.env` through it) and `CreateCollection` is REFUSED by a read-only database, so making it unconditional would turn every function run into a 503 during read-only recovery - trading a live outage for a hardening step that collection does not need.
+  **What database 2.17.0 actually does, confirmed from their source and then independently by them:** collection-level `encrypted=true` encrypts EVERY non-null value in the collection whatever the field is called (`isEncryptedPath` returns true for any non-empty path when the rule is whole-document). Strings become `$ENC$...`, and numbers, bools, objects and arrays become `$ENCJ$...` and read back with their original type. The built-in sensitive-name patterns match a WHOLE path segment, so `openai_api_key` does NOT match `api_key` - which is why the collection flag, not the field name, is the only thing that was ever going to protect us. Grep a data file with `grep -F`: a bare `$ENC$` pattern is a regex anchor and matches nothing.
+  **A tenant can now reach `encrypted_field` through the INDEX route, and we answer 503 for it.** After 2.17.0 the name patterns match at top level in every collection, user collections included, so a tenant declaring an index on a field named `token` or `password` is refused with INVALID_ARGUMENT / `encrypted_field`. But `CreateIndexResult` carries no `reason`: the client turns a non-OK status into `success = false` with only the message text (`client.cpp` in `Impl::createUniqueIndex`), discarding the trailer detail, so `indexDeclineError` falls through to **503 `db_error`** - "retry as-is" for something no retry can fix. The mirror image of the `FailedPrecondition` bug: that told a caller a read-only database was its own mistake, this tells a caller its own permanent mistake is our outage. It cannot be fixed on our side, because the only distinguishing signal is the message text and matching on that is forbidden here. Reported to the database for a `reason` field on that struct; until it exists, the index route's refusal for an encrypted field is mis-classified, and the same "status becomes a success flag, detail discarded" shape is worth grepping for in the other index calls.
 - **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.

+ 19 - 2
src/key_store.cpp

@@ -20,8 +20,25 @@ void KeyStore::reload() {
 }
 
 void KeyStore::bootstrap(const std::string& envAdminKey) {
-    if (!db_.client().getCollectionInfo(coll_).has_value())
-        db_.client().createCollection(coll_, 0, /*encrypted*/ true, 0, 0);
+    // UNCONDITIONAL, not guarded by "does it exist yet", and that is the whole
+    // point. Measured on the dev database: this collection reports
+    // `encrypted: no` even though this call has asked for `true` since the
+    // first commit that introduced it - because the collection already existed
+    // when the code first ran (an earlier write created it implicitly), so a
+    // presence guard skipped the create in exactly the case that needed it.
+    // Database 2.17.0 is what makes the re-call matter: createCollection on an
+    // EXISTING collection now switches encryption ON, encrypting the stored
+    // rows and their history, and can never switch it off. Against anything
+    // older it is a plain no-op, so this is safe on every server we support.
+    //
+    // Safe to re-issue for a second reason worth stating: every other option
+    // here is passed as 0, and the existing-collection path only acts on a
+    // vector dimension greater than zero, so nothing but the encryption flag
+    // can change. A collection created plain would otherwise stay plain
+    // FOREVER - the database encrypts on the flag, and the built-in
+    // sensitive-name patterns cannot save us here because the secret is stored
+    // under `key`, which is not one of them.
+    db_.client().createCollection(coll_, 0, /*encrypted*/ true, 0, 0);
     reload();
     if (snap_->empty()) {
         ApiKey k;

+ 17 - 2
src/project_secret_store.cpp

@@ -11,8 +11,23 @@ ProjectSecretStore::ProjectSecretStore(DbGateway& db) : db_(db) {}
 void ProjectSecretStore::ensure(const std::string& project) {
     const std::string c = collectionFor(project);
     // Encrypted at rest, like the settings collection that holds the global
-    // provider key. The flag is fixed at creation, so it has to be right the
-    // first time - there is no later upgrade for a collection created plain.
+    // provider key.
+    //
+    // The guard STAYS here, unlike the two global stores which call
+    // createCollection unconditionally to repair a flag that was never
+    // applied. The difference is the call path, not the intent: this runs on
+    // every secret READ (the runner builds ctx.env through it), and
+    // CreateCollection is REFUSED by a read-only database. Making it
+    // unconditional would turn every function run into a 503 on a database in
+    // read-only recovery, where today the read succeeds - trading a live
+    // outage for a hardening step that is not needed, because this collection
+    // was created with the flag from its first commit and is measured
+    // `encrypted: yes`. If one is ever found plain, repair it from an admin
+    // path, not from the read path.
+    //
+    // NOT "fixed at creation", which this comment used to claim: database
+    // 2.17.0 switches encryption ON for an existing collection when
+    // createCollection asks for it, and can never switch it off.
     if (!db_.client().getCollectionInfo(c).has_value())
         db_.client().createCollection(c, 0, /*encrypted*/ true, 0, 0);
 }

+ 8 - 2
src/settings_store.cpp

@@ -9,8 +9,14 @@ SettingsStore::SettingsStore(DbGateway& db, std::string collection, std::string
       snap_(std::make_shared<const Settings>()) {}
 
 void SettingsStore::bootstrap(const std::string& envOpenAiKey) {
-    if (!db_.client().getCollectionInfo(coll_).has_value())
-        db_.client().createCollection(coll_, 0, /*encrypted*/ true, 0, 0);
+    // Unconditional for the same reason as KeyStore::bootstrap - see the long
+    // note there. This collection was also measured reporting `encrypted: no`
+    // while this call asked for `true`, and it holds the global provider
+    // credential under `openai_api_key`, which does NOT match the database's
+    // sensitive-name patterns (they match a whole path segment, so `api_key`
+    // does not match `openai_api_key`). The collection flag is therefore the
+    // only thing that will ever encrypt it.
+    db_.client().createCollection(coll_, 0, /*encrypted*/ true, 0, 0);
 
     Settings s;
     if (auto doc = db_.client().get(coll_, docId_))

+ 85 - 0
tests/test_api_integration.cpp

@@ -3669,6 +3669,91 @@ TEST_F(ApiFixture, EachCredentialStoreSetsTheEncryptedFLAG_whichProtectsNothing)
 }
 
 
+// --- the flag was ASKED FOR and never APPLIED -------------------------------
+//
+// Measured on the dev database: `vectorapi_keys` and `vectorapi_settings`
+// report `encrypted: no`, even though KeyStore::bootstrap and
+// SettingsStore::bootstrap have passed `encrypted=true` since the first commit
+// that introduced them. The cause was a presence guard - `if
+// (!getCollectionInfo(...))` - which skipped the create for a collection that
+// already existed, which is EXACTLY the case that needed it: an earlier write
+// had created the collection implicitly, with the default flag of false.
+//
+// So the request was real, the guard swallowed it, and `getCollectionInfo`
+// honestly reported false while our code looked like it had asked. Nothing in
+// the suite noticed, because the existing flag test deliberately points each
+// store at a FRESH collection name - which is the right call for testing the
+// creating path, and is precisely why it could not see this.
+//
+// That matters more than a tidy flag now: database 2.17.0 encrypts a
+// collection's rows based on this flag, and the built-in sensitive-NAME
+// patterns cannot cover for it, because they match a whole path segment and we
+// store the secrets under `key` and `openai_api_key`. A collection left plain
+// stays plaintext through the 2.17.0 migration and forever after.
+//
+// The fix is to call createCollection unconditionally. 2.17.0 turns encryption
+// ON for an existing collection (never off); older servers treat the re-call
+// as a no-op.
+TEST_F(ApiFixture, BootstrapAsksForEncryptionOnAnAlreadyEXISTINGCollection) {
+    const std::string suffix = std::to_string(::getpid()) + "_" + std::to_string(::time(nullptr));
+    const std::string target  = "enc_upgrade_target_" + suffix;
+    const std::string control = "enc_upgrade_control_" + suffix;
+    const std::string qTarget  = svapi::qualify("default", target);
+    const std::string qControl = svapi::qualify("default", control);
+
+    // Both collections are created PLAIN and by hand, standing in for one the
+    // database made implicitly before our store ever ran.
+    ASSERT_TRUE(db_->client().createCollection(qTarget, 0, /*encrypted*/ false, 0, 0));
+    ASSERT_TRUE(db_->client().createCollection(qControl, 0, /*encrypted*/ false, 0, 0));
+    ASSERT_FALSE(db_->client().getCollectionInfo(qTarget)->encrypted)
+        << "the premise of this test is a collection that starts PLAIN";
+
+    // A row that must survive the re-call. Re-issuing createCollection against
+    // a populated collection is the part of this fix that could do harm, so it
+    // is asserted rather than reasoned about.
+    db_->client().upsert(qTarget, nlohmann::json{{"key_id", "pre-existing"}}, "pre-existing");
+    const uint64_t before = db_->client().count(qTarget);
+    ASSERT_EQ(before, 1u);
+
+    // The store runs against the collection that already exists.
+    svapi::KeyStore keys(*db_, target);
+    keys.bootstrap("");
+
+    // Safety first, and this half holds on EVERY server version.
+    EXPECT_TRUE(db_->client().get(qTarget, "pre-existing").has_value())
+        << "re-issuing createCollection destroyed a pre-existing document";
+    EXPECT_GE(db_->client().count(qTarget), before)
+        << "re-issuing createCollection lost rows";
+
+    const auto target_info  = db_->client().getCollectionInfo(qTarget);
+    const auto control_info = db_->client().getCollectionInfo(qControl);
+    ASSERT_TRUE(target_info.has_value());
+    ASSERT_TRUE(control_info.has_value());
+
+    // The control is what makes the assertion mean something: it is never
+    // bootstrapped, so if BOTH collections were encrypted the cause would be
+    // something other than our call, and if both stay plain the server simply
+    // cannot do this yet.
+    EXPECT_FALSE(control_info->encrypted)
+        << "a collection nothing bootstrapped became encrypted; this test is "
+           "not measuring what it claims to";
+
+    if (!target_info->encrypted) {
+        db_->client().dropCollection(qTarget);
+        db_->client().dropCollection(qControl);
+        GTEST_SKIP() << "this server does not switch encryption on for an existing collection "
+                        "(database 2.17.0 and later do); our side asked for it, which is all "
+                        "this code controls - verify the bytes with `smartbotic-db-cli "
+                        "encryption-verify` once 2.17.0 is deployed";
+    }
+
+    // Reached only on 2.17.0+: the upgrade happened, driven by our re-call.
+    EXPECT_TRUE(target_info->encrypted);
+    db_->client().dropCollection(qTarget);
+    db_->client().dropCollection(qControl);
+}
+
+
 // --- is a credential actually encrypted at rest? ----------------------------
 //
 // The test above asserts getCollectionInfo()->encrypted, which is THE FLAG.