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

fix(unreleased 2.17.2): vectors in encrypted collections, unsealed verdict, key_file error

- _vector is never encrypted: since 2.17.0 the whole-document rule encrypted
  the embedding before the store extracted it, so every insert carrying a
  vector into an encrypted collection was refused. 4 e2e checks; all fail
  with the exemption reverted.
- The CLI prints CLEAN (UNSEALED: ...) while a reseal is pending.
- A missing storage.encryption.key_file is named in the startup error.
fszontagh 1 місяць тому
батько
коміт
1ccddbc82e

Різницю між файлами не показано, бо вона завелика
+ 0 - 0
CLAUDE.md


+ 7 - 1
cli/main.cpp

@@ -544,7 +544,13 @@ bool execCommand(smartbotic::database::Client& client,
                           << c.historyPlaintextRequired << ", double " << c.historyDoubleEncrypted << ")\n";
                           << c.historyPlaintextRequired << ", double " << c.historyDoubleEncrypted << ")\n";
                 for (const auto& s : c.samples) std::cout << "       plaintext at " << s << "\n";
                 for (const auto& s : c.samples) std::cout << "       plaintext at " << s << "\n";
             }
             }
-            std::cout << (r.clean() ? "CLEAN\n" : "FINDINGS - see FAIL lines\n");
+            // v2.17.2 - CLEAN describes the live store; while a reseal is
+            // pending the old plaintext is still on disk (WAL, older
+            // snapshots, LMDB free pages), so the verdict must say so rather
+            // than read as "nothing in plaintext on this disk".
+            if (!r.clean()) std::cout << "FINDINGS - see FAIL lines\n";
+            else if (!r.atRestSealed) std::cout << "CLEAN (UNSEALED: old plaintext copies remain on disk until the next restart)\n";
+            else std::cout << "CLEAN\n";
             return r.clean() && r.atRestSealed;
             return r.clean() && r.atRestSealed;
         }
         }
 
 

+ 4 - 7
docs/ROADMAP.md

@@ -377,13 +377,10 @@ joins; see 5c), which does not fit in 10 s. Run the container with
   the prune streams in two passes outside MemoryStore's locks; a reseal is
   the prune streams in two passes outside MemoryStore's locks; a reseal is
   requested only when an online upgrade rewrote plaintext, and compacts only
   requested only when an online upgrade rewrote plaintext, and compacts only
   that project.
   that project.
-- **⚠ Encrypted collection with vectors (found 2026-10-12, since 2.17.0):** an
-  insert carrying `_vector` into an `encrypted=true` collection is REFUSED
-  ("Invalid JSON ... type must be number, but is string"): the handler
-  encrypts the body, `_vector` included, before the store extracts the vector.
-  Vectors stored before the flag was switched on stay searchable. Needs a
-  decision: exempt `_vector` from encryption, or refuse `encrypted` together
-  with `vector_dimension`.
+- ~~**Encrypted collection with vectors**~~ - FIXED on main for 2.17.2 (not
+  released): `_vector` is exempt from encryption, so an encrypted collection
+  accepts, searches and exports vectors. Since 2.17.0 every such insert had
+  been refused.
 - Collection schemas cannot be declared in a migration file yet (the
 - Collection schemas cannot be declared in a migration file yet (the
   existing-row check lives in the SetCollectionSchema handler).
   existing-row check lives in the SetCollectionSchema handler).
 - ~~**Bogus index declarations on a production instance (found 2026-10-09, predates 2.14.0):**~~ removed
 - ~~**Bogus index declarations on a production instance (found 2026-10-09, predates 2.14.0):**~~ removed

+ 12 - 2
docs/integration-guide.md

@@ -979,7 +979,14 @@ encrypted (AES-256-GCM, random IV) when ANY of these applies:
 
 
 1. **The collection was created with `encrypted=true`**: every non-null value of
 1. **The collection was created with `encrypted=true`**: every non-null value of
    every document, strings as `$ENC$...`, other types as `$ENCJ$...` so a read
    every document, strings as `$ENC$...`, other types as `$ENCJ$...` so a read
-   restores the type. Property NAMES stay plaintext.
+   restores the type. Property NAMES stay plaintext. **The embedding
+   (`_vector`) is never encrypted**: similarity search compares its numbers, so
+   an encrypted collection searches, exports and re-imports like any other
+   (the text beside the vector is encrypted; filters on it are refused). Note
+   that an embedding can reveal something about its source text. In 2.17.0
+   and 2.17.1 the vector WAS encrypted, so every insert carrying a vector into
+   an encrypted collection was refused ("type must be number, but is
+   string"); fixed in 2.17.2 (on main, not yet released).
 2. **Its path is in the collection's `sensitive_fields`** (or lies under one).
 2. **Its path is in the collection's `sensitive_fields`** (or lies under one).
 3. **Its name matches a built-in pattern, at ANY depth, top level included**:
 3. **Its name matches a built-in pattern, at ANY depth, top level included**:
    `password`, `secret`, `token`, `api_key`, `apiKey`, `credentials` (exact name,
    `password`, `secret`, `token`, `api_key`, `apiKey`, `credentials` (exact name,
@@ -1096,7 +1103,10 @@ and counts:
 - plaintext where ciphertext is required;
 - plaintext where ciphertext is required;
 - ciphertext of ciphertext (double encryption);
 - ciphertext of ciphertext (double encryption);
 - ciphertext the key cannot open;
 - ciphertext the key cannot open;
-and whether the migration's seal is complete. It exits 1 on any finding.
+and whether the migration's seal is complete. It exits 1 on any finding, and
+also while unsealed. Since 2.17.2 the CLI prints `CLEAN (UNSEALED: ...)` while
+a reseal is pending: the live store is clean but old plaintext copies remain on
+disk until the next restart.
 
 
 What CLEAN means: everything the rules above REQUIRE to be encrypted is
 What CLEAN means: everything the rules above REQUIRE to be encrypted is
 encrypted, once, and decrypts. It does not mean "nothing sensitive is in the
 encrypted, once, and decrypts. It does not mean "nothing sensitive is in the

+ 21 - 1
service/src/encryption/encryption_manager.cpp

@@ -190,7 +190,20 @@ bool EncryptionManager::initialize() {
         // Save the generated key if using file provider
         // Save the generated key if using file provider
         if (config_.keyProvider == "file") {
         if (config_.keyProvider == "file") {
             if (!saveKeyToFile()) {
             if (!saveKeyToFile()) {
-                spdlog::error("CRITICAL: Failed to save encryption key to file - data will be lost on restart!");
+                // v2.17.2 - name the setting. The old text ("data will be lost
+                // on restart") read as a data-integrity emergency when the
+                // usual cause is simply that no key file was configured.
+                if (config_.keyFilePath.empty()) {
+                    spdlog::error("Encryption is enabled but no key file is configured: set "
+                                  "storage.encryption.key_file to a writable path (for example "
+                                  "<data_directory>/storage.key). Refusing to start rather than "
+                                  "encrypt with a key that would be lost at the next restart.");
+                } else {
+                    spdlog::error("Cannot save the generated encryption key to '{}' "
+                                  "(storage.encryption.key_file): make the path writable. Refusing "
+                                  "to start rather than encrypt with a key that would be lost at the "
+                                  "next restart.", config_.keyFilePath.string());
+                }
                 return false;
                 return false;
             }
             }
         }
         }
@@ -268,6 +281,13 @@ bool EncryptionManager::encryptJsonFieldEx(nlohmann::json& obj, const std::strin
 }
 }
 
 
 bool EncryptionManager::isEncryptedPath(const std::string& fieldPath, const EncryptionRule& rule) const {
 bool EncryptionManager::isEncryptedPath(const std::string& fieldPath, const EncryptionRule& rule) const {
+    // v2.17.2 - the embedding is never encrypted. It must stay an array of
+    // numbers: the store extracts it into the vector index AFTER the handler
+    // encrypted the body, and similarity search compares the numbers. 2.17.0
+    // encrypted it under the whole-document rule, so every insert carrying a
+    // vector into an encrypted collection was refused ("type must be number,
+    // but is string"). Only the top-level field: elements share its path.
+    if (fieldPath == "_vector") return false;
     if (rule.wholeDocument) return !fieldPath.empty();
     if (rule.wholeDocument) return !fieldPath.empty();
     // The path itself or any ancestor: under `credentials` everything is secret.
     // The path itself or any ancestor: under `credentials` everything is secret.
     std::string prefix;
     std::string prefix;

+ 34 - 0
tests/load_test/test_encryption_at_rest.cpp

@@ -251,6 +251,40 @@ static int upgrade2() {
     (void)c.createCollection("aliased", 0, true, 0, 0);
     (void)c.createCollection("aliased", 0, true, 0, 0);
     ck(c.verifyEncryption("aliased").atRestSealed,
     ck(c.verifyEncryption("aliased").atRestSealed,
        "a flag switched on over values already encrypted requests no reseal");
        "a flag switched on over values already encrypted requests no reseal");
+    // v2.17.2 - vectors in an encrypted collection. The embedding is never
+    // encrypted (search compares numbers); every other value is. 2.17.0/2.17.1
+    // refused every insert carrying a vector into an encrypted collection.
+    {
+        ck(c.createCollection("vvec", 0, true, 0, 4), "an encrypted vector collection is created");
+        bool inserted = true;
+        try {
+            c.insert("vvec", {{"text", "CANARY-VEC-TEXT-5150"}, {"_vector", std::vector<float>{1, 0, 0, 0}}}, "v1");
+            c.insert("vvec", {{"text", "other"}, {"_vector", std::vector<float>{0, 1, 0, 0}}}, "v2");
+        } catch (const std::exception& e) {
+            inserted = false;
+            std::cerr << "  (" << e.what() << ")\n";
+        }
+        ck(inserted, "inserts carrying a vector into an encrypted collection are accepted");
+        auto hits = c.similaritySearch("vvec", {1, 0, 0, 0}, 2, -1.f);
+        ck(!hits.empty() && hits[0].id == "v1" && hits[0].score > 0.999f,
+           "similarity search on an encrypted collection finds the row at 1.0");
+        auto d = c.get("vvec", "v1", Client::WithVector{});
+        ck(d && d->value("text", "") == "CANARY-VEC-TEXT-5150" && (*d)["_vector"].is_array() &&
+               (*d)["_vector"].size() == 4 && (*d)["_vector"][0].get<float>() == 1.0f,
+           "get returns the decrypted text and the numeric vector");
+        // A plain vector collection switched to encrypted keeps taking vectors.
+        c.createCollection("vflip", 0, false, 0, 4);
+        c.insert("vflip", {{"text", "before"}, {"_vector", std::vector<float>{1, 0, 0, 0}}}, "a");
+        (void)c.createCollection("vflip", 0, true, 0, 4);
+        bool after = true;
+        try {
+            c.insert("vflip", {{"text", "after"}, {"_vector", std::vector<float>{0, 1, 0, 0}}}, "b");
+        } catch (const std::exception&) { after = false; }
+        auto h2 = c.similaritySearch("vflip", {0, 1, 0, 0}, 1, -1.f);
+        ck(after && !h2.empty() && h2[0].id == "b" && h2[0].score > 0.999f,
+           "after switching a vector collection to encrypted, a new vector is stored and found");
+        verifyClean(c, "vectors", false);   // vflip's online upgrade requests a reseal
+    }
     ck(!c.verifyEncryption("late").collections.empty(), "late is audited");
     ck(!c.verifyEncryption("late").collections.empty(), "late is audited");
     ck(!c.createCollection("late", 0, true, 0, 0), "createCollection on existing late returns false");
     ck(!c.createCollection("late", 0, true, 0, 0), "createCollection on existing late returns false");
     auto r = c.verifyEncryption("late");
     auto r = c.verifyEncryption("late");

+ 2 - 1
tests/load_test/test_encryption_at_rest.sh

@@ -102,7 +102,8 @@ must_not_find() {
 LEGACY=(CANARY-TOP-PW-3391 CANARY-HIST-PW-4471 CANARY-PATCH-PW-6025 CANARY-ARRAY-0457
 LEGACY=(CANARY-TOP-PW-3391 CANARY-HIST-PW-4471 CANARY-PATCH-PW-6025 CANARY-ARRAY-0457
         CANARY-APIKEY-7720 CANARY-VAULT-KEY-5512 CANARY-VAULT-NESTED-9930 CANARY-VAULT-LIST-2210
         CANARY-APIKEY-7720 CANARY-VAULT-KEY-5512 CANARY-VAULT-NESTED-9930 CANARY-VAULT-LIST-2210
         CANARY-SF-MIGRATION-3398 CANARY-SF-PIN-8841 CANARY-ALIASED-4417)
         CANARY-SF-MIGRATION-3398 CANARY-SF-PIN-8841 CANARY-ALIASED-4417)
-ALL=("${LEGACY[@]}" CANARY-NESTED-PW-1182 CANARY-NEW-PW-1906 CANARY-NEW-TOKEN-7783 CANARY-NEW-VAULT-3360)
+ALL=("${LEGACY[@]}" CANARY-NESTED-PW-1182 CANARY-NEW-PW-1906 CANARY-NEW-TOKEN-7783 CANARY-NEW-VAULT-3360
+     CANARY-VEC-TEXT-5150)
 
 
 echo "=== seed with the RELEASED 2.16.0 server ==="
 echo "=== seed with the RELEASED 2.16.0 server ==="
 start "$OLD"
 start "$OLD"

Деякі файли не було показано, через те що забагато файлів було змінено