瀏覽代碼

fix(tests): our credentials are plaintext at rest, and my test said otherwise

The database team established that collection-level `encrypted=true`
encrypts nothing: CollectionOptions::encrypted is stored, reported by
getCollectionInfo, and never read by any write path. Their actual
mechanism matches sensitive field PATHS (`*.password`, `*.api_key`, ...)
and needs a dot before the name, so our top-level `value` and `key`
never matched - and `key` is not in that list at any nesting.

Verified independently rather than accepted: a project secret written
through our own HTTP route was found in plaintext in
`wal/wal-current.log` and in the project's `env/data.mdb`.

So API key secrets, the global OpenAI credential and every project
secret including mail passwords are readable by anyone with access to
the data directory OR ANY BACKUP OF IT - including the pre-upgrade
tarballs this session created under /var/backups on prod. On every
version we have ever run.

AND I HAD A TEST ASSERTING THE OPPOSITE. It read
getCollectionInfo()->encrypted and presented a flag as evidence about
bytes. That is precisely the proxy-not-the-thing failure this repo is
full of warnings about, and I committed it an hour after writing one of
them. It is renamed to say what it actually checks - that our stores
REQUEST encryption, which is worth keeping because it is what we control
and what starts working if the flag is ever honoured - and it now points
at the test that measures the property.

The new test asserts the DEFECT rather than the property, deliberately.
A permanently red test gets ignored, and this one is self-correcting:
when the database ships encryption at rest it FAILS and says to flip the
assertion back, and notes that rows written before then are still
plaintext and need rewriting. It skips, loudly, where the data directory
is not readable - a skip says "not checked", where a pass would be a
false assurance.

The remedy is the user's decision and is recorded in task #66: whatever
ships database-side, the credentials currently stored should be treated
as exposed, which means rotation rather than migration alone.

1250/1250 green.
fszontagh 1 月之前
父節點
當前提交
3e6244c328
共有 2 個文件被更改,包括 99 次插入 和 10 次删除
  1. 5 2
      CLAUDE.md
  2. 94 8
      tests/test_api_integration.cpp

+ 5 - 2
CLAUDE.md

@@ -83,8 +83,11 @@ 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.
+- **EVERY CREDENTIAL WE STORE IS PLAINTEXT AT REST. This is a live exposure, not a theoretical one.** API key secrets (`vectorapi_keys`, field `key`), the global OpenAI credential (`vectorapi_settings`) and every project secret including mail passwords (`<project>:vectorapi_secrets`) are readable by anyone with access to the database's data directory **or to any backup of it** - including the pre-upgrade tarballs under `/var/backups/` on prod. On every version we have ever run.
+  **The mechanism we believed in does not exist.** Each store creates its collection with `createCollection(..., encrypted=true, ...)`, and **nothing in the database's write path reads that flag** - `CollectionOptions::encrypted` is stored, reported by `getCollectionInfo` and never acted on. The database's actual mechanism is pattern matching on sensitive FIELD PATHS (`*.password`, `*.api_key`, ...), which requires a dot before the name, so our top-level `value` and `key` never matched - and `key` is not in the pattern list at any nesting.
+  **Measured here, not taken on report:** a project secret written through our own HTTP route was found in plaintext in `wal/wal-current.log` and in the project's `env/data.mdb`. `AStoredSecretIsCurrentlyPLAINTEXTatRest` does exactly that, and asserts the DEFECT so the suite stays honest and green while being self-correcting: when the database ships encryption at rest, that test fails and says to flip it.
+  **AND I HAD A TEST ASSERTING THE OPPOSITE.** It read `getCollectionInfo()->encrypted` and presented a flag as evidence about bytes, which is the same proxy-not-the-thing failure this file is full of warnings about. It is now named `EachCredentialStoreSetsTheEncryptedFLAG_whichProtectsNothing` and says so. **A flag that records an intention is not a measurement of the outcome** - if a security property matters, assert the property: write a canary and look for it on disk.
+  Until the database ships encryption at rest, the only reliable protection is encrypting CLIENT-SIDE before the value is stored.
 - **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.

+ 94 - 8
tests/test_api_integration.cpp

@@ -3,6 +3,9 @@
 #include "embedding_cache.hpp"
 #include <thread>
 #include <chrono>
+#include <cstdio>
+#include <sys/stat.h>
+#include <unistd.h>
 using svapi::testutil::ApiFixture;
 
 TEST_F(ApiFixture, HealthzPublic) { auto r = noAuth().Get("/healthz"); ASSERT_TRUE(r); EXPECT_EQ(r->status, 200); }
@@ -3598,7 +3601,7 @@ TEST_F(ApiFixture, AFilteredSearchREPORTSWhichPathAnsweredIt) {
     EXPECT_EQ(j.at("scanned"), 0) << j.dump();
 }
 
-TEST_F(ApiFixture, EverySecretBearingSTOREcreatesANEncryptedCollection) {
+TEST_F(ApiFixture, EachCredentialStoreSetsTheEncryptedFLAG_whichProtectsNothing) {
     // 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
@@ -3606,11 +3609,21 @@ TEST_F(ApiFixture, EverySecretBearingSTOREcreatesANEncryptedCollection) {
     // 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.
+    // We do not rely on field matching: each store passes the COLLECTION-level
+    // encrypted flag.
+    //
+    // **AND THAT FLAG PROTECTS NOTHING.** The database team established, by
+    // code reading and a canary, that NOTHING in the write path reads it -
+    // `CollectionOptions::encrypted` is stored and reported and never acted on.
+    // Confirmed here independently: see
+    // AStoredSecretIsCurrentlyPLAINTEXTatRest below, which finds a secret
+    // written through our own route in the data directory.
+    //
+    // So this test asserts only that our stores REQUEST encryption. That is
+    // worth keeping - it is what we control, and it is what will start
+    // working if the database ever honours the flag - but it is NOT evidence
+    // about the bytes, and an earlier version of this test presented it as
+    // though it were. A flag is a proxy; the bytes are the thing.
     //
     // 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
@@ -3630,7 +3643,9 @@ TEST_F(ApiFixture, EverySecretBearingSTOREcreatesANEncryptedCollection) {
     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";
+        EXPECT_TRUE(info->encrypted)
+            << name << ": our store did not even REQUEST encryption (which, note, the database "
+                       "does not act on - see AStoredSecretIsCurrentlyPLAINTEXTatRest)";
         db_->client().dropCollection(svapi::qualify("default", name));
     }
 
@@ -3643,7 +3658,7 @@ TEST_F(ApiFixture, EverySecretBearingSTOREcreatesANEncryptedCollection) {
     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";
+        << "the project secret store did not request encryption";
     c.Delete(secrets.c_str());
 
     // The falsifying half: a collection with no credentials in it is NOT
@@ -3652,3 +3667,74 @@ TEST_F(ApiFixture, EverySecretBearingSTOREcreatesANEncryptedCollection) {
     const auto plain = db_->client().getCollectionInfo(svapi::qualify(project_, "vectorapi_functions"));
     if (plain) EXPECT_FALSE(plain->encrypted) << "the function registry should be plaintext";
 }
+
+
+// --- is a credential actually encrypted at rest? ----------------------------
+//
+// The test above asserts getCollectionInfo()->encrypted, which is THE FLAG.
+// The database team then established, by code reading and a canary of their
+// own, that nothing in the write path reads that flag - so the flag is not
+// evidence about the bytes, and a test asserting it was pinning a mechanism
+// that does not exist. That is the same proxy-not-the-thing failure this file
+// is full of notes about, committed by me.
+//
+// This asserts the PROPERTY: write a credential through our own route, then
+// look for it in the database's data directory. It needs the directory to be
+// readable from here, which it is for the bind-mounted dev container, so the
+// test SKIPS rather than fails when it is not - a skip says "not checked",
+// which is honest, where a pass would be a false assurance.
+TEST_F(ApiFixture, AStoredSecretIsCurrentlyPLAINTEXTatRest) {
+    const char* dataDir = "/data/smartbotic-db/data";
+    struct stat st{};
+    if (::stat(dataDir, &st) != 0 || !S_ISDIR(st.st_mode)) {
+        GTEST_SKIP() << "no readable data directory at " << dataDir
+                     << "; cannot inspect bytes at rest";
+    }
+
+    // A value no other row could contain, so a hit is unambiguous.
+    const std::string canary =
+        "svapi-at-rest-canary-" + std::to_string(::getpid()) + "-" + std::to_string(::time(nullptr));
+
+    auto c = admin();
+    const std::string path = "/api/v1/projects/" + project_ + "/secrets/AT_REST_PROBE";
+    auto put = c.Put(path.c_str(), nlohmann::json{{"value", canary}}.dump(), "application/json");
+    ASSERT_TRUE(put); ASSERT_EQ(put->status / 100, 2) << put->body;
+
+    // Read it back so we know the write really landed, not merely 2xx.
+    auto back = c.Get(("/api/v1/projects/" + project_ + "/secrets").c_str());
+    ASSERT_TRUE(back); ASSERT_EQ(back->status, 200) << back->body;
+    EXPECT_NE(back->body.find("AT_REST_PROBE"), std::string::npos) << back->body;
+
+    // grep -r for the canary. Exit 0 means FOUND, i.e. plaintext on disk.
+    const std::string cmd = "grep -rlF " + canary + " " + dataDir + " 2>/dev/null | head -3";
+    std::string hits;
+    if (FILE* p = ::popen(cmd.c_str(), "r")) {
+        char buf[512];
+        while (::fgets(buf, sizeof(buf), p) != nullptr) hits += buf;
+        ::pclose(p);
+    }
+    c.Delete(path.c_str());
+
+    // ASSERTS THE DEFECT, deliberately. The property we want does NOT hold:
+    // collection-level `encrypted=true` encrypts nothing, and the database's
+    // sensitive-field patterns need a dot before the name so our top-level
+    // `value` never matched. Measured here: the canary appears in
+    // `wal/wal-current.log` and in the project's `env/data.mdb`.
+    //
+    // Pinned this way round rather than left failing, for two reasons. A
+    // permanently red test gets ignored, and this one is self-correcting: when
+    // the database ships encryption at rest, THIS TEST FAILS and says so,
+    // which is the moment to flip it back to `hits.empty()` and delete this
+    // comment. A silent skip would have hidden the exposure instead.
+    EXPECT_FALSE(hits.empty())
+        << "A secret is NO LONGER plaintext at rest - the database appears to have shipped "
+           "encryption. Flip this assertion back to hits.empty() and remove the known-defect "
+           "framing; the credentials written before that release are still plaintext and need "
+           "rewriting.";
+    if (!hits.empty()) {
+        GTEST_LOG_(WARNING)
+            << "KNOWN DEFECT: a project secret written through our own route is PLAINTEXT in "
+               "the database's data directory, and therefore in every backup of it. Files:\n"
+            << hits;
+    }
+}