Browse Source

wip: 2.17.0 - encryption at rest that does what it says (NOT RELEASED)

Work in progress, paused for the weekend. Built and passing:
test_encryption_at_rest (seeded by the released 2.16.0 server, canaries
proven plaintext before and absent from every file after), every part
reverted alone fails it. The zeus-copy comparison (decrypted dumps before
and after) was running when paused; the first, invalidated pass showed
16816/16816 common documents byte-identical.

Fixes: the collection encrypted flag and sensitive_fields were never read;
the name patterns matched nested fields only; patch and migration ops never
encrypted; strings in arrays were never encrypted or decrypted; migration
options lived under the bare collection name. One-time migration with a
seal (WAL rotation, verified snapshot, old snapshots/WAL removed, LMDB
compaction), online upgrade via createCollection(encrypted=true),
VerifyEncryption / encryption-verify, comparisons on ciphertext refused
(encrypted_field). Client: 29 reads now carry the server's error reason.

Remaining: zeus-copy result, full suites, compat.sh, release, zeus,
consumer notices.
fszontagh 1 month ago
parent
commit
d129ec2cfb

File diff suppressed because it is too large
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.16.0
+2.17.0

+ 24 - 0
cli/main.cpp

@@ -78,6 +78,7 @@ void printUsage() {
               << "  " << C_CYAN << "unlock" << C_RESET << "                               Unlock database (accept writes)\n"
               << "  " << C_CYAN << "status" << C_RESET << "                               Show read-only + recovery status\n"
               << "  " << C_CYAN << "server-info" << C_RESET << "                          Server version, commit and feature names (2.15.0+)\n"
+              << "  " << C_CYAN << "encryption-verify" << C_RESET << " [collection]         Audit encryption at rest (exit 1 on any finding)\n"
               << C_BOLD << "  Collection schema (v2.16.0+)" << C_RESET << "\n"
               << "  " << C_CYAN << "schema" << C_RESET << " <collection>                  Show the schema, mode and counters\n"
               << "  " << C_CYAN << "schema-set" << C_RESET << " <collection> <json|@file> [--audit]\n"
@@ -522,6 +523,29 @@ bool execCommand(smartbotic::database::Client& client,
             return true;
         }
 
+        if (cmd == "encryption-verify") {
+            const auto r = client.verifyEncryption(params.empty() ? "" : params[0]);
+            if (!r.encryptionEnabled) {
+                std::cout << "encryption is DISABLED on this server: nothing is encrypted at rest\n";
+                return false;
+            }
+            std::cout << "at-rest migration sealed: " << (r.atRestSealed ? "yes" : "NO (restart pending)") << "\n";
+            for (const auto& c : r.collections) {
+                const bool bad = c.plaintextRequired || c.doubleEncrypted || c.undecryptable ||
+                                 c.historyPlaintextRequired || c.historyDoubleEncrypted;
+                std::cout << (bad ? "FAIL " : "ok   ") << c.collection
+                          << (c.collectionEncrypted ? " [encrypted]" : "")
+                          << "  rows " << c.rows << ", ciphertext values " << c.encryptedValues
+                          << ", plaintext-required " << c.plaintextRequired
+                          << ", double " << c.doubleEncrypted << ", undecryptable " << c.undecryptable
+                          << ", history " << c.historyVersions << " (plaintext-required "
+                          << c.historyPlaintextRequired << ", double " << c.historyDoubleEncrypted << ")\n";
+                for (const auto& s : c.samples) std::cout << "       plaintext at " << s << "\n";
+            }
+            std::cout << (r.clean() ? "CLEAN\n" : "FINDINGS - see FAIL lines\n");
+            return r.clean() && r.atRestSealed;
+        }
+
         if (cmd == "schema" || cmd == "schema-drop" || cmd == "schema-suggest") {
             if (params.empty()) {
                 printError("usage: " + cmd + " <collection>");

+ 45 - 0
client/include/smartbotic/database/client.hpp

@@ -332,6 +332,7 @@ public:
         static constexpr const char* kServerInfo = "server_info";
         static constexpr const char* kClientVersionHeader = "client_version_header";
         static constexpr const char* kCollectionSchema = "collection_schema";
+        static constexpr const char* kEncryptionAtRest = "encryption_at_rest";
     };
 
     struct ServerInfo {
@@ -1197,6 +1198,50 @@ public:
                      uint64_t& rowsIndexed);
     bool dropIndex(const std::string& collection, const std::string& field);
 
+    // ===== Encryption at rest (v2.17.0) =====
+
+    struct EncryptionAudit {
+        std::string collection;
+        bool collectionEncrypted = false;
+        std::vector<std::string> sensitiveFields;
+        uint64_t rows = 0;
+        uint64_t encryptedValues = 0;
+        uint64_t plaintextRequired = 0;      // must be 0
+        uint64_t doubleEncrypted = 0;        // must be 0
+        uint64_t undecryptable = 0;          // must be 0
+        uint64_t historyVersions = 0;
+        uint64_t historyPlaintextRequired = 0;   // must be 0
+        uint64_t historyDoubleEncrypted = 0;     // must be 0
+        std::vector<std::string> samples;    // "<id>: <path>" of plaintext findings
+    };
+
+    struct EncryptionReport {
+        bool encryptionEnabled = false;
+        bool atRestSealed = false;
+        std::vector<EncryptionAudit> collections;
+        /// True when nothing is plaintext that must be encrypted, nothing is
+        /// encrypted twice, and every ciphertext opens with the server's key.
+        bool clean() const {
+            for (const auto& c : collections) {
+                if (c.plaintextRequired || c.doubleEncrypted || c.undecryptable ||
+                    c.historyPlaintextRequired || c.historyDoubleEncrypted) {
+                    return false;
+                }
+            }
+            return true;
+        }
+    };
+
+    /**
+     * v2.17.0 - audit encryption at rest: every stored row and history version
+     * of `collection` (empty = every user collection) counted against the
+     * encryption rules (an `encrypted` collection: every value; its
+     * `sensitive_fields`; the built-in name patterns at any depth). Read-only;
+     * admin. Throws Client::Error on failure, FailedPrecondition with reason
+     * `server_unsupported` against a pre-2.17.0 server.
+     */
+    [[nodiscard]] EncryptionReport verifyEncryption(const std::string& collection = "");
+
     // ===== Collection schema (v2.16.0) =====
     //
     // OPTIONAL per collection: a collection without a schema behaves exactly as

+ 68 - 29
client/src/client.cpp

@@ -547,7 +547,7 @@ public:
                 throw Client::PermissionDenied("access denied: get");
             }
             spdlog::error("Client::get failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         if (!response.found()) {
@@ -932,7 +932,7 @@ public:
                 throw Client::PermissionDenied("access denied: exists");
             }
             spdlog::error("Client::exists failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         return response.exists();
@@ -984,7 +984,7 @@ public:
             // caller bug, and returning {} here is indistinguishable from a
             // legitimately empty result. Since v2.12.4 every other failure
             // throws too (below).
-            throwStatus(status, status.error_message());
+            throwStatus(status, status.error_message(), trailerDetail(context));
         }
         if (!status.ok()) {
             // v2.8.0 — a permission denial must NOT look like "no data".
@@ -997,7 +997,7 @@ public:
                 throw Client::PermissionDenied("access denied: find");
             }
             spdlog::error("Client::find failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         std::vector<nlohmann::json> results;
@@ -1047,7 +1047,7 @@ public:
 
         auto status = stub_->Find(&context, request, &response);
         if (status.error_code() == grpc::StatusCode::NOT_FOUND) {
-            throwStatus(status, status.error_message());  // see find()
+            throwStatus(status, status.error_message(), trailerDetail(context));  // see find()
         }
         if (!status.ok()) {
             // v2.8.0 — a permission denial must NOT look like "no data".
@@ -1060,7 +1060,7 @@ public:
                 throw Client::PermissionDenied("access denied: findWithMetrics");
             }
             spdlog::error("Client::findWithMetrics failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         Client::FindResult result;
@@ -1115,7 +1115,7 @@ public:
                 throw Client::PermissionDenied("access denied: count");
             }
             spdlog::error("Client::count failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         return response.count();
@@ -1173,7 +1173,7 @@ public:
         auto status = stub_->SetMembers(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::setMembers failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         return {response.members().begin(), response.members().end()};
@@ -1192,7 +1192,7 @@ public:
         auto status = stub_->SetIsMember(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::setIsMember failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         return response.is_member();
@@ -1236,7 +1236,7 @@ public:
         auto status = stub_->SimilaritySearch(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::similaritySearch failed: {}", status.error_message());
-            throwStatus(status, status.error_message());
+            throwStatus(status, status.error_message(), trailerDetail(context));
         }
         // v2.14.0 - a pre-2.14.0 server ignores the filters and ranks the
         // whole collection. Those rows look exactly like a filtered answer, so
@@ -1336,7 +1336,7 @@ public:
         auto status = stub_->ListCollections(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::listCollections failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         // v2.4.5 — round-trip the naming: callers pass bare names in, so they
@@ -1366,7 +1366,7 @@ public:
         auto status = stub_->GetCollectionInfo(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::getCollectionInfo failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         if (!response.found()) {
@@ -1397,7 +1397,7 @@ public:
         auto status = stub_->ListProjects(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::listProjects failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         return {response.projects().begin(), response.projects().end()};
     }
@@ -1413,7 +1413,7 @@ public:
         auto status = stub_->CreateProject(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::createProject failed: {}", status.error_message());
-            throwStatus(status, "createProject transport failure: " + status.error_message());
+            throwStatus(status, "createProject transport failure: " + status.error_message(), trailerDetail(context));
         }
         if (!response.error().empty()) {
             // Validation error (invalid name etc.) — surfaced via the
@@ -1435,7 +1435,7 @@ public:
         auto status = stub_->DropProject(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::dropProject failed: {}", status.error_message());
-            throwStatus(status, "dropProject transport failure: " + status.error_message());
+            throwStatus(status, "dropProject transport failure: " + status.error_message(), trailerDetail(context));
         }
         if (!response.error().empty()) {
             throw std::runtime_error("dropProject('" + name + "') refused: " +
@@ -1485,7 +1485,7 @@ public:
         auto status = stub_->GetCollectionConfig(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::getCollectionConfig failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         out.timestampPrecision = response.config().timestamp_precision();
         if (out.timestampPrecision.empty()) out.timestampPrecision = "ms";
@@ -1510,7 +1510,7 @@ public:
         auto status = stub_->GetCollectionConfig(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::hasCollectionConfig failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         return response.found();
     }
@@ -1752,6 +1752,41 @@ public:
         return out;
     }
 
+    Client::EncryptionReport verifyEncryption(const std::string& collection) {
+        requireCapability(Client::Capability::kEncryptionAtRest, "verifyEncryption");
+        smartbotic::databasepb::VerifyEncryptionRequest request;
+        if (!collection.empty()) request.set_collection(qualify(collection));
+        smartbotic::databasepb::VerifyEncryptionResponse response;
+        grpc::ClientContext context;
+        // A full scan of every collection and its history.
+        context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(600));
+        attachAuth(context);
+        auto status = stub_->VerifyEncryption(&context, request, &response);
+        if (!status.ok()) {
+            throwStatus(status, "verifyEncryption: " + status.error_message(), trailerDetail(context));
+        }
+        Client::EncryptionReport out;
+        out.encryptionEnabled = response.encryption_enabled();
+        out.atRestSealed = response.at_rest_sealed();
+        for (const auto& a : response.collections()) {
+            Client::EncryptionAudit e;
+            e.collection = a.collection();
+            e.collectionEncrypted = a.collection_encrypted();
+            e.sensitiveFields.assign(a.sensitive_fields().begin(), a.sensitive_fields().end());
+            e.rows = a.rows();
+            e.encryptedValues = a.encrypted_values();
+            e.plaintextRequired = a.plaintext_required();
+            e.doubleEncrypted = a.double_encrypted();
+            e.undecryptable = a.undecryptable();
+            e.historyVersions = a.history_versions();
+            e.historyPlaintextRequired = a.history_plaintext_required();
+            e.historyDoubleEncrypted = a.history_double_encrypted();
+            e.samples.assign(a.samples().begin(), a.samples().end());
+            out.collections.push_back(std::move(e));
+        }
+        return out;
+    }
+
     // ===== Collection schema (v2.16.0) =====
 
     Client::SchemaChangeResult schemaChange(const std::string& collection, const std::string& schemaJson,
@@ -1847,7 +1882,7 @@ public:
         auto status = stub_->ListIndexes(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::listIndexes failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         out.reserve(response.indexes_size());
         if (uniqueFlags != nullptr) {
@@ -1929,7 +1964,7 @@ public:
         auto status = stub_->ListIndexes(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::listCompositeUniqueIndexes failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         for (const auto& i : response.indexes()) {
             if (i.fields_size() > 0) out.emplace_back(i.fields().begin(), i.fields().end());
@@ -1953,7 +1988,7 @@ public:
         auto status = stub_->GetIndexValues(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::indexValues failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         out.reserve(response.values_size());
         for (const auto& v : response.values()) {
@@ -1996,7 +2031,7 @@ public:
         auto status = stub_->ListViews(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::listViews failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         for (const auto& pb : response.views()) {
             Client::ViewDefinition v;
@@ -2036,7 +2071,7 @@ public:
         auto status = stub_->GetViewInfo(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::getViewInfo failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         if (!response.found()) {
             return std::nullopt;
@@ -2155,7 +2190,7 @@ public:
         auto status = stub_->ListRelations(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::listRelations failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         out.reserve(response.relations_size());
         for (const auto& pb : response.relations()) {
@@ -2174,7 +2209,7 @@ public:
         auto status = stub_->GetRelationInfo(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::getRelationInfo failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
         if (!response.found()) {
             return std::nullopt;
@@ -2519,7 +2554,7 @@ public:
         auto status = stub_->GetVersionHistory(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::getVersionHistory failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         Client::VersionHistoryResult result;
@@ -2556,7 +2591,7 @@ public:
         auto status = stub_->GetDocumentVersion(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::getDocumentVersion failed: {}", status.error_message());
-            throwStatus(status, status.error_message());  // v2.12.4: never empty on failure
+            throwStatus(status, status.error_message(), trailerDetail(context));  // v2.12.4: never empty on failure
         }
 
         if (!response.found()) {
@@ -2870,7 +2905,7 @@ public:
         auto status = reader->Finish();
         if (!status.ok()) {
             spdlog::error("Client::downloadFile failed: {}", status.error_message());
-            throwStatus(status, status.error_message());
+            throwStatus(status, status.error_message(), trailerDetail(context));
         }
         return fileData;
     }
@@ -2888,7 +2923,7 @@ public:
         if (!status.ok()) {
             if (status.error_code() == grpc::StatusCode::NOT_FOUND) return std::nullopt;
             spdlog::error("Client::getFileInfo failed: {}", status.error_message());
-            throwStatus(status, status.error_message());
+            throwStatus(status, status.error_message(), trailerDetail(context));
         }
 
         Client::FileRecord record;
@@ -2980,7 +3015,7 @@ public:
         auto status = stub_->ListFiles(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::listFiles failed: {}", status.error_message());
-            throwStatus(status, status.error_message());
+            throwStatus(status, status.error_message(), trailerDetail(context));
         }
 
         Client::FileListResult result;
@@ -3641,6 +3676,10 @@ Client::FileListResult Client::listFiles(const std::string& file_type,
 #define SMARTBOTIC_DB_GIT_COMMIT_STRING "unknown"
 #endif
 
+Client::EncryptionReport Client::verifyEncryption(const std::string& collection) {
+    return impl_->verifyEncryption(collection);
+}
+
 Client::SchemaChangeResult Client::setCollectionSchema(const std::string& collection,
                                                        const nlohmann::json& schema,
                                                        SchemaMode mode) {

+ 11 - 18
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Released version: 2.16.0** (see `VERSION`). Last reviewed: 2026-10-09.
+**Released version: 2.17.0** (see `VERSION`). Last reviewed: 2026-10-09.
 
 > 2.11.5 was prepared but never released on its own: its work (event actors,
 > `removeAs()`) ships inside 2.12.0. There is no 2.11.5 package.
@@ -56,12 +56,15 @@ Consequences of that substitution, which trip up readers:
 
 ## Shipped
 
-Every item below is in the installed product as of 2.16.0. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.17.0. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
 - LMDB storage substrate, one env per project, dual-write mirror from MemoryStore
 - Multi-project namespaces (`<project>:<collection>`)
+- Encryption at rest that does what it says: encrypted collections,
+  `sensitive_fields`, sensitive names at any depth, a one-time migration with
+  a seal, `encryption-verify`, comparisons on ciphertext refused (2.17.0)
 - Optional per-collection JSON Schema (enforce/audit, existing rows checked
   first, suggested from data) (2.16.0)
 - Independent client and server releases: `GetServerInfo` capability
@@ -480,22 +483,12 @@ joins; see 5c), which does not fit in 10 s. The container is now run with
   comparison.
 - TTL is not retro-applied: rows written before a default TTL existed keep no
   expiry.
-- **⚠ The collection-level `encrypted` flag encrypts NOTHING (found 2026-10-09).**
-  `CollectionOptions::encrypted` is stored, persisted and reported by
-  getCollectionInfo, and no code path reads it: every write encrypts only the
-  fields whose path matches the built-in patterns. Confirmed by experiment on
-  2.16.0 (collection created with encrypted=true, a top-level `key` value found
-  in plaintext in the data directory, a nested `password` encrypted). True
-  since the initial extraction. smartbotic-vectorapi relied on it for
-  `vectorapi_keys` / `vectorapi_settings` / `vectorapi_secrets`, all plaintext at
-  rest. Also: createCollection on an EXISTING collection ignores its options, so
-  the flag can read false on a collection that was created implicitly first.
-- **Top-level sensitive fields are not encrypted (found 2026-10-09).** The
-  built-in patterns (`*.password`, `*.api_key`, `*.token`, ...) become regexes
-  that need a dot before the name, so only NESTED fields match; a top-level
-  `password` is stored in plaintext. The patterns are not configurable. Fixing
-  it changes what gets encrypted on existing installs (rows written before stay
-  plaintext until rewritten), so it wants its own release and a migration note.
+- ~~Encryption at rest~~ - FIXED in 2.17.0 (the collection `encrypted` flag and
+  `sensitive_fields` did nothing, the patterns matched nested fields only,
+  patch / migration ops never encrypted, strings in arrays were never
+  encrypted). See CLAUDE.md v2.17.0. What a database cannot fix: copies made
+  before the upgrade (backups, `pre-upgrade-*`, the zeus nightly tarballs)
+  still hold the plaintext.
 - Collection schemas cannot be declared in a migration file yet (the
   existing-row check lives in the SetCollectionSchema handler).
 - ~~**Bogus index declarations on zeus (found 2026-10-09, predates 2.14.0):**~~ removed

+ 81 - 32
docs/integration-guide.md

@@ -656,7 +656,7 @@ Review it, edit it, then apply it with `setCollectionSchema`.
 
 **Server version:** all four client methods need a 2.16.0 server. Against an older one they refuse before sending, with FailedPrecondition and reason `server_unsupported`. The change calls report that reason in their result; the reads throw it.
 
-**⚠ A sensitive-field caveat, independent of schemas:** the default sensitive-field patterns (`*.password`, `*.api_key`, ...) need a dot before the name, so they match a NESTED field only. A top-level `password` is stored in plaintext. The patterns are built in (not configurable), so nest secrets, e.g. `creds.password`. Found while testing 2.16.0; recorded in the ROADMAP.
+**Encrypted fields and schemas:** a schema validates the PLAINTEXT of an encrypted field (see "Encryption at rest"); `maxLength` on a password means the password's length.
 
 ### Indexes and unique constraints
 
@@ -962,37 +962,86 @@ this name is always a subset of what the view allows.
 > reader; the protection is against someone reading data files, snapshots, or
 > backups, not against a client.
 
-#### ⚠ Field-level encryption is ON by default and keyed off FIELD NAMES
-
-This surprises people, so it is spelled out here rather than left to be
-discovered. `encryption.enabled` defaults to **`true`**, and the daemon encrypts
-any field whose path matches one of these patterns, in **every** collection -
-independent of the collection-level `encrypted` flag and of
-`CollectionOptions.sensitiveFields`:
-
-```
-*.api_key   *.apiKey   *.password   *.secret   *.token   *.credentials
-```
-
-So a document with `config.password` is stored as `"$ENC$..."` whether or not you
-asked for encryption. Consequences worth knowing:
-
-- **Reads are symmetric.** `Get`, `Find`, `SimilaritySearch`, view reads,
-  `GetVersionHistory` and `GetDocumentVersion` all return plaintext. (Before
-  2.11.1 the two version handlers did **not** decrypt, so a live read returned
-  plaintext while every version of the same document returned `$ENC$...` - which
-  made "does this document differ from its published version?" answer *yes*
-  forever. If you compare documents against versions, require >= 2.11.1.)
-- **The same ciphertext in consecutive versions is correct**, not a fixed IV.
-  When a sensitive field does not change between writes, the stored ciphertext is
-  carried over verbatim instead of being re-encrypted, precisely so version
-  history does not show a spurious difference on every save.
-- **An encrypted field cannot be indexed or filtered on usefully**, since the
-  stored bytes are ciphertext.
-- To turn it off, set `storage.encryption.enabled: false`. Existing `$ENC$`
-  values then read back as the literal ciphertext string - decryption is gated on
-  the manager being enabled - so switch it off before storing such fields, not
-  after.
+#### Encryption at rest (rewritten in 2.17.0 - read this if you store secrets)
+
+`encryption.enabled` defaults to **`true`**. Since **2.17.0** a value is stored
+encrypted (AES-256-GCM, random IV) when ANY of these applies:
+
+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
+   restores the type. Property NAMES stay plaintext.
+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**:
+   `password`, `secret`, `token`, `api_key`, `apiKey`, `credentials` (exact name,
+   case-insensitive) - and everything under such a field, array elements
+   included. `refreshToken` or `apiKeyHash` do NOT match.
+
+**⚠ Before 2.17.0 only part of this was true, and nothing said so:**
+- **(1) and (2) did nothing at all.** The options were stored and reported, and
+  no code read them.
+- **(3) matched NESTED fields only**, so a top-level `password` was plaintext.
+- **patch never encrypted**, migration-file ops never encrypted, and strings
+  inside arrays were neither encrypted nor decrypted.
+
+If you relied on any of these, your data was plaintext at rest - and so are any
+backups or copies taken before the upgrade.
+
+**The upgrade migrates existing data, once, at the first 2.17.0 boot:**
+- **What is encrypted:** every stored value the rules above require, in place
+  (same version, no new history entry), and every stored history version.
+- **The old plaintext is then removed from the database files:** the WAL is
+  rotated, a verified snapshot is taken, every older snapshot and WAL file is
+  deleted, and every LMDB environment is compacted (LMDB is copy-on-write, so
+  freed pages still hold old bytes until compacted).
+- **No double encryption:** a value already carrying `$ENC$`/`$ENCJ$` is never
+  encrypted again, so the pass is idempotent.
+- **Boot time:** it is logged (`v2.17 at-rest`) and extends the systemd start
+  timeout as it goes. On a copy of the zeus dataset (17k documents, 626 MB) it
+  took about 7 minutes; the compaction shrank that file to 35 MB.
+- **What it cannot reach:** copies made BEFORE that boot - backups, pre-upgrade
+  copies, replicas, released disk blocks. Rotate any credential that was stored
+  in plaintext.
+
+**Switching encryption on for an existing collection:** `createCollection(name,
+..., encrypted=true)` on an existing collection now switches it on (never off),
+and `sensitive_fields` given that way are added. Its rows and history are
+encrypted immediately. The old plaintext copies are removed at the next
+restart: `encryption-verify` reports `sealed: NO` until then.
+
+**Encrypted fields cannot be compared, so comparisons are REFUSED** with
+INVALID_ARGUMENT, reason `encrypted_field`, the fields named:
+- a find/count/similaritySearch filter or a sort on an encrypted field, or a
+  SEARCH filter on an encrypted collection;
+- an index, unique or composite constraint, or relation on an encrypted field;
+- listing an encrypted field's index values;
+- an increment of an encrypted value;
+- set operations on an encrypted collection.
+
+Before 2.17.0 such a comparison ran against ciphertext under a random IV and
+silently matched nothing - an empty result indistinguishable from "no such
+row". An index already declared on a field that is now encrypted is disarmed
+at boot and named in an ERROR line; drop it. **To look a record up by a
+secret** (an API key, a token), store a keyed hash of it in a field with a
+non-sensitive name, look up by that, and keep the secret itself encrypted.
+Filters on metadata (`_id`, `_created_at`, ...) and on non-sensitive fields of a
+non-encrypted collection work as before.
+
+**Reading is unchanged:** `Get`, `Find`, `SimilaritySearch`, view reads, exports
+and version reads all return plaintext. The same ciphertext in consecutive
+versions is correct (an unchanged sensitive value keeps its stored ciphertext).
+
+**Auditing:** `smartbotic-db-cli encryption-verify [collection]` /
+`Client::verifyEncryption()` (admin) walks every stored row and history version
+and counts:
+- values correctly stored as ciphertext;
+- plaintext where ciphertext is required;
+- ciphertext of ciphertext (double encryption);
+- ciphertext the key cannot open;
+and whether the migration's seal is complete. It exits 1 on any finding.
+
+**To turn encryption off** set `storage.encryption.enabled: false`. Existing
+ciphertext then reads back as the literal `$ENC$` string, so do it before
+storing such fields, not after.
 
 ### Access Policy — row and column level security (2.7.0+)
 

+ 23 - 0
packaging/old-server.sh

@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+#
+# packaging/old-server.sh <version> - unpack a RELEASED server binary into
+# build/old-server-<version>/ so an e2e suite can create data the way that
+# release did (tests/load_test/test_encryption_at_rest.sh seeds with 2.16.0).
+# Needs the .deb in a smartbotics-deb-repo checkout ($DEB_REPO_DIR, default:
+# next to this one). The binary runs in the packaging/dev.sh image (Debian 13).
+
+set -euo pipefail
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+V="${1:?usage: packaging/old-server.sh <version>}"
+DEB_REPO_DIR="${DEB_REPO_DIR:-$(dirname "$ROOT")/smartbotics-deb-repo}"
+DEB="$DEB_REPO_DIR/repo/pool/trixie/main/smartbotic-database_${V}-1_amd64.deb"
+[[ -f "$DEB" ]] || { echo "missing $DEB"; exit 1; }
+OUT="$ROOT/build/old-server-$V"
+rm -rf "$OUT"
+mkdir -p "$OUT"
+cd "$OUT"
+ar x "$DEB"
+tar -xf data.tar.* ./usr/bin/smartbotic-database
+rm -f control.tar.* data.tar.* debian-binary
+echo "$OUT/usr/bin/smartbotic-database"

+ 33 - 0
proto/database.proto

@@ -166,6 +166,9 @@ service DatabaseService {
     // refuse a call the server would misunderstand instead of sending it. A
     // pre-2.15.0 server answers UNIMPLEMENTED.
     rpc GetServerInfo(GetServerInfoRequest) returns (GetServerInfoResponse);
+    // v2.17.0 - audit encryption at rest: every stored row and history
+    // version, counted against the encryption rules. Read-only, admin.
+    rpc VerifyEncryption(VerifyEncryptionRequest) returns (VerifyEncryptionResponse);
     rpc GetStats(GetStatsRequest) returns (GetStatsResponse);
     rpc GetMemoryStats(GetMemoryStatsRequest) returns (GetMemoryStatsResponse);
 
@@ -1019,6 +1022,36 @@ message HealthCheckRequest {
 message GetServerInfoRequest {
 }
 
+// v2.17.0 - encryption at rest. A value must be stored encrypted when its
+// collection is `encrypted` (every value), when its path is in the collection's
+// `sensitive_fields` (or under one), or when its name matches a built-in
+// sensitive pattern (password, secret, token, api_key, apiKey, credentials) at
+// any depth.
+message VerifyEncryptionRequest {
+    string collection = 1;   // empty = every user collection
+}
+
+message EncryptionAudit {
+    string collection = 1;
+    bool collection_encrypted = 2;
+    repeated string sensitive_fields = 3;
+    uint64 rows = 4;
+    uint64 encrypted_values = 5;          // stored as ciphertext
+    uint64 plaintext_required = 6;        // plaintext where ciphertext is required (must be 0)
+    uint64 double_encrypted = 7;          // ciphertext of ciphertext (must be 0)
+    uint64 undecryptable = 8;             // ciphertext this key cannot open (must be 0)
+    uint64 history_versions = 9;
+    uint64 history_plaintext_required = 10;
+    uint64 history_double_encrypted = 11;
+    repeated string samples = 12;         // "<id>: <path>" of plaintext findings, up to 5
+}
+
+message VerifyEncryptionResponse {
+    bool encryption_enabled = 1;
+    bool at_rest_sealed = 2;              // the one-time migration ran and no reseal is pending
+    repeated EncryptionAudit collections = 3;
+}
+
 message GetServerInfoResponse {
     string version = 1;                // e.g. "2.15.0"
     string commit = 2;                 // short git commit, or "unknown"

+ 188 - 4
service/src/database_grpc_impl.cpp

@@ -415,6 +415,41 @@ grpc::Status DatabaseGrpcImpl::rejectMaskedFilters(
     return grpc::Status::OK;
 }
 
+// v2.17.0 - see the header.
+grpc::Status DatabaseGrpcImpl::refuseEncryptedFields(
+    grpc::ServerContext* context, const std::string& collection,
+    const std::vector<Filter>& filters, const std::vector<std::string>& fields,
+    const std::string& what) {
+    if (!encryption_.isEnabled()) return grpc::Status::OK;
+    const EncryptionRule rule = encryptionRuleFor(collection);
+    const bool whole = rule.wholeDocument;
+    std::vector<std::string> bad;
+    const auto check = [&](const std::string& f) {
+        if (f.empty() || isReservedField(f)) return;
+        if (encryption_.isEncryptedPath(f, rule)) bad.push_back(f);
+    };
+    for (const auto& f : filters) {
+        // A full-text search reads every value: over an encrypted collection
+        // it would search ciphertext. (Under the pattern rule it simply cannot
+        // see the sensitive values, which is the point of them.)
+        if (f.op == FilterOp::SEARCH) {
+            if (whole) bad.push_back("(search)");
+            continue;
+        }
+        check(f.field);
+    }
+    for (const auto& f : fields) check(f);
+    if (bad.empty()) return grpc::Status::OK;
+    std::string list;
+    for (const auto& b : bad) list += (list.empty() ? "" : ", ") + b;
+    attachErrorDetail(context, {{"reason", "encrypted_field"}, {"fields", bad}});
+    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                        "cannot " + what + " on a field stored encrypted (" + list +
+                        "): its stored form is ciphertext, so any comparison would be "
+                        "silently wrong. Look such records up by id, or by a hash kept "
+                        "in a non-sensitive field.");
+}
+
 grpc::Status DatabaseGrpcImpl::Insert(
     grpc::ServerContext* context,
     const pb::InsertRequest* request,
@@ -470,7 +505,7 @@ grpc::Status DatabaseGrpcImpl::Insert(
         }
 
         // Encrypt sensitive fields if needed
-        encryption_.encryptSensitiveFields(doc);
+        encryption_.encryptSensitiveFields(doc, encryptionRuleFor(request->collection()));
 
         std::string id = store_.insert(request->collection(), doc);
 
@@ -665,7 +700,7 @@ grpc::Status DatabaseGrpcImpl::Update(
             doc.updatedBy = request->actor();
         }
 
-        encryption_.encryptSensitiveFields(doc);
+        encryption_.encryptSensitiveFields(doc, encryptionRuleFor(request->collection()));
 
         bool success;
         if (request->expected_version() > 0) {
@@ -775,6 +810,26 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
             expectedVersion = request->expected_version();
         }
 
+        // v2.17.0 - a patch is a write like any other: values at encrypted
+        // paths are encrypted before they are merged. Before 2.17.0 this path
+        // never encrypted, so patching `creds.password` stored plaintext.
+        // Arithmetic on ciphertext is impossible, so an increment on an
+        // encrypted path is refused rather than failing as "non-numeric".
+        {
+            const EncryptionRule rule = encryptionRuleFor(request->collection());
+            if (increments && increments->is_object()) {
+                for (const auto& [path, delta] : increments->items()) {
+                    if (encryption_.isEnabled() && encryption_.isEncryptedPath(path, rule)) {
+                        attachErrorDetail(context, {{"reason", "encrypted_field"},
+                                                    {"fields", nlohmann::json::array({path})}});
+                        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                                            "cannot increment '" + path + "': it is stored encrypted");
+                    }
+                }
+            }
+            encryption_.encryptTree(patch, rule);
+        }
+
         nlohmann::json incremented = nlohmann::json::object();
         MemoryStore::PatchRefusal refusal;
         uint64_t newVersion = store_.patchDocument(
@@ -916,7 +971,7 @@ grpc::Status DatabaseGrpcImpl::Upsert(
             }
         }
 
-        encryption_.encryptSensitiveFields(doc);
+        encryption_.encryptSensitiveFields(doc, encryptionRuleFor(request->collection()));
 
         std::string id = store_.upsert(request->collection(), doc);
 
@@ -1360,7 +1415,7 @@ grpc::Status DatabaseGrpcImpl::BatchInsert(
                 doc.updatedBy = actor;
             }
 
-            encryption_.encryptSensitiveFields(doc);
+            encryption_.encryptSensitiveFields(doc, encryptionRuleFor(request->collection()));
 
             std::string id = store_.insert(request->collection(), doc);
             response->add_ids(id);
@@ -1558,6 +1613,11 @@ grpc::Status DatabaseGrpcImpl::Find(
     // A filter naming a masked path is refused: `salary > 100000` would leak a
     // value the caller is not permitted to read.
     if (auto st = rejectMaskedFilters(query.filters, dec.mask); !st.ok()) return st;
+    if (auto st = refuseEncryptedFields(context, targetCollection, query.filters,
+            {query.sort ? query.sort->field : std::string()}, "filter or sort");
+        !st.ok()) {
+        return st;   // v2.17.0
+    }
     // Row predicate AND-merges with the caller's filters, exactly as a view's
     // `where` already does.
     for (const auto& f : dec.row) query.filters.push_back(f);
@@ -1651,6 +1711,10 @@ grpc::Status DatabaseGrpcImpl::Count(
         return st;
     }
     if (auto st = rejectMaskedFilters(filters, dec.mask); !st.ok()) return st;
+    if (auto st = refuseEncryptedFields(context, targetCollection, filters, {}, "filter");
+        !st.ok()) {
+        return st;   // v2.17.0
+    }
     // Row predicate narrows the count, exactly as it narrows a Find.
     for (const auto& f : dec.row) filters.push_back(f);
 
@@ -1741,6 +1805,10 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
                                 std::string("Bad filter value: ") + e.what());
         }
         if (auto st = rejectMaskedFilters(filters, dec.mask); !st.ok()) return st;
+        if (auto st = refuseEncryptedFields(context, collection, filters, {}, "filter");
+            !st.ok()) {
+            return st;   // v2.17.0
+        }
         for (const auto& f : dec.row) filters.push_back(f);
 
         // v2.0 Stage 5 — LMDB-first SimilaritySearch. Same gate shape as
@@ -2187,6 +2255,13 @@ grpc::Status DatabaseGrpcImpl::SetAdd(
     if (auto st = gate(context, request->collection(), smartbotic::database::Access::Write, dec); !st.ok()) {
         return st;
     }
+    // v2.17.0 - set members are stored as plaintext strings and compared by
+    // value, so a set cannot live in an encrypted collection.
+    if (encryption_.isEnabled() && encryptionRuleFor(request->collection()).wholeDocument) {
+        attachErrorDetail(context, {{"reason", "encrypted_field"}, {"fields", nlohmann::json::array({"members"})}});
+        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
+                            "set operations are not available on an encrypted collection");
+    }
 
     if (service_.isReadOnly()) {
         return readOnlyStatus(context, "SetAdd", service_);
@@ -2222,6 +2297,13 @@ grpc::Status DatabaseGrpcImpl::SetRemove(
     if (auto st = gate(context, request->collection(), smartbotic::database::Access::Write, dec); !st.ok()) {
         return st;
     }
+    // v2.17.0 - set members are stored as plaintext strings and compared by
+    // value, so a set cannot live in an encrypted collection.
+    if (encryption_.isEnabled() && encryptionRuleFor(request->collection()).wholeDocument) {
+        attachErrorDetail(context, {{"reason", "encrypted_field"}, {"fields", nlohmann::json::array({"members"})}});
+        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
+                            "set operations are not available on an encrypted collection");
+    }
 
     if (service_.isReadOnly()) {
         return readOnlyStatus(context, "SetRemove", service_);
@@ -2318,6 +2400,23 @@ grpc::Status DatabaseGrpcImpl::CreateCollection(
 
     if (created) {
         persistence_.logCreateCollection(request->name(), opts);
+    } else if (store_.upgradeEncryptionOptions(request->name(), opts.encrypted, opts.sensitiveFields)) {
+        // v2.17.0 - the collection exists: until 2.17.0 its options were
+        // silently ignored here, so an `encrypted=true` asked of a collection
+        // created implicitly by an earlier write never took effect. Encryption
+        // can now be switched ON (never off) or extended with sensitive fields;
+        // the existing rows and their history are encrypted now, and the old
+        // plaintext copies (WAL, older snapshots, LMDB free pages) are removed
+        // at the next restart. The full options are logged so a replay
+        // re-applies the upgrade.
+        const auto full = store_.collectionOptions(request->name()).value_or(opts);
+        persistence_.logCreateCollection(request->name(), full);
+        const auto s = service_.encryptCollectionAtRest(request->name());
+        service_.requestResealAtNextBoot();
+        spdlog::warn("v2.17 encryption: {} upgraded (encrypted={}, {} sensitive field(s)); {} row(s) "
+                     "and {} history version(s) encrypted now; old plaintext copies are removed at "
+                     "the next restart", request->name(), full.encrypted, full.sensitiveFields.size(),
+                     s.rewritten + s.lmdbOnly, s.versions);
     }
 
     return grpc::Status::OK;
@@ -3188,6 +3287,70 @@ grpc::Status DatabaseGrpcImpl::GetServerInfo(
     return grpc::Status::OK;
 }
 
+grpc::Status DatabaseGrpcImpl::VerifyEncryption(
+    grpc::ServerContext* context,
+    const pb::VerifyEncryptionRequest* request,
+    pb::VerifyEncryptionResponse* response
+) {
+    if (auto st = requireAnyAdmin(context, "VerifyEncryption"); !st.ok()) return st;
+    response->set_encryption_enabled(encryption_.isEnabled());
+    response->set_at_rest_sealed(service_.atRestSealed());
+    if (!encryption_.isEnabled()) return grpc::Status::OK;
+    std::vector<std::string> names;
+    if (!request->collection().empty()) {
+        names.push_back(request->collection());
+    } else {
+        for (const auto& c : store_.listCollections()) {
+            if (!c.empty() && c[0] != '_') names.push_back(c);
+        }
+    }
+    try {
+        for (const auto& coll : names) {
+            const EncryptionRule rule = encryptionRuleFor(coll);
+            auto* a = response->add_collections();
+            a->set_collection(coll);
+            a->set_collection_encrypted(rule.wholeDocument);
+            for (const auto& f : rule.paths) a->add_sensitive_fields(f);
+            EncryptionManager::TreeAudit rows, hist;
+            uint64_t n = 0;
+            const auto rc = smartbotic::database::resolveCollection(coll);
+            if (auto* ds = service_.docStore(rc.project)) {
+                ds->export_scan(rc.collection, "", false, nullptr, [](uint64_t) {},
+                    [&](Document&& d, smartbotic::db::storage::DocumentStore::ExportVectorState,
+                        const float*, size_t) -> bool {
+                        ++n;
+                        const uint64_t before = rows.plaintextRequired;
+                        encryption_.auditTree(d.data(), rule, rows);
+                        if (rows.plaintextRequired > before && a->samples_size() < 5) {
+                            a->add_samples(d.id + ": " +
+                                (rows.plaintextPaths.empty() ? std::string("?") : rows.plaintextPaths.back()));
+                        }
+                        return true;
+                    });
+            }
+            uint64_t versions = 0;
+            if (auto* hs = service_.historyStore()) {
+                hs->rewrite(coll, [&](DocumentVersion& v) {
+                    ++versions;
+                    encryption_.auditTree(v.data(), rule, hist);
+                    return false;   // audit only: nothing is written
+                });
+            }
+            a->set_rows(n);
+            a->set_encrypted_values(rows.encryptedValues + hist.encryptedValues);
+            a->set_plaintext_required(rows.plaintextRequired);
+            a->set_double_encrypted(rows.doubleEncrypted);
+            a->set_undecryptable(rows.undecryptable + hist.undecryptable);
+            a->set_history_versions(versions);
+            a->set_history_plaintext_required(hist.plaintextRequired);
+            a->set_history_double_encrypted(hist.doubleEncrypted);
+        }
+    } catch (const std::exception& e) {
+        return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
+    }
+    return grpc::Status::OK;
+}
+
 grpc::Status DatabaseGrpcImpl::GetStats(
     grpc::ServerContext* context,
     const pb::GetStatsRequest* /*request*/,
@@ -3911,6 +4074,11 @@ grpc::Status DatabaseGrpcImpl::CreateRelation(
         r.child = request->child();
         r.childField = request->child_field();
         r.parent = request->parent();
+        if (auto st = refuseEncryptedFields(context, r.child, {}, {r.childField},
+                                            "declare a relation");
+            !st.ok()) {
+            return st;   // v2.17.0
+        }
         // v2.11.0 final review (finding 9) — VALIDATE, do not coerce. An
         // unrecognised on_delete used to become Restrict silently, which
         // stopped being a safe default the moment T12 made cascade/set_null
@@ -4479,8 +4647,19 @@ grpc::Status DatabaseGrpcImpl::CreateIndex(
         return grpc::Status::OK;
     }
     if (request->fields_size() > 0) {
+        std::vector<std::string> fs(request->fields().begin(), request->fields().end());
+        if (auto st = refuseEncryptedFields(context, request->collection(), {}, fs,
+                                            "declare a unique constraint");
+            !st.ok()) {
+            return st;   // v2.17.0
+        }
         return createCompositeUnique(context, request, response, dec);
     }
+    if (auto st = refuseEncryptedFields(context, request->collection(), {}, {request->field()},
+                                        "index");
+        !st.ok()) {
+        return st;   // v2.17.0
+    }
     if (request->field().empty()) {
         response->set_success(false);
         response->set_error("field is required");
@@ -4807,6 +4986,11 @@ grpc::Status DatabaseGrpcImpl::GetIndexValues(
         response->set_error("field is masked for this principal");
         return grpc::Status::OK;
     }
+    if (auto st = refuseEncryptedFields(context, request->collection(), {}, {request->field()},
+                                        "list index values");
+        !st.ok()) {
+        return st;   // v2.17.0
+    }
     try {
         const auto rc = smartbotic::database::resolveCollection(request->collection());
         auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(

+ 25 - 0
service/src/database_grpc_impl.hpp

@@ -440,6 +440,13 @@ public:
         pb::GetServerInfoResponse* response
     ) override;
 
+    // v2.17.0 - encryption-at-rest audit (admin, read-only).
+    grpc::Status VerifyEncryption(
+        grpc::ServerContext* context,
+        const pb::VerifyEncryptionRequest* request,
+        pb::VerifyEncryptionResponse* response
+    ) override;
+
     grpc::Status GetStats(
         grpc::ServerContext* context,
         const pb::GetStatsRequest* request,
@@ -643,6 +650,24 @@ private:
     static grpc::Status rejectMaskedFilters(
         const std::vector<smartbotic::database::Filter>& filters,
         const std::vector<std::string>& mask);
+
+    // v2.17.0 - a value stored encrypted is ciphertext under a random IV, so a
+    // filter, sort, index, constraint or relation over it is silently wrong
+    // (never matches, never collides). Refused instead: INVALID_ARGUMENT,
+    // reason `encrypted_field`, the fields named. Metadata fields are never
+    // encrypted and always allowed.
+    // v2.17.0 - which values of `collection` are stored encrypted.
+    EncryptionRule encryptionRuleFor(const std::string& collection) const {
+        EncryptionRule r;
+        store_.encryptionOptionsFor(collection, r.wholeDocument, r.paths);
+        return r;
+    }
+
+    grpc::Status refuseEncryptedFields(grpc::ServerContext* context,
+                                       const std::string& collection,
+                                       const std::vector<smartbotic::database::Filter>& filters,
+                                       const std::vector<std::string>& fields,
+                                       const std::string& what);
     std::chrono::steady_clock::time_point startTime_ = std::chrono::steady_clock::now();
 
     // v1.6.2 — per-RPC-type streaming concurrency limits (set by DatabaseService

+ 206 - 5
service/src/database_service.cpp

@@ -302,6 +302,10 @@ bool DatabaseService::initialize() {
         // telling the operator to restart, which re-incurs it). Reads keep
         // gating on the RAW counter - a stale row genuinely means MemoryStore
         // is ahead, and that fallback must stay.
+        // v2.17.0 - encrypt what must be encrypted, and remove the plaintext
+        // copies, before anything can read or replicate them.
+        migrateEncryptionAtRest();
+
         store_->markMirrorDriftBaseline();
         if (store_->mirrorDriftBaseline() > 0) {
             spdlog::warn("mirror drift at READY: {} - accrued on the boot path (see the "
@@ -492,6 +496,9 @@ bool DatabaseService::runMigrations() {
 
     migrationRunner_ = std::make_unique<MigrationRunner>(
         *store_, *view_manager_, *relation_manager_, migrationConfig);
+    migrationRunner_->setDocumentPreparer([this](const std::string& collection, Document& doc) {
+        encryption_->encryptSensitiveFields(doc, encryptionRuleFor(collection));   // v2.17.0
+    });
     const bool ok = migrationRunner_->runMigrations();
 
     // v2.11.0 close-out — a `create_relation` migration op only PERSISTS the
@@ -519,6 +526,166 @@ nlohmann::json DatabaseService::schemaView(const nlohmann::json& body) const {
     return copy;
 }
 
+DatabaseService::AtRestStats DatabaseService::encryptCollectionAtRest(const std::string& collection) {
+    AtRestStats st;
+    if (!encryption_ || !encryption_->isEnabled()) return st;
+    const EncryptionRule rule = encryptionRuleFor(collection);
+    const auto transform = [&](nlohmann::json& body) { return encryption_->encryptTree(body, rule); };
+
+    // LMDB holds every row (MemoryStore may have evicted some); find the rows
+    // that still hold plaintext, then rewrite each under the collection lock.
+    smartbotic::db::storage::DocumentStore* ds = nullptr;
+    std::string bare;
+    // The names MemoryStore may hold this collection's rows under: the
+    // qualified form and, in the default project, the bare one (see
+    // MemoryStore::encryptionOptionsFor). Both map to the same LMDB sub-db.
+    std::vector<std::string> names{collection};
+    try {
+        const auto rc = smartbotic::database::resolveCollection(collection);
+        ds = docStore(rc.project);
+        bare = rc.collection;
+        if (rc.qualified != collection) names.push_back(rc.qualified);
+        if (rc.project == smartbotic::database::kDefaultProject && rc.collection != collection) {
+            names.push_back(rc.collection);
+        }
+    } catch (const std::exception&) {
+    }
+    std::vector<std::string> ids;
+    if (ds != nullptr) {
+        ds->export_scan(bare, "", false, nullptr, [](uint64_t) {},
+            [&](Document&& d, smartbotic::db::storage::DocumentStore::ExportVectorState,
+                const float*, size_t) -> bool {
+                ++st.scanned;
+                EncryptionManager::TreeAudit a;
+                encryption_->auditTree(d.data(), rule, a);
+                if (a.plaintextRequired > 0) ids.push_back(d.id);
+                return true;
+            });
+    }
+    for (const auto& id : ids) {
+        int r = -1;
+        for (const auto& n : names) {
+            r = store_->rewriteBodyInPlace(n, id, transform);
+            if (r != -1) break;
+        }
+        if (r == 1) {
+            ++st.rewritten;
+        } else if (r == -1 && ds != nullptr) {
+            // Not in MemoryStore at all: the LMDB row is the only copy.
+            if (auto d = ds->get(bare, id)) {
+                nlohmann::json b = d->data();
+                if (transform(b)) {
+                    d->set_data(b);
+                    d->encrypted = true;
+                    ds->put(bare, id, *d);
+                    ++st.lmdbOnly;
+                }
+            }
+        }
+    }
+    if (history_store_) {
+        for (const auto& n : names) {
+            st.versions += history_store_->rewrite(n, [&](DocumentVersion& v) {
+                nlohmann::json b = v.data();
+                if (!transform(b)) return false;
+                v.set_data(b);
+                v.encrypted = true;
+                return true;
+            });
+        }
+    }
+    return st;
+}
+
+void DatabaseService::requestResealAtNextBoot() {
+    std::ofstream(config_.dataDirectory / "encryption-reseal.pending") << "1\n";
+}
+
+void DatabaseService::migrateEncryptionAtRest() {
+    namespace fs = std::filesystem;
+    const fs::path marker = config_.dataDirectory / "encryption-at-rest.v1";
+    const fs::path reseal = config_.dataDirectory / "encryption-reseal.pending";
+    std::error_code ec;
+    const bool firstRun = !fs::exists(marker, ec);
+    const bool resealPending = fs::exists(reseal, ec);
+    if (!encryption_ || !encryption_->isEnabled()) {
+        if (firstRun) spdlog::warn("v2.17 at-rest: encryption is disabled; nothing is encrypted at rest");
+        return;
+    }
+    if (!firstRun && !resealPending) return;
+
+    AtRestStats total;
+    if (firstRun) {
+        spdlog::warn("v2.17 at-rest: one-time migration - encrypting values stored in plaintext "
+                     "that must be encrypted (encrypted collections, sensitive_fields, the "
+                     "sensitive name patterns at any depth)");
+        std::set<std::string> done;   // canonical names: aliases share one LMDB sub-db
+        for (const auto& coll : store_->listCollections()) {
+            if (coll.empty() || coll[0] == '_') continue;
+            std::string canonical = coll;
+            try {
+                canonical = smartbotic::database::resolveCollection(coll).qualified;
+            } catch (const std::exception&) {
+            }
+            if (!done.insert(canonical).second) continue;
+#ifdef HAVE_SYSTEMD
+            // Each collection is a scan plus a history rewrite: on a large
+            // dataset the whole pass outlasts TimeoutStartSec. Same protocol
+            // the v1 migration and recovery use.
+            sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
+            sd_notify(0, ("STATUS=Encrypting at rest: " + canonical).c_str());
+#endif
+            const auto s = encryptCollectionAtRest(canonical);
+            total.scanned += s.scanned;
+            total.rewritten += s.rewritten;
+            total.lmdbOnly += s.lmdbOnly;
+            total.versions += s.versions;
+            if (s.rewritten + s.lmdbOnly + s.versions > 0) {
+                spdlog::warn("v2.17 at-rest: {}: {} row(s) and {} history version(s) encrypted "
+                             "(of {} row(s) scanned)", canonical, s.rewritten + s.lmdbOnly, s.versions,
+                             s.scanned);
+            }
+        }
+        spdlog::warn("v2.17 at-rest: {} row(s) scanned, {} encrypted in place ({} LMDB-only), "
+                     "{} history version(s) encrypted", total.scanned,
+                     total.rewritten + total.lmdbOnly, total.lmdbOnly, total.versions);
+    }
+
+    // The seal: the rewrite replaced plaintext in the live stores, but older
+    // snapshots, the WAL and LMDB's freed pages still hold it.
+    std::string err;
+    size_t snaps = 0, wals = 0;
+    if (!persistence_->sealAfterRewrite(*store_, err, snaps, wals)) {
+        spdlog::error("v2.17 at-rest: seal FAILED ({}); old plaintext copies remain in the WAL / "
+                      "snapshots. Serving continues; the next boot retries.", err);
+        requestResealAtNextBoot();
+        return;
+    }
+    for (const auto& p : projects_->listOpen()) {
+        uint64_t before = 0, after = 0;
+        std::string cerr;
+        if (projects_->compact(p, before, after, cerr)) {
+            spdlog::info("v2.17 at-rest: project '{}' compacted, {} -> {} bytes", p, before, after);
+        } else {
+            spdlog::error("v2.17 at-rest: project '{}' compaction failed: {} - freed pages may "
+                          "still hold old plaintext; the next boot retries", p, cerr);
+            requestResealAtNextBoot();
+            applyIndexDeclarations();
+            applyRelationDeclarations(/*afterMigrations=*/true);
+            return;
+        }
+    }
+    // Compaction reopened every env: per-store arming must be applied again.
+    applyIndexDeclarations();
+    applyRelationDeclarations(/*afterMigrations=*/true);
+
+    std::ofstream(marker) << "encrypted at rest by 2.17.0\n";
+    fs::remove(reseal, ec);
+    spdlog::warn("v2.17 at-rest: sealed - {} old snapshot(s) and {} WAL file(s) removed, every "
+                 "project compacted. Copies made BEFORE this boot (backups, pre-upgrade copies, "
+                 "replicas, disk blocks) are outside the database's reach.", snaps, wals);
+}
+
 void DatabaseService::applySchemaDeclarations() {
     size_t armed = 0;
     for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
@@ -553,7 +720,41 @@ void DatabaseService::applyIndexDeclarations() {
             auto* lmdb =
                 dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
             if (lmdb == nullptr) continue;
-            lmdb->set_indexed_fields(rc.collection, cfg.indexedFields);
+            // v2.17.0 - an index over a field stored encrypted indexes
+            // ciphertext under random IVs: lookups never hit and a unique
+            // constraint never fires. Such declarations are disarmed (neither
+            // maintained nor consulted) and named, so the operator drops them.
+            CollectionCfg armed = cfg;
+            if (encryption_ && encryption_->isEnabled()) {
+                const EncryptionRule rule = encryptionRuleFor(qualified);
+                const auto enc = [&](const std::string& f) {
+                    return !isReservedField(f) && encryption_->isEncryptedPath(f, rule);
+                };
+                const auto strip = [&](std::vector<std::string>& v, const char* what) {
+                    for (auto it = v.begin(); it != v.end();) {
+                        if (enc(*it)) {
+                            spdlog::error("v2.17 encryption: {} on {}#{} is DISARMED - the field is "
+                                          "stored encrypted. Drop it.", what, qualified, *it);
+                            it = v.erase(it);
+                        } else {
+                            ++it;
+                        }
+                    }
+                };
+                strip(armed.indexedFields, "index");
+                strip(armed.uniqueFields, "unique constraint");
+                for (auto it = armed.compositeUniques.begin(); it != armed.compositeUniques.end();) {
+                    if (std::any_of(it->begin(), it->end(), enc)) {
+                        spdlog::error("v2.17 encryption: a composite unique constraint on {} is "
+                                      "DISARMED - one of its fields is stored encrypted. Drop it.",
+                                      qualified);
+                        it = armed.compositeUniques.erase(it);
+                    } else {
+                        ++it;
+                    }
+                }
+            }
+            lmdb->set_indexed_fields(rc.collection, armed.indexedFields);
             // v2.11.0 T11 — arm uniqueFields the same way. This is the fix
             // for the exact failure mode the type was built to avoid:
             // uniqueFields has been persisted since T8 with no RPC or proto
@@ -561,12 +762,12 @@ void DatabaseService::applyIndexDeclarations() {
             // set_unique_fields is reachable, a restart that skipped this
             // call would silently stop enforcing a constraint every write
             // handler still advertises as active.
-            lmdb->set_unique_fields(rc.collection, cfg.uniqueFields);
+            lmdb->set_unique_fields(rc.collection, armed.uniqueFields);
             // v2.12.0 - composite constraints, armed the same way and for the
             // same reason: skipping this would stop enforcing a constraint the
             // record still declares. Self-healed below if its sub-db is gone.
-            lmdb->set_composite_uniques(rc.collection, cfg.compositeUniques);
-            for (const auto& cf : cfg.compositeUniques) {
+            lmdb->set_composite_uniques(rc.collection, armed.compositeUniques);
+            for (const auto& cf : armed.compositeUniques) {
                 if (lmdb->has_composite_unique_subdb(rc.collection, cf)) continue;
                 uint64_t rows = 0;
                 auto dupes = lmdb->build_composite_unique(rc.collection, cf, rows);
@@ -597,7 +798,7 @@ void DatabaseService::applyIndexDeclarations() {
             // would maintain the new index correctly, but rows written BEFORE the
             // upgrade would have no postings, so an indexed query would silently
             // return only the newer ones. Rebuilding is the only safe reading.
-            for (const auto& field : cfg.indexedFields) {
+            for (const auto& field : armed.indexedFields) {
                 if (lmdb->index_stats(rc.collection, field).has_value()) continue;
                 const uint64_t rows = lmdb->build_index(rc.collection, field);
                 spdlog::warn("v2.9 index: rebuilt {}#{} over {} row(s) - the index "

+ 30 - 0
service/src/database_service.hpp

@@ -381,6 +381,11 @@ private:
     // record can) is logged and NOT armed.
     void applySchemaDeclarations();
 
+    // v2.17.0 - the one-time at-rest encryption migration and the seal that
+    // removes old plaintext copies. Runs at the end of initialize(), before any
+    // background thread or listener starts.
+    void migrateEncryptionAtRest();
+
 public:
     // v2.16.0 - the armed schemas; the gRPC handlers change them.
     smartbotic::db::schema::SchemaRegistry& schemaRegistry() { return schemas_; }
@@ -388,6 +393,31 @@ public:
     // sensitive fields decrypted. A copy; used by the write check, the
     // existing-row check and the suggester alike, so they cannot disagree.
     nlohmann::json schemaView(const nlohmann::json& body) const;
+    // v2.17.0 - encrypt, in place, every stored body of `collection` (live
+    // rows, LMDB-only rows and history versions) that holds plaintext its rule
+    // requires encrypted. Idempotent: ciphertext is never encrypted again.
+    struct AtRestStats {
+        uint64_t scanned = 0, rewritten = 0, lmdbOnly = 0, versions = 0;
+    };
+    AtRestStats encryptCollectionAtRest(const std::string& collection);
+
+    // v2.17.0 - old plaintext copies (WAL, older snapshots, LMDB free pages)
+    // can only be removed at boot; ask the next boot to do it.
+    void requestResealAtNextBoot();
+    // v2.17.0 - the one-time migration ran and no reseal is pending.
+    bool atRestSealed() const {
+        std::error_code ec;
+        return std::filesystem::exists(config_.dataDirectory / "encryption-at-rest.v1", ec) &&
+               !std::filesystem::exists(config_.dataDirectory / "encryption-reseal.pending", ec);
+    }
+    HistoryStore* historyStore() { return history_store_.get(); }
+
+    // v2.17.0 - which values of `collection` are stored encrypted.
+    EncryptionRule encryptionRuleFor(const std::string& collection) const {
+        EncryptionRule r;
+        store_->encryptionOptionsFor(collection, r.wholeDocument, r.paths);
+        return r;
+    }
     bool isSensitivePath(const std::string& path) const { return encryption_->isSensitiveField(path); }
 
 private:

+ 155 - 29
service/src/encryption/encryption_manager.cpp

@@ -20,6 +20,14 @@ constexpr size_t KEY_SIZE = 32;     // AES-256
 constexpr size_t IV_SIZE = 12;      // GCM IV
 constexpr size_t TAG_SIZE = 16;     // GCM Auth tag
 constexpr char ENCRYPTED_PREFIX[] = "$ENC$";
+// v2.17.0 - a non-string value of an encrypted collection: the ciphertext of
+// its JSON text, so a read restores the original type. Distinct from $ENC$ at
+// its fifth character, so neither prefix is a prefix of the other.
+constexpr char ENCRYPTED_JSON_PREFIX[] = "$ENCJ$";
+
+bool isCiphertext(const std::string& s) {
+    return s.rfind(ENCRYPTED_PREFIX, 0) == 0 || s.rfind(ENCRYPTED_JSON_PREFIX, 0) == 0;
+}
 
 // Base64 encoding/decoding helpers
 std::string base64Encode(const std::vector<uint8_t>& data) {
@@ -82,11 +90,21 @@ std::vector<uint8_t> base64Decode(const std::string& encoded) {
 }
 
 // Convert glob pattern to regex
+//
+// v2.17.0 - a leading "*." also matches at the TOP level: "*.password" is
+// "(?:.*\.)?password". Before, it became ".*\.password", which needs a dot,
+// so a top-level `password` / `api_key` / `token` / `secret` / `credentials`
+// was stored in plaintext - the opposite of what every reader assumed.
 std::string globToRegex(const std::string& glob) {
     std::string regex;
     regex.reserve(glob.size() * 2);
 
-    for (char c : glob) {
+    std::string_view rest(glob);
+    if (rest.rfind("*.", 0) == 0) {
+        regex += "(?:.*\\.)?";
+        rest.remove_prefix(2);
+    }
+    for (char c : rest) {
         switch (c) {
             case '*':
                 regex += ".*";
@@ -187,24 +205,130 @@ bool EncryptionManager::initialize() {
     return true;
 }
 
-void EncryptionManager::encryptSensitiveFields(Document& doc) {
+void EncryptionManager::encryptSensitiveFields(Document& doc, const EncryptionRule& rule) {
     if (!isEnabled()) {
         return;
     }
 
     std::lock_guard lock(mutex_);
 
-    // Materialise once, mutate via the existing recursive helper, then
-    // re-encode. encryptJsonField mutates the tree in place.
+    // Materialise once, mutate in place, re-encode.
     nlohmann::json tree = doc.data();
-    encryptJsonField(tree, "");
+    encryptJsonFieldEx(tree, "", rule);
     doc.set_data(tree);
 
     doc.encrypted = true;
 }
 
+bool EncryptionManager::encryptTree(nlohmann::json& tree, const EncryptionRule& rule) {
+    if (!isEnabled()) return false;
+    std::lock_guard lock(mutex_);
+    return encryptJsonFieldEx(tree, "", rule);
+}
+
+std::string EncryptionManager::encryptTyped(const nlohmann::json& value) {
+    const std::string text = value.dump();
+    std::vector<uint8_t> bytes(text.begin(), text.end());
+    return std::string(ENCRYPTED_JSON_PREFIX) + base64Encode(encryptData(bytes));
+}
+
+// Strings at an encrypted path become $ENC$; in a whole-document collection
+// every other non-null scalar becomes $ENCJ$. Objects and arrays are walked.
+// An existing ciphertext string is never touched (no double encryption).
+bool EncryptionManager::encryptJsonFieldEx(nlohmann::json& obj, const std::string& path, const EncryptionRule& rule) {
+    const bool whole = rule.wholeDocument;
+    bool changed = false;
+    const auto visit = [&](nlohmann::json& value, const std::string& fieldPath) {
+        if (value.is_object() || value.is_array()) {
+            changed |= encryptJsonFieldEx(value, fieldPath, rule);
+            return;
+        }
+        if (value.is_null()) return;
+        if (!isEncryptedPath(fieldPath, rule)) return;
+        if (value.is_string()) {
+            const auto& s = value.get_ref<const std::string&>();
+            if (isCiphertext(s)) return;
+            value = encryptValue(s);
+            changed = true;
+        } else if (whole) {
+            value = encryptTyped(value);
+            changed = true;
+        }
+    };
+    if (obj.is_object()) {
+        for (auto& [key, value] : obj.items()) {
+            visit(value, path.empty() ? key : path + "." + key);
+        }
+    } else if (obj.is_array()) {
+        // Array elements share their array's path for the pattern rule: an
+        // element of `tokens` is as sensitive as `tokens` itself.
+        for (auto& el : obj) visit(el, path);
+    }
+    return changed;
+}
+
+bool EncryptionManager::isEncryptedPath(const std::string& fieldPath, const EncryptionRule& rule) const {
+    if (rule.wholeDocument) return !fieldPath.empty();
+    // The path itself or any ancestor: under `credentials` everything is secret.
+    std::string prefix;
+    size_t start = 0;
+    while (true) {
+        const size_t dot = fieldPath.find('.', start);
+        prefix = fieldPath.substr(0, dot);
+        if (isSensitiveField(prefix)) return true;
+        if (std::find(rule.paths.begin(), rule.paths.end(), prefix) != rule.paths.end()) return true;
+        if (dot == std::string::npos) return false;
+        start = dot + 1;
+    }
+}
+
+void EncryptionManager::auditTree(const nlohmann::json& tree, const EncryptionRule& rule, TreeAudit& out) {
+    std::lock_guard lock(mutex_);
+    auditJson(tree, "", rule, out);
+}
+
+void EncryptionManager::auditJson(const nlohmann::json& v, const std::string& path, const EncryptionRule& rule,
+                                  TreeAudit& out) {
+    if (v.is_object()) {
+        for (const auto& [k, sub] : v.items()) auditJson(sub, path.empty() ? k : path + "." + k, rule, out);
+        return;
+    }
+    if (v.is_array()) {
+        for (const auto& el : v) auditJson(el, path, rule, out);
+        return;
+    }
+    if (v.is_string() && isCiphertext(v.get_ref<const std::string&>())) {
+        ++out.encryptedValues;
+        const auto& s = v.get_ref<const std::string&>();
+        try {
+            std::string plain;
+            if (s.rfind(ENCRYPTED_JSON_PREFIX, 0) == 0) {
+                auto bytes = decryptData(base64Decode(s.substr(strlen(ENCRYPTED_JSON_PREFIX))));
+                plain.assign(bytes.begin(), bytes.end());
+            } else {
+                plain = decryptValue(s);
+            }
+            if (isCiphertext(plain)) ++out.doubleEncrypted;
+        } catch (...) {
+            ++out.undecryptable;
+        }
+        return;
+    }
+    if (v.is_null() || path.empty()) return;
+    const bool required = isEncryptedPath(path, rule) && (rule.wholeDocument || v.is_string());
+    if (required) {
+        ++out.plaintextRequired;
+        if (out.plaintextPaths.size() < 5) out.plaintextPaths.push_back(path);
+    }
+}
+
 void EncryptionManager::decryptSensitiveFields(Document& doc) {
-    if (!isEnabled() || !doc.encrypted) {
+    // v2.17.0 - no longer gated on doc.encrypted. That marker was set only by
+    // the paths that called encryptSensitiveFields, so a document created by a
+    // set operation or a migration op and later PATCHED with a sensitive value
+    // held ciphertext with the marker false, and read back as ciphertext.
+    // Decryption touches only $ENC$/$ENCJ$ strings, so plaintext is safe.
+    if (!isEnabled()) {
         return;
     }
 
@@ -225,7 +349,7 @@ void EncryptionManager::decryptTree(nlohmann::json& tree) {
 void EncryptionManager::decryptSensitiveFields(DocumentVersion& ver,
                                                const std::string& collection,
                                                const std::string& id) {
-    if (!isEnabled() || !ver.encrypted) {
+    if (!isEnabled()) {   // v2.17.0 - see the Document overload
         return;
     }
 
@@ -706,31 +830,33 @@ void EncryptionManager::encryptJsonField(nlohmann::json& obj, const std::string&
 
 void EncryptionManager::decryptJsonField(nlohmann::json& obj, const std::string& path,
                                          const std::string& collection, const std::string& docId) {
-    if (obj.is_object()) {
-        for (auto& [key, value] : obj.items()) {
-            std::string fieldPath = path.empty() ? key : path + "." + key;
-
-            if (value.is_string()) {
-                std::string str = value.get<std::string>();
-                if (str.find(ENCRYPTED_PREFIX) == 0) {
-                    // Decrypt this field
-                    try {
-                        value = decryptValue(str);
-                    } catch (const std::exception& e) {
-                        spdlog::error("Failed to decrypt field {} in document {}/{}: {}",
-                                     fieldPath, collection, docId, e.what());
-                    }
-                }
-            } else if (value.is_object() || value.is_array()) {
-                // Recurse into nested objects/arrays
-                decryptJsonField(value, fieldPath, collection, docId);
+    // One value: a ciphertext string is decrypted ($ENCJ$ back to its JSON
+    // type), an object or array is walked. v2.17.0 - array ELEMENTS are
+    // handled too; before, a ciphertext string directly inside an array was
+    // never decrypted (and, symmetrically, never encrypted).
+    const auto one = [&](nlohmann::json& value, const std::string& fieldPath) {
+        if (value.is_object() || value.is_array()) {
+            decryptJsonField(value, fieldPath, collection, docId);
+            return;
+        }
+        if (!value.is_string()) return;
+        const std::string& str = value.get_ref<const std::string&>();
+        try {
+            if (str.rfind(ENCRYPTED_JSON_PREFIX, 0) == 0) {
+                auto bytes = decryptData(base64Decode(str.substr(strlen(ENCRYPTED_JSON_PREFIX))));
+                value = nlohmann::json::parse(std::string(bytes.begin(), bytes.end()));
+            } else if (str.rfind(ENCRYPTED_PREFIX, 0) == 0) {
+                value = decryptValue(str);
             }
+        } catch (const std::exception& e) {
+            spdlog::error("Failed to decrypt field {} in document {}/{}: {}",
+                          fieldPath, collection, docId, e.what());
         }
+    };
+    if (obj.is_object()) {
+        for (auto& [key, value] : obj.items()) one(value, path.empty() ? key : path + "." + key);
     } else if (obj.is_array()) {
-        for (size_t i = 0; i < obj.size(); ++i) {
-            std::string fieldPath = path + "[" + std::to_string(i) + "]";
-            decryptJsonField(obj[i], fieldPath, collection, docId);
-        }
+        for (size_t i = 0; i < obj.size(); ++i) one(obj[i], path + "[" + std::to_string(i) + "]");
     }
 }
 

+ 54 - 2
service/src/encryption/encryption_manager.hpp

@@ -15,6 +15,19 @@ namespace smartbotic::database {
  * Encryption manager for field-level encryption of sensitive data.
  * Uses AES-256-GCM for authenticated encryption.
  */
+/**
+ * v2.17.0 - which values of a collection are stored encrypted.
+ *  - wholeDocument: the collection's `encrypted` option - every non-null value;
+ *  - paths: the collection's `sensitive_fields` option - these paths and
+ *    everything under them (before 2.17.0 this option was stored, returned by
+ *    reads, and never used);
+ *  - and always the built-in sensitive patterns (*.password, *.api_key, ...).
+ */
+struct EncryptionRule {
+    bool wholeDocument = false;
+    std::vector<std::string> paths;
+};
+
 class EncryptionManager {
 public:
     struct Config {
@@ -48,9 +61,45 @@ public:
     [[nodiscard]] bool isEnabled() const { return config_.enabled && initialized_; }
 
     /**
-     * Encrypt sensitive fields in a document.
+     * Encrypt what must be encrypted in a document.
+     *
+     * v2.17.0 - `wholeDocument` is the collection's `encrypted` option. Before
+     * 2.17.0 that option was stored and reported and NOTHING read it: only
+     * fields matching the sensitive patterns were ever encrypted. Now an
+     * encrypted collection encrypts EVERY non-null value (strings as $ENC$,
+     * other types as $ENCJ$ so a read restores the type); property names stay
+     * plaintext. Without it, the sensitive-path rule applies (strings only).
+     *
+     * Never encrypts a value twice: a string already carrying $ENC$ / $ENCJ$
+     * is left as it is. That is what makes the at-rest migration idempotent.
      */
-    void encryptSensitiveFields(Document& doc);
+    void encryptSensitiveFields(Document& doc, const EncryptionRule& rule = {});
+
+    /**
+     * v2.17.0 - the same rule on a bare tree (a patch, a stored body, a
+     * version). Null values are left alone: in a merge patch null means
+     * "remove this field". Returns true if anything was encrypted.
+     */
+    bool encryptTree(nlohmann::json& tree, const EncryptionRule& rule);
+
+    /**
+     * v2.17.0 - is a value at `fieldPath` stored encrypted? True for every
+     * user field of an encrypted collection, and for a path matching a
+     * sensitive pattern or lying under one. Such a field cannot be filtered,
+     * sorted, indexed or constrained: the stored form is ciphertext under a
+     * random IV, so any comparison would be silently wrong.
+     */
+    [[nodiscard]] bool isEncryptedPath(const std::string& fieldPath, const EncryptionRule& rule) const;
+
+    // v2.17.0 - what the at-rest verifier counts in a stored tree.
+    struct TreeAudit {
+        uint64_t encryptedValues = 0;    // values stored as ciphertext
+        uint64_t plaintextRequired = 0;  // plaintext where the rule requires ciphertext
+        uint64_t doubleEncrypted = 0;    // ciphertext whose plaintext is ciphertext again
+        uint64_t undecryptable = 0;      // ciphertext that does not decrypt with this key
+        std::vector<std::string> plaintextPaths;   // up to a few, for the report
+    };
+    void auditTree(const nlohmann::json& tree, const EncryptionRule& rule, TreeAudit& out);
 
     /**
      * Decrypt sensitive fields in a document.
@@ -127,6 +176,9 @@ private:
     bool saveKeyToFile();
 
     void encryptJsonField(nlohmann::json& obj, const std::string& path);
+    bool encryptJsonFieldEx(nlohmann::json& obj, const std::string& path, const EncryptionRule& rule);
+    void auditJson(const nlohmann::json& v, const std::string& path, const EncryptionRule& rule, TreeAudit& out);
+    std::string encryptTyped(const nlohmann::json& value);
     void decryptJsonField(nlohmann::json& obj, const std::string& path,
                          const std::string& collection = "", const std::string& docId = "");
     void preserveUnchangedJsonField(nlohmann::json& newObj, const nlohmann::json& existingObj,

+ 85 - 0
service/src/memory_store.cpp

@@ -326,6 +326,91 @@ bool MemoryStore::collectionExists(const std::string& name) const {
     return collections_.find(name) != collections_.end();
 }
 
+bool MemoryStore::isCollectionEncrypted(const std::string& name) const {
+    std::shared_lock<std::shared_mutex> lock(globalMutex_);
+    auto it = collections_.find(name);
+    return it != collections_.end() && it->second->options.encrypted;
+}
+
+std::optional<CollectionOptions> MemoryStore::collectionOptions(const std::string& name) const {
+    std::shared_lock<std::shared_mutex> lock(globalMutex_);
+    auto it = collections_.find(name);
+    if (it == collections_.end()) return std::nullopt;
+    return it->second->options;
+}
+
+void MemoryStore::encryptionOptionsFor(const std::string& name, bool& encrypted,
+                                       std::vector<std::string>& sensitiveFields) const {
+    encrypted = false;
+    sensitiveFields.clear();
+    static const std::string kDefaultPrefix = "default:";
+    std::vector<std::string> names{name};
+    if (name.rfind(kDefaultPrefix, 0) == 0) {
+        names.push_back(name.substr(kDefaultPrefix.size()));
+    } else if (name.find(':') == std::string::npos) {
+        names.push_back(kDefaultPrefix + name);
+    }
+    std::shared_lock<std::shared_mutex> lock(globalMutex_);
+    for (const auto& n : names) {
+        auto it = collections_.find(n);
+        if (it == collections_.end()) continue;
+        const auto& o = it->second->options;
+        encrypted = encrypted || o.encrypted;
+        for (const auto& f : o.sensitiveFields) {
+            if (std::find(sensitiveFields.begin(), sensitiveFields.end(), f) == sensitiveFields.end()) {
+                sensitiveFields.push_back(f);
+            }
+        }
+    }
+}
+
+bool MemoryStore::upgradeEncryptionOptions(const std::string& name, bool encrypted,
+                                           const std::vector<std::string>& sensitiveFields) {
+    std::shared_lock<std::shared_mutex> lock(globalMutex_);
+    auto it = collections_.find(name);
+    if (it == collections_.end()) return false;
+    std::unique_lock<std::shared_mutex> collLock(it->second->mutex);
+    auto& o = it->second->options;
+    bool changed = false;
+    if (encrypted && !o.encrypted) {
+        o.encrypted = true;
+        changed = true;
+    }
+    for (const auto& f : sensitiveFields) {
+        if (std::find(o.sensitiveFields.begin(), o.sensitiveFields.end(), f) == o.sensitiveFields.end()) {
+            o.sensitiveFields.push_back(f);
+            changed = true;
+        }
+    }
+    return changed;
+}
+
+int MemoryStore::rewriteBodyInPlace(const std::string& collection, const std::string& id,
+                                    const std::function<bool(nlohmann::json&)>& transform) {
+    // Look up, never create: the migration probes aliases ("x", "default:x"),
+    // and creating the one that does not exist would conjure an empty
+    // collection - found on a copy of zeus, where it made a bare-named legacy
+    // collection suddenly readable under its qualified name.
+    CollectionData* coll = const_cast<CollectionData*>(getCollection(collection));
+    if (coll == nullptr) return -1;
+    InFlightWriteGuard inFlight(*coll, id);
+    reloadIfEvicted(collection, id);
+    std::unique_lock<std::shared_mutex> lock(coll->mutex);
+    auto it = coll->documents.find(id);
+    if (it == coll->documents.end()) return -1;
+    nlohmann::json body = it->second.data();
+    if (!transform(body)) return 0;
+    it->second.set_data(body);
+    it->second.encrypted = true;
+    // The vector is untouched; the document and its marker commit together.
+    mirrorDocOrUndo(collection, id, it->second, EventType::UPDATE, [] {},
+                    smartbotic::db::storage::VectorChange::keep());
+    const Document copy = it->second;
+    lock.unlock();
+    emitPersist(collection, id, copy, EventType::UPDATE);
+    return 1;
+}
+
 // ===== Document CRUD =====
 
 void MemoryStore::withCollectionWriteLock(const std::string& collection,

+ 32 - 0
service/src/memory_store.hpp

@@ -414,6 +414,38 @@ public:
      */
     [[nodiscard]] bool collectionExists(const std::string& name) const;
 
+    // v2.17.0 - the collection's `encrypted` option: every value of its
+    // documents is stored encrypted. False for an unknown collection.
+    [[nodiscard]] bool isCollectionEncrypted(const std::string& name) const;
+    // v2.17.0 - the collection's options, nullopt if unknown.
+    [[nodiscard]] std::optional<CollectionOptions> collectionOptions(const std::string& name) const;
+
+    // v2.17.0 - the encryption options that apply to `name`, merged with its
+    // alias in the default project ("x" <-> "default:x"): `encrypted` OR'd,
+    // `sensitive_fields` united. MemoryStore keys collections by the string as
+    // given, so a migration's `create_collection "x"` (bare) and a client's
+    // writes to "default:x" were two collections, and options declared in the
+    // migration never applied to the client's rows.
+    void encryptionOptionsFor(const std::string& name, bool& encrypted,
+                              std::vector<std::string>& sensitiveFields) const;
+
+    // v2.17.0 - UPGRADE an existing collection's encryption options: switch
+    // `encrypted` on, add `sensitive_fields`. Never removes either (that would
+    // need every row decrypted). Returns true if anything changed. Applied by
+    // CreateCollection on an existing collection and by WAL replay of its entry.
+    bool upgradeEncryptionOptions(const std::string& name, bool encrypted,
+                                  const std::vector<std::string>& sensitiveFields);
+
+    // v2.17.0 - replace a document's body IN PLACE: same version, no history
+    // entry, no event to subscribers beyond the persist record. Used only to
+    // re-encrypt rows at rest, where the content is unchanged and a new version
+    // would put the plaintext into history. Mirrors to LMDB and logs to the WAL
+    // like any write. `transform` runs on the CURRENT body under the
+    // collection lock (no read-then-write race) and returns whether it changed
+    // it. Returns: 1 rewritten, 0 unchanged, -1 not in MemoryStore.
+    int rewriteBodyInPlace(const std::string& collection, const std::string& id,
+                           const std::function<bool(nlohmann::json&)>& transform);
+
     // ===== Document CRUD =====
 
     /**

+ 6 - 5
service/src/migrations/migration_runner.cpp

@@ -411,7 +411,7 @@ bool MigrationRunner::applyOperation(const nlohmann::json& operation) {
         doc.set_data(operation["data"]);
 
         try {
-            store_.insert(collection, doc);
+            prepare(collection, doc); store_.insert(collection, doc);
             spdlog::debug("insert into '{}': {}", collection, doc.id);
         } catch (const std::exception& e) {
             spdlog::error("insert failed: {}", e.what());
@@ -440,7 +440,7 @@ bool MigrationRunner::applyOperation(const nlohmann::json& operation) {
         doc.set_data(operation["data"]);
 
         try {
-            store_.insert(collection, doc);
+            prepare(collection, doc); store_.insert(collection, doc);
             spdlog::debug("insert_if_not_exists into '{}': {}", collection, id);
         } catch (const std::exception& e) {
             spdlog::error("insert_if_not_exists failed: {}", e.what());
@@ -462,7 +462,7 @@ bool MigrationRunner::applyOperation(const nlohmann::json& operation) {
         doc.id = id;
         doc.set_data(operation["data"]);
 
-        store_.upsert(collection, doc);
+        prepare(collection, doc); store_.upsert(collection, doc);
         spdlog::debug("upsert into '{}': {}", collection, doc.id);
         return true;
     }
@@ -480,6 +480,7 @@ bool MigrationRunner::applyOperation(const nlohmann::json& operation) {
         doc.id = id;
         doc.set_data(operation["data"]);
 
+        prepare(collection, doc);
         bool updated = store_.update(collection, id, doc);
         spdlog::debug("update '{}': {} ({})", id, updated ? "updated" : "not found",
                      updated ? "success" : "failed");
@@ -624,7 +625,7 @@ bool MigrationRunner::applyOperation(const nlohmann::json& operation) {
         Document doc;
         doc.id = key;
         doc.set_data(nlohmann::json{{"value", value_to_write}});
-        store_.upsert(collection, doc);
+        prepare(collection, doc); store_.upsert(collection, doc);
         spdlog::debug("upsert_setting '{}/{}' = '{}' (fresh_install={})",
                       collection, key, value_to_write, fresh_install_at_start_);
         return true;
@@ -668,7 +669,7 @@ bool MigrationRunner::applyOperation(const nlohmann::json& operation) {
         Document doc;
         doc.id = key;
         doc.set_data(nlohmann::json{{"value", hex.str()}});
-        store_.upsert(collection, doc);
+        prepare(collection, doc); store_.upsert(collection, doc);
         spdlog::info("generate_secret '{}/{}': {}-byte secret generated", collection, key, bytes);
         return true;
     }

+ 18 - 0
service/src/migrations/migration_runner.hpp

@@ -1,5 +1,7 @@
 #pragma once
 
+#include <functional>
+
 #include "../memory_store.hpp"
 #include "../relations/relation_manager.hpp"
 #include "../views/view_manager.hpp"
@@ -99,6 +101,17 @@ public:
      */
     bool runMigrations();
 
+    /**
+     * v2.17.0 - called on every document a migration op is about to write
+     * (insert, insert_if_not_exists, upsert, update, upsert_setting,
+     * generate_secret). DatabaseService installs field encryption here: before
+     * 2.17.0 these ops wrote straight to the store, so a `generate_secret` or a
+     * seeded credential was stored in plaintext.
+     */
+    void setDocumentPreparer(std::function<void(const std::string& collection, Document& doc)> fn) {
+        preparer_ = std::move(fn);
+    }
+
     /**
      * Get list of pending migrations (not yet applied).
      */
@@ -110,6 +123,11 @@ public:
     std::vector<std::string> appliedMigrations() const;
 
 private:
+    std::function<void(const std::string&, Document&)> preparer_;   // v2.17.0
+    void prepare(const std::string& collection, Document& doc) {
+        if (preparer_) preparer_(collection, doc);
+    }
+
     /**
      * Apply a single migration file.
      */

+ 41 - 0
service/src/persistence/history_store.cpp

@@ -285,6 +285,47 @@ void HistoryStore::prune(const std::string& collection, uint32_t maxVersions) {
     }
 }
 
+uint64_t HistoryStore::rewrite(const std::string& collection,
+                               const std::function<bool(DocumentVersion&)>& transform) {
+    auto path = filePath(collection);
+    if (!std::filesystem::exists(path)) return 0;
+    std::lock_guard<std::mutex> lock(appendMutex_);
+
+    std::ifstream in(path, std::ios::binary);
+    if (!in) return 0;
+    std::vector<std::pair<std::string, DocumentVersion>> records;
+    uint64_t changed = 0;
+    scanFile(in, [&](const std::string& recDocId, DocumentVersion&& v) {
+        if (transform(v)) ++changed;
+        records.emplace_back(recDocId, std::move(v));
+    });
+    in.close();
+    if (changed == 0) return 0;
+
+    auto tmp = path;
+    tmp += ".tmp";
+    {
+        std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
+        if (!out) {
+            throw std::runtime_error("HistoryStore::rewrite: cannot open " + tmp.string());
+        }
+        for (const auto& [docId, v] : records) {
+            auto bytes = serializeRecord(docId, v);
+            out.write(reinterpret_cast<const char*>(bytes.data()),
+                      static_cast<std::streamsize>(bytes.size()));
+        }
+        out.flush();
+        if (!out) throw std::runtime_error("HistoryStore::rewrite: write failed for " + tmp.string());
+    }
+    std::error_code ec;
+    std::filesystem::rename(tmp, path, ec);
+    if (ec) {
+        std::filesystem::remove(tmp, ec);
+        throw std::runtime_error("HistoryStore::rewrite: rename failed for " + path.string());
+    }
+    return changed;
+}
+
 uint64_t HistoryStore::totalSizeBytes() const {
     uint64_t total = 0;
     std::error_code ec;

+ 10 - 0
service/src/persistence/history_store.hpp

@@ -6,6 +6,7 @@
 #include <deque>
 #include <filesystem>
 #include <fstream>
+#include <functional>
 #include <mutex>
 #include <optional>
 #include <string>
@@ -102,6 +103,15 @@ public:
      */
     void prune(const std::string& collection, uint32_t maxVersions);
 
+    /**
+     * v2.17.0 - apply `transform` to every stored version of `collection`, in
+     * file order, and rewrite the file (tmp + rename) if any changed. Used by
+     * the at-rest encryption migration: a past version holds the same
+     * plaintext the live row did. Returns the number of versions changed.
+     */
+    uint64_t rewrite(const std::string& collection,
+                     const std::function<bool(DocumentVersion&)>& transform);
+
     /**
      * Total disk bytes used by all history files.
      */

+ 43 - 1
service/src/persistence/persistence_manager.cpp

@@ -55,7 +55,14 @@ void applyWalEntry(MemoryStore& store, const WalEntry& entry) {
             break;
         case WalOpType::CREATE_COLLECTION:
             if (entry.collectionOptions) {
-                store.createCollection(entry.collection, *entry.collectionOptions);
+                // v2.17.0 - an entry for an existing collection may upgrade its
+                // encryption (CreateCollection with encrypted=true on an
+                // existing collection logs one). Upgrade only, never off.
+                if (!store.createCollection(entry.collection, *entry.collectionOptions)) {
+                    store.upgradeEncryptionOptions(entry.collection,
+                                                   entry.collectionOptions->encrypted,
+                                                   entry.collectionOptions->sensitiveFields);
+                }
             }
             break;
         case WalOpType::DROP_COLLECTION:
@@ -567,6 +574,41 @@ void PersistenceManager::forceSnapshot(const MemoryStore& store) {
     createSnapshot();
 }
 
+bool PersistenceManager::sealAfterRewrite(const MemoryStore& store, std::string& error,
+                                          size_t& snapshotsRemoved, size_t& walFilesRemoved) {
+    snapshotsRemoved = walFilesRemoved = 0;
+    if (!wal_ || !snapshotMgr_) {
+        error = "persistence is not initialised";
+        return false;
+    }
+    {
+        std::lock_guard<std::mutex> lock(storeMutex_);
+        currentStore_ = &store;
+    }
+    try {
+        wal_->rotateNow();
+        const uint64_t walSeq = wal_->currentSequence();
+        const auto path = snapshotMgr_->createSnapshot(store, walSeq);
+        if (path.empty() || !snapshotMgr_->verifySnapshot(path)) {
+            error = "the new snapshot did not verify; nothing was removed";
+            return false;
+        }
+        {
+            std::lock_guard<std::mutex> lock(statsMutex_);
+            lastSnapshotSequence_ = walSeq;
+            lastSnapshotTime_ = std::chrono::steady_clock::now();
+        }
+        snapshotsRemoved = snapshotMgr_->removeAllExcept(path);
+        walFilesRemoved = wal_->removeArchivedFiles();
+        spdlog::info("at-rest seal: snapshot {} at sequence {}; removed {} older snapshot(s) and "
+                     "{} WAL file(s)", path.string(), walSeq, snapshotsRemoved, walFilesRemoved);
+        return true;
+    } catch (const std::exception& e) {
+        error = e.what();
+        return false;
+    }
+}
+
 uint64_t PersistenceManager::currentWalSequence() const {
     return wal_ ? wal_->currentSequence() : 0;
 }

+ 10 - 0
service/src/persistence/persistence_manager.hpp

@@ -271,6 +271,16 @@ public:
      */
     void forceSnapshot(const MemoryStore& store);
 
+    /**
+     * v2.17.0 - after the at-rest encryption rewrite: rotate the WAL, take a
+     * verified snapshot of the (now encrypted) store, then delete every older
+     * snapshot and every archived WAL file, because each of them still holds
+     * the plaintext the rewrite replaced. Nothing is deleted unless the new
+     * snapshot verified. Returns false with `error` on failure.
+     */
+    bool sealAfterRewrite(const MemoryStore& store, std::string& error,
+                          size_t& snapshotsRemoved, size_t& walFilesRemoved);
+
     /**
      * Get current WAL sequence.
      */

+ 10 - 0
service/src/persistence/snapshot.cpp

@@ -500,6 +500,16 @@ std::optional<SnapshotHeader> SnapshotManager::getSnapshotInfo(const std::filesy
     return header;
 }
 
+size_t SnapshotManager::removeAllExcept(const std::filesystem::path& keep) {
+    size_t removed = 0;
+    for (const auto& p : listSnapshots()) {
+        if (p == keep) continue;
+        std::error_code ec;
+        if (std::filesystem::remove(p, ec)) ++removed;
+    }
+    return removed;
+}
+
 void SnapshotManager::cleanupOldSnapshots() {
     auto snapshots = listSnapshots();
 

+ 3 - 0
service/src/persistence/snapshot.hpp

@@ -162,6 +162,9 @@ public:
      */
     [[nodiscard]] bool verifySnapshot(const std::filesystem::path& path) const;
 
+    /// v2.17.0 - delete every snapshot except `keep` (the at-rest seal).
+    size_t removeAllExcept(const std::filesystem::path& keep);
+
 private:
     /**
      * Generate a filename for a new snapshot.

+ 17 - 0
service/src/persistence/wal.cpp

@@ -488,6 +488,23 @@ uint64_t WriteAheadLog::totalSizeBytes() const {
     return total;
 }
 
+void WriteAheadLog::rotateNow() {
+    std::lock_guard<std::mutex> lock(writeMutex_);
+    rotate();
+}
+
+size_t WriteAheadLog::removeArchivedFiles() {
+    std::lock_guard<std::mutex> lock(writeMutex_);
+    size_t removed = 0;
+    const auto current = currentFilePath();
+    for (const auto& file : getWalFiles()) {
+        if (file == current) continue;
+        std::error_code ec;
+        if (std::filesystem::remove(file, ec)) ++removed;
+    }
+    return removed;
+}
+
 void WriteAheadLog::truncateBefore(uint64_t sequence) {
     std::lock_guard<std::mutex> lock(writeMutex_);
 

+ 14 - 0
service/src/persistence/wal.hpp

@@ -153,6 +153,20 @@ public:
      */
     void truncateBefore(uint64_t sequence);
 
+    /**
+     * v2.17.0 - close the current file as an archive and start a new one, so
+     * everything written so far can be removed once a snapshot covers it.
+     */
+    void rotateNow();
+
+    /**
+     * v2.17.0 - delete every archived WAL file (all but the current one).
+     * Only valid right after a snapshot that covers the whole log, taken after
+     * rotateNow(): the at-rest encryption seal, which must not leave old
+     * plaintext entries on disk. Returns the number of files removed.
+     */
+    size_t removeArchivedFiles();
+
     /**
      * Check if WAL is open.
      */

+ 2 - 1
service/src/server_capabilities.hpp

@@ -18,7 +18,7 @@
 
 namespace smartbotic::database {
 
-inline constexpr std::array<std::string_view, 22> kServerCapabilities = {
+inline constexpr std::array<std::string_view, 23> kServerCapabilities = {
     "projects",              // 2.3.0  <project>:<collection> namespaces
     "access_policy",         // 2.7.0  row/column security
     "query_projection",      // 2.7.1  FindRequest.projection
@@ -41,6 +41,7 @@ inline constexpr std::array<std::string_view, 22> kServerCapabilities = {
     "server_info",           // 2.15.0 GetServerInfo itself
     "client_version_header", // 2.15.0 the server reads sbdb-client-version
     "collection_schema",     // 2.16.0 Set/Get/SuggestCollectionSchema, schema_violation
+    "encryption_at_rest",    // 2.17.0 encrypted collections encrypt, VerifyEncryption, encrypted_field
 };
 
 }  // namespace smartbotic::database

+ 52 - 0
service/src/storage/project_store.cpp

@@ -11,6 +11,8 @@
 #include "project_addressing.hpp"
 #include "storage/document_store_lmdb.hpp"
 
+#include <lmdb.h>
+
 namespace fs = std::filesystem;
 
 namespace smartbotic::db::storage {
@@ -187,6 +189,56 @@ bool ProjectStoreRegistry::create(std::string_view name, std::string& error) {
     }
 }
 
+bool ProjectStoreRegistry::compact(std::string_view name, uint64_t& bytesBefore,
+                                   uint64_t& bytesAfter, std::string& error) {
+    std::unique_lock lk(mutex_);
+    auto it = stores_.find(name);
+    if (it == stores_.end()) {
+        error = "project not open";
+        return false;
+    }
+    const fs::path dir = env_dir(name);
+    const fs::path tmp = dir.parent_path() / "env.compact";
+    std::error_code ec;
+    fs::remove_all(tmp, ec);
+    fs::create_directories(tmp, ec);
+    if (ec) {
+        error = "cannot create " + tmp.string() + ": " + ec.message();
+        return false;
+    }
+    bytesBefore = fs::file_size(dir / "data.mdb", ec);
+    const int rc = mdb_env_copy2(it->second->env->raw(), tmp.c_str(), MDB_CP_COMPACT);
+    if (rc != MDB_SUCCESS) {
+        error = std::string("mdb_env_copy2: ") + mdb_strerror(rc);
+        fs::remove_all(tmp, ec);
+        return false;   // nothing changed
+    }
+    // Close the env (destroys the DocumentStore first), then swap the files.
+    it->second.reset();
+    const fs::path old = dir / "data.mdb.pre-compact";
+    fs::rename(dir / "data.mdb", old, ec);
+    if (ec) {
+        error = "rename data.mdb: " + ec.message();
+        it->second = open_one(std::string(name));   // the original is untouched
+        fs::remove_all(tmp, ec);
+        return false;
+    }
+    fs::rename(tmp / "data.mdb", dir / "data.mdb", ec);
+    if (ec) {
+        error = "install compacted copy: " + ec.message();
+        std::error_code ec2;
+        fs::rename(old, dir / "data.mdb", ec2);   // put the original back
+        it->second = open_one(std::string(name));
+        fs::remove_all(tmp, ec2);
+        return false;
+    }
+    fs::remove(old, ec);
+    fs::remove_all(tmp, ec);
+    it->second = open_one(std::string(name));
+    bytesAfter = fs::file_size(dir / "data.mdb", ec);
+    return true;
+}
+
 bool ProjectStoreRegistry::drop(std::string_view name, std::string& error) {
     if (name == smartbotic::database::kDefaultProject) {
         error = "cannot drop default project";

+ 12 - 0
service/src/storage/project_store.hpp

@@ -88,6 +88,18 @@ public:
     // or rm fails.
     bool drop(std::string_view name, std::string& error);
 
+    // v2.17.0 - rewrite a project's env without free pages: a compacted copy
+    // (mdb_env_copy2 MDB_CP_COMPACT) replaces data.mdb, then the env is
+    // reopened. LMDB is copy-on-write, so after rows are rewritten the pages
+    // that held their old bytes stay in the file until reused; the at-rest
+    // encryption seal compacts so no old plaintext survives in data.mdb.
+    // EVERY DocumentStore* obtained for this project before the call is
+    // invalid after it, and per-store state (index/unique/relation arming) is
+    // gone - the caller re-arms. Only for boot, before anything caches a
+    // pointer or serves traffic. Throws if the reopen fails.
+    bool compact(std::string_view name, uint64_t& bytesBefore, uint64_t& bytesAfter,
+                 std::string& error);
+
 private:
     std::filesystem::path project_dir(std::string_view name) const;
     std::filesystem::path env_dir(std::string_view name) const;

+ 237 - 0
tests/load_test/test_encryption_at_rest.cpp

@@ -0,0 +1,237 @@
+// v2.17.0 - encryption at rest, and the migration of data written by 2.16.0.
+//
+// Before 2.17.0: a collection created with encrypted=true encrypted nothing;
+// the sensitive name patterns matched nested fields only; `sensitive_fields`
+// was stored and never used; patch and migration ops never encrypted; strings
+// inside arrays were neither encrypted nor decrypted. Every secret below is a
+// unique CANARY string, so test_encryption_at_rest.sh can grep the data
+// directory for it: before the upgrade it must be found (else this test proves
+// nothing), after the upgrade's seal it must be found NOWHERE.
+//
+// Phases (test_encryption_at_rest.sh):
+//   seed      - run against the RELEASED 2.16.0 server: write the legacy data.
+//   upgraded  - 2.17.0 on the same directory, after the one-time migration:
+//               every value reads back exactly (type included), the verifier
+//               is clean and sealed, history decrypts, refusals, new writes.
+//   upgrade2  - createCollection(encrypted=true) on a collection created
+//               implicitly: switched on online, rows encrypted now, reseal
+//               pending until the restart.
+//   resealed  - after a restart: sealed again, all values still exact.
+
+#include <smartbotic/database/client.hpp>
+
+#include <iostream>
+#include <string>
+
+using namespace smartbotic::database;
+using json = nlohmann::json;
+static int pass = 0, fail = 0;
+static void ck(bool c, const std::string& m) {
+    if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
+}
+
+static Client::Config cfg() {
+    Client::Config c;
+    c.address = "127.0.0.1:9031";
+    c.project = "default";   // the migration file uses bare names, which live in default
+    c.writeRetries = 0;
+    return c;
+}
+
+// Every stored value, as written. The canaries are what the grep looks for.
+static const json kPlain1 = {{"password", "CANARY-TOP-PW-3391"}, {"name", "visible-name"}};
+static const json kPlain2 = {{"creds", {{"password", "CANARY-NESTED-PW-1182"}}},
+                             {"secret", json::array({"CANARY-ARRAY-0457", "CANARY-ARRAY-0458"})},
+                             {"api_key", "CANARY-APIKEY-7720"}};
+static const json kVault = {{"key", "CANARY-VAULT-KEY-5512"}, {"n", 42}, {"ratio", 0.25},
+                            {"flag", true}, {"nul", nullptr},
+                            {"nested", {{"v", "CANARY-VAULT-NESTED-9930"}}},
+                            {"list", json::array({1, "CANARY-VAULT-LIST-2210"})}};
+static const json kLate = {{"value", "CANARY-LATE-VALUE-6604"}, {"count", 7}};
+static const json kSf = {{"pin", "CANARY-SF-PIN-8841"}, {"label", "public"}};
+
+static json userFields(json d) {
+    for (const char* k : {"_id", "_version", "_created_at", "_updated_at", "_created_by", "_updated_by"}) d.erase(k);
+    return d;
+}
+
+static void exact(Client& c, const std::string& coll, const std::string& id, const json& want,
+                  const std::string& what) {
+    auto got = c.get(coll, id);
+    ck(got && userFields(*got) == want,
+       what + ": reads back exactly (got " + (got ? userFields(*got).dump() : "nothing") + ")");
+}
+
+static int seed() {
+    Client c(cfg());
+    c.connect();
+    c.createCollection("plain");
+    c.insert("plain", kPlain1, "p1");
+    // Two updates put the top-level password into HISTORY as well.
+    c.update("plain", "p1", {{"password", "CANARY-HIST-PW-4471"}, {"name", "visible-name"}});
+    c.update("plain", "p1", kPlain1);
+    c.insert("plain", kPlain2, "p2");
+    // A PATCH of a nested password: 2.16.0 never encrypted on patch.
+    c.insert("plain", {{"name", "patched"}}, "p3");
+    c.patch("plain", "p3", {{"creds", {{"password", "CANARY-PATCH-PW-6025"}}}});
+    ck(c.createCollection("vault", 0, true, 0, 0), "vault created with encrypted=true");
+    c.insert("vault", kVault, "v1");
+    // Created implicitly by a write: createCollection(encrypted) afterwards is
+    // what 2.16.0 ignored.
+    c.insert("late", kLate, "l1");
+    // sf is created by the migration file (sensitive_fields ["pin"]) and
+    // seeded by its insert op; one more row through the client.
+    c.insert("sf", kSf, "s2");
+    return 0;
+}
+
+static void commonChecks(Client& c, const std::string& phase, const json& p1 = kPlain1) {
+    exact(c, "plain", "p1", p1, phase + " p1");
+    exact(c, "plain", "p2", kPlain2, phase + " p2 (nested + array + api_key)");
+    exact(c, "plain", "p3", {{"name", "patched"}, {"creds", {{"password", "CANARY-PATCH-PW-6025"}}}},
+          phase + " p3 (patched)");
+    exact(c, "vault", "v1", kVault, phase + " vault (types restored)");
+    exact(c, "late", "l1", kLate, phase + " late");
+    exact(c, "sf", "s1", {{"pin", "CANARY-SF-MIGRATION-3398"}, {"label", "seeded"}}, phase + " sf/s1 (migration op)");
+    exact(c, "sf", "s2", kSf, phase + " sf/s2");
+    // History versions decrypt.
+    auto h = c.getVersionHistory("plain", "p1", 0);
+    bool sawHist = false;
+    for (const auto& v : h.versions) {
+        if (v.data.value("password", "") == "CANARY-HIST-PW-4471") sawHist = true;
+    }
+    ck(sawHist, phase + ": a history version reads back its original plaintext");
+}
+
+static void verifyClean(Client& c, const std::string& phase, bool sealedExpected) {
+    auto r = c.verifyEncryption();
+    ck(r.encryptionEnabled, phase + ": encryption enabled");
+    ck(r.clean(), phase + ": verifier clean (nothing plaintext that must be encrypted, nothing double)");
+    ck(r.atRestSealed == sealedExpected, phase + ": sealed == " + (sealedExpected ? "true" : "false"));
+    uint64_t enc = 0;
+    for (const auto& a : r.collections) {
+        enc += a.encryptedValues;
+        if (a.plaintextRequired || a.doubleEncrypted || a.undecryptable || a.historyPlaintextRequired ||
+            a.historyDoubleEncrypted) {
+            std::cerr << "  " << a.collection << ": plain " << a.plaintextRequired << " double "
+                      << a.doubleEncrypted << " undecryptable " << a.undecryptable << " hist-plain "
+                      << a.historyPlaintextRequired << "\n";
+            for (const auto& s : a.samples) std::cerr << "    " << s << "\n";
+        }
+    }
+    ck(enc > 10, phase + ": ciphertext values exist (" + std::to_string(enc) + ")");
+}
+
+static bool refusedEncrypted(const std::function<void()>& f) {
+    try {
+        f();
+        std::cerr << "  (no exception)\n";
+    } catch (const Client::Error& e) {
+        const auto* d = Client::errorDetail(e);
+        if (d && d->reason == "encrypted_field") return true;
+        std::cerr << "  (Client::Error " << e.what() << " reason '" << (d ? d->reason : "-") << "')\n";
+    } catch (const std::exception& e) {
+        std::cerr << "  (other exception " << e.what() << ")\n";
+    }
+    return false;
+}
+
+static int upgraded() {
+    Client c(cfg());
+    c.connect();
+    ck(c.serverSupports(Client::Capability::kEncryptionAtRest), "server reports encryption_at_rest");
+    commonChecks(c, "upgraded");
+    verifyClean(c, "upgraded", true);
+
+    // The refusals: comparisons over ciphertext are refused, not silently empty.
+    ck(refusedEncrypted([&] {
+        Client::QueryOptions o;
+        o.filters = {Client::Filter::eq("password", "x")};
+        (void)c.find("plain", o);
+    }), "find filter on a top-level password is refused");
+    ck(refusedEncrypted([&] {
+        Client::QueryOptions o;
+        o.filters = {Client::Filter::eq("creds.password", "x")};
+        (void)c.find("plain", o);
+    }), "find filter on creds.password is refused");
+    ck(refusedEncrypted([&] {
+        Client::QueryOptions o;
+        o.filters = {Client::Filter::eq("key", "x")};
+        (void)c.find("vault", o);
+    }), "find filter on any field of an encrypted collection is refused");
+    ck(refusedEncrypted([&] {
+        Client::QueryOptions o;
+        o.sortField = "n";
+        (void)c.find("vault", o);
+    }), "sort on an encrypted collection field is refused");
+    ck(refusedEncrypted([&] { (void)c.count("plain", {Client::Filter::eq("api_key", "x")}); }),
+       "count filter on api_key is refused");
+    {
+        Client::QueryOptions o;
+        o.filters = {Client::Filter::eq("name", "visible-name")};
+        ck(c.find("plain", o).size() == 1, "a filter on a non-sensitive field still works");
+        Client::QueryOptions all;
+        ck(c.find("vault", all).size() == 1, "an unfiltered read of an encrypted collection works");
+        Client::QueryOptions byId;
+        byId.filters = {Client::Filter::eq("_id", "v1")};
+        ck(c.find("vault", byId).size() == 1, "a metadata filter on an encrypted collection works");
+    }
+    ck(!c.createIndex("vault", "key"), "index on an encrypted collection field is refused");
+    ck(!c.createUniqueIndex("plain", "password").success, "unique index on password is refused");
+    ck(c.createIndex("plain", "name"), "index on a non-sensitive field still works");
+    {
+        Client::FailureDetail fd;
+        ck(!c.increment("vault", "v1", {{"n", 1}}, fd).has_value() && fd.reason == "encrypted_field",
+           "increment on an encrypted value is refused (" + fd.reason + ")");
+    }
+    ck(!c.setAdd("vault", "s", "m"), "set operations on an encrypted collection are refused");
+
+    // New writes are encrypted at once (the .sh greps these canaries too).
+    c.insert("plain", {{"password", "CANARY-NEW-PW-1906"}}, "n1");
+    c.patch("plain", "p1", {{"token", "CANARY-NEW-TOKEN-7783"}});
+    c.insert("vault", {{"key", "CANARY-NEW-VAULT-3360"}, {"n", 1}}, "v2");
+    exact(c, "plain", "n1", {{"password", "CANARY-NEW-PW-1906"}}, "new insert");
+    exact(c, "vault", "v2", {{"key", "CANARY-NEW-VAULT-3360"}, {"n", 1}}, "new vault insert");
+    {
+        auto p1 = c.get("plain", "p1");
+        ck(p1 && p1->value("token", "") == "CANARY-NEW-TOKEN-7783", "new patch value reads back");
+    }
+    verifyClean(c, "after new writes", true);
+    return 0;
+}
+
+static int upgrade2() {
+    Client c(cfg());
+    c.connect();
+    ck(!c.verifyEncryption("late").collections.empty(), "late is audited");
+    ck(!c.createCollection("late", 0, true, 0, 0), "createCollection on existing late returns false");
+    auto r = c.verifyEncryption("late");
+    ck(!r.collections.empty() && r.collections.front().collectionEncrypted,
+       "late is now an encrypted collection");
+    ck(r.clean(), "late: every value encrypted right away");
+    ck(!r.atRestSealed, "a reseal is pending until the restart");
+    exact(c, "late", "l1", kLate, "late after the online upgrade");
+    return 0;
+}
+
+static int resealed() {
+    Client c(cfg());
+    c.connect();
+    json p1 = kPlain1;
+    p1["token"] = "CANARY-NEW-TOKEN-7783";   // patched in the upgraded phase
+    commonChecks(c, "resealed", p1);
+    exact(c, "plain", "n1", {{"password", "CANARY-NEW-PW-1906"}}, "resealed new insert");
+    verifyClean(c, "resealed", true);
+    return 0;
+}
+
+int main(int argc, char** argv) {
+    const std::string phase = argc > 1 ? argv[1] : "";
+    if (phase == "seed") seed();
+    else if (phase == "upgraded") upgraded();
+    else if (phase == "upgrade2") upgrade2();
+    else if (phase == "resealed") resealed();
+    else { std::cerr << "usage: seed|upgraded|upgrade2|resealed\n"; return 2; }
+    std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 143 - 0
tests/load_test/test_encryption_at_rest.sh

@@ -0,0 +1,143 @@
+#!/usr/bin/env bash
+# v2.17.0 e2e - encryption at rest and the migration of 2.16.0 data, on a
+# throwaway instance. See test_encryption_at_rest.cpp for what each phase asserts.
+#
+# The seed is written by the RELEASED 2.16.0 server, so the data is genuinely
+# legacy. Prepare it once on the host:   packaging/old-server.sh 2.16.0
+#
+# The grep checks are the point: every secret is a unique CANARY string, and
+#   - after the 2.16.0 seed, they MUST be on disk in plaintext (else the test
+#     proves nothing);
+#   - after the upgrade's seal, NONE may be found anywhere in the data
+#     directory: LMDB, WAL, snapshots, history.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+OLD="$ROOT/build/old-server-2.16.0/usr/bin/smartbotic-database"
+NEW="$ROOT/build/service/smartbotic-database"
+[[ -x "$OLD" ]] || { echo "missing $OLD - run: packaging/old-server.sh 2.16.0"; exit 1; }
+
+DIR=/tmp/sbdb-encryption-at-rest
+PORT=9031
+rm -rf "$DIR"
+mkdir -p "$DIR/data" "$DIR/migrations"
+
+cat > "$DIR/config.json" <<CFG
+{
+  "storage": {
+    "data_directory": "$DIR/data",
+    "bind_address": "127.0.0.1",
+    "rpc_port": $PORT,
+    "encryption": { "enabled": true, "key_file": "$DIR/data/storage.key" },
+    "migrations": { "enabled": true, "auto_apply": true, "directory": "$DIR/migrations" },
+    "replication": { "enabled": false }
+  }
+}
+CFG
+
+# A consumer-style migration with BARE names: declares sensitive_fields and
+# seeds a row - both of which 2.16.0 left in plaintext.
+cat > "$DIR/migrations/001_sf.json" <<'MIG'
+{
+  "version": "001",
+  "name": "sf",
+  "operations": [
+    { "type": "create_collection", "collection": "sf", "options": { "sensitive_fields": ["pin"] } },
+    { "type": "insert", "collection": "sf", "id": "s1", "data": { "pin": "CANARY-SF-MIGRATION-3398", "label": "seeded" } }
+  ]
+}
+MIG
+
+echo "=== building test binary ==="
+g++ -std=c++20 -O1 -o "$DIR/t" test_encryption_at_rest.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+SERVER_PID=""
+BOOTS=0
+start() {
+    "$1" --config "$DIR/config.json" >> "$DIR/server.log" 2>&1 &
+    SERVER_PID=$!
+    BOOTS=$((BOOTS + 1))
+    for _ in $(seq 1 120); do
+        [[ $(grep -c "Notified systemd: READY" "$DIR/server.log") -ge $BOOTS ]] && return 0
+        sleep 0.5
+    done
+    tail -30 "$DIR/server.log"; exit 1
+}
+stop() {
+    [[ -n "$SERVER_PID" ]] || return 0
+    kill "$SERVER_PID" 2>/dev/null || true
+    wait "$SERVER_PID" 2>/dev/null || true
+    SERVER_PID=""
+}
+trap stop EXIT
+
+run() {
+    set +e
+    LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" "$1" 2>&1 | grep -v '\[error\]\|\[info\]' | tee "$DIR/out-$1.txt"
+    local rc=${PIPESTATUS[0]}
+    set -e
+    [[ $rc -eq 0 ]] || { echo "FAILED in phase $1"; tail -25 "$DIR/server.log"; exit $rc; }
+}
+
+FAILS=0
+# "|| true": no match is the outcome we WANT after the seal; under set -e and
+# pipefail it would otherwise end the script without a word.
+found()  { { grep -rlaF "$1" "$DIR/data" 2>/dev/null || true; } | sed "s|$DIR/data/||" | tr '\n' ' '; }
+must_find() {
+    local f; f=$(found "$1")
+    if [[ -n "$f" ]]; then echo "ok   plaintext before upgrade: $1 in $f"; else echo "FAIL $1 not on disk before the upgrade - the test would be vacuous"; FAILS=$((FAILS+1)); fi
+}
+must_not_find() {
+    local f; f=$(found "$1")
+    if [[ -z "$f" ]]; then echo "ok   nowhere on disk: $1"; else echo "FAIL $1 still in plaintext in: $f"; FAILS=$((FAILS+1)); fi
+}
+
+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-SF-MIGRATION-3398 CANARY-SF-PIN-8841)
+ALL=("${LEGACY[@]}" CANARY-NESTED-PW-1182 CANARY-NEW-PW-1906 CANARY-NEW-TOKEN-7783 CANARY-NEW-VAULT-3360)
+
+echo "=== seed with the RELEASED 2.16.0 server ==="
+start "$OLD"
+run seed
+stop
+for c in "${LEGACY[@]}" CANARY-LATE-VALUE-6604; do must_find "$c"; done
+
+echo "=== upgrade: 2.17.0 on the same directory ==="
+start "$NEW"
+grep -q "one-time migration" "$DIR/server.log" || { echo "FAIL: the migration did not run"; exit 1; }
+grep -E "v2.17 at-rest" "$DIR/server.log" | sed 's/^/    /'
+run upgraded
+stop
+for c in "${ALL[@]}"; do must_not_find "$c"; done
+# `late` is neither encrypted nor sensitive yet: still plaintext, by design.
+must_find CANARY-LATE-VALUE-6604
+
+echo "=== online upgrade of an existing collection ==="
+start "$NEW"
+run upgrade2
+stop
+
+echo "=== restart: the reseal ==="
+start "$NEW"
+run resealed
+stop
+for c in "${ALL[@]}" CANARY-LATE-VALUE-6604; do must_not_find "$c"; done
+
+echo "=== restart again: nothing re-runs, nothing changes ==="
+start "$NEW"
+run resealed
+stop
+n=$(grep -c "one-time migration" "$DIR/server.log")
+[[ $n -eq 1 ]] && echo "ok   the one-time migration ran exactly once" || { echo "FAIL: migration ran $n times"; FAILS=$((FAILS+1)); }
+for c in "${ALL[@]}" CANARY-LATE-VALUE-6604; do must_not_find "$c"; done
+
+[[ $FAILS -eq 0 ]] || { echo "FAILED: $FAILS on-disk check(s)"; exit 1; }
+echo ""
+echo "OK - encryption at rest e2e passed"

+ 28 - 13
tests/load_test/test_server_info.cpp

@@ -42,7 +42,7 @@ static const std::vector<const char*> kAllCaps = {
     Cap::kUniqueIndexes, Cap::kErrorDetail, Cap::kPatchIfVersion, Cap::kIncrement,
     Cap::kCompositeUnique, Cap::kBatchDeleteIds, Cap::kEventActor, Cap::kVectorReadback,
     Cap::kExportCollection, Cap::kWriteSizeGuard, Cap::kFilteredSimilarity, Cap::kServerInfo,
-    Cap::kClientVersionHeader, Cap::kCollectionSchema,
+    Cap::kClientVersionHeader, Cap::kCollectionSchema, Cap::kEncryptionAtRest,
 };
 
 // Ordinary calls a client of any version makes; they must work across versions.
@@ -97,7 +97,8 @@ static int old() {
         ck(!c.serverSupports(Cap::kServerInfo), "old (pre-2.15.0): serverSupports is false");
     } else {
         ck(si->version != clientLibraryVersion(), "old (2.15.0+): reports its own version " + si->version);
-        ck(!c.serverSupports(Cap::kCollectionSchema), "old (2.15.0+): lacks collection_schema");
+        // The newest capability this client knows; bump it with each release.
+        ck(!c.serverSupports(Cap::kEncryptionAtRest), "old (2.15.0+): lacks encryption_at_rest");
     }
     basics(c, "old");
     // A pre-2.14.0 server would answer a filtered search UNFILTERED; a 2.14.0
@@ -113,18 +114,32 @@ static int old() {
         refused = d && d->reason == "filters_unsupported";
     }
     ck(refused || r.empty(), "old: a filtered search is refused or really filtered, never unfiltered");
-    // v2.16.0 - the first feature gated by capability: refused BEFORE sending.
-    const auto sr = c.setCollectionSchema("w", {{"type", "object"}});
-    ck(!sr.success && sr.reason == "server_unsupported",
-       "old: setCollectionSchema refused with server_unsupported (got '" + sr.reason + "')");
-    bool getRefused = false;
-    try {
-        (void)c.getCollectionSchema("w");
-    } catch (const Client::FailedPrecondition& e) {
-        const auto* d = Client::errorDetail(e);
-        getRefused = d && d->reason == "server_unsupported";
+    // Features gated by capability are refused BEFORE sending against a server
+    // that lacks them (2.16.0 schema calls against a pre-2.16 server, 2.17.0
+    // verifyEncryption against a pre-2.17 one).
+    if (!c.serverSupports(Cap::kCollectionSchema)) {
+        const auto sr = c.setCollectionSchema("w", {{"type", "object"}});
+        ck(!sr.success && sr.reason == "server_unsupported",
+           "old: setCollectionSchema refused with server_unsupported (got '" + sr.reason + "')");
+        bool getRefused = false;
+        try {
+            (void)c.getCollectionSchema("w");
+        } catch (const Client::FailedPrecondition& e) {
+            const auto* d = Client::errorDetail(e);
+            getRefused = d && d->reason == "server_unsupported";
+        }
+        ck(getRefused, "old: getCollectionSchema refused with server_unsupported");
+    }
+    {
+        bool refused = false;
+        try {
+            (void)c.verifyEncryption();
+        } catch (const Client::FailedPrecondition& e) {
+            const auto* d = Client::errorDetail(e);
+            refused = d && d->reason == "server_unsupported";
+        }
+        ck(refused, "old: verifyEncryption refused with server_unsupported");
     }
-    ck(getRefused, "old: getCollectionSchema refused with server_unsupported");
     return 0;
 }
 

Some files were not shown because too many files changed in this diff