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

feat: 0.18.0 - request-level refusals precede the 404, and a key is confirmed readable before it is handed out

SV-26: scoped() is split into authorized() + requireCollection() so a route can
refuse a REQUEST-level fault between authorization and the 404, which is the
ordering rule this project already had written down. PUT's ttl_seconds refusal
answered 422 on a collection that existed and 404 on one that did not, so a
caller who misspelled the collection never learned the parameter is
unsupported. Falsified: reverting the ordering fails the new test while the
pre-existing refusal test still passes.

SV-25: KeyStore::visible() answers whether an id is in the snapshot that reads
and therefore authentication are served from, and create()/update() now throw
503 rather than returning a credential the read path cannot see. A 201 with a
dead secret is a silent permanent failure that looks like success.

SV-15: the last two exists() probes are gone. The contract change the task
assumed was needed is not - the function can throw for a transport failure and
keep returning bool for present/absent, exactly as CollectionRegistry does, so
a blip is a 503 instead of an unretryable 404.

1352/1352.
fszontagh 1 місяць тому
батько
коміт
8e0309b77f

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.17.0
+0.18.0

+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.17.0",
+    "version": "0.18.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {

+ 36 - 4
src/handlers/documents.cpp

@@ -26,17 +26,42 @@ struct Target {
     CollectionMeta meta;
 };
 
-// Authorize + verify the collection exists.
-Target scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
+// Authorize only - everything `scoped()` does BEFORE the resource has to exist.
+//
+// Split out so a route can refuse a REQUEST-level fault BETWEEN authorization
+// and the 404, which is the one ordering rule this service holds everywhere:
+// authorize, then the server's own capability (501), then the REQUEST (422),
+// then the resource (404). A request-level fault that no amount of creating the
+// collection would fix must not hide behind the collection's absence.
+//
+// It exists because PUT's `ttl_seconds` refusal was on the wrong side of that
+// line and the defect was visible from outside: the SAME refused parameter
+// answered 422 on a collection that existed and 404 on one that did not, so a
+// caller who misspelled the collection never learned the parameter is
+// unsupported - they fixed the name, retried, and only then met the 422.
+Target authorized(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
     Target t;
     t.key = requireKey(*d, req);
     t.project = req.matches[projIdx];
     t.name = req.matches[collIdx];
     requireCapability(*d, t.key, req, t.project, t.name, op);
+    t.qualified = qualify(t.project, t.name);
+    return t;
+}
+
+// Fill in the collection metadata, 404 if there is no such collection.
+void requireCollection(ServerDeps* d, Target& t) {
     auto meta = d->registry.get(t.project, t.name);
     if (!meta) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
     t.meta = *meta;
-    t.qualified = qualify(t.project, t.name);
+}
+
+// Authorize + verify the collection exists. The composition of the two above,
+// so there is ONE implementation of each step rather than a second copy in the
+// one route that needs them apart.
+Target scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
+    Target t = authorized(d, req, projIdx, collIdx, op);
+    requireCollection(d, t);
     return t;
 }
 
@@ -284,7 +309,11 @@ void registerDocumentRoutes(ApiServer& s) {
     });
 
     svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
-        Target t = scoped(d, req, 1, 2, KeyOp::Update);
+        // AUTHORIZE first, then the REQUEST, then the RESOURCE - see
+        // `authorized()` above. The parameter refusal below must come before
+        // the collection's 404, or the same refused parameter answers 422 on a
+        // collection that exists and 404 on one that does not.
+        Target t = authorized(d, req, 1, 2, KeyOp::Update);
         std::string id = req.matches[3];
 
         // REFUSE `?ttl_seconds=` HERE, because this route CANNOT honour it and
@@ -317,6 +346,9 @@ void registerDocumentRoutes(ApiServer& s) {
             "no TTL. POST with an id to create a row WITH one, or PATCH to set or clear it on a "
             "row that already exists");
 
+        // The resource LAST of the three.
+        requireCollection(d, t);
+
         const auto ifVersion = ifVersionParam(req);
         nlohmann::json data = documentBody(bodyJson(req));
 

+ 37 - 0
src/key_store.cpp

@@ -1,5 +1,7 @@
 #include "key_store.hpp"
+#include "errors.hpp"
 #include <spdlog/spdlog.h>
+#include <algorithm>
 #include <ctime>
 
 namespace svapi {
@@ -74,6 +76,19 @@ void KeyStore::bootstrap(const std::string& envAdminKey) {
     }
 }
 
+/// Is this key id present in the snapshot reads are served from?
+///
+/// `lookup()` authenticates by scanning the snapshot that `reload()` loads with
+/// `find()`, so a key the READ path cannot see cannot authenticate, whatever a
+/// write reported. The two directions of the store's memory/disk split are not
+/// symmetric for this collection: a row visible to writes and not to reads is
+/// exactly a credential that was accepted and does not work.
+bool KeyStore::visible(const std::string& id) const {
+    std::lock_guard<std::mutex> lk(m_);
+    return std::any_of(snap_->begin(), snap_->end(),
+                       [&](const ApiKey& k) { return k.id == id; });
+}
+
 std::optional<ApiKey> KeyStore::lookup(const std::string& key) const {
     std::lock_guard<std::mutex> lk(m_);
     for (const auto& k : *snap_)
@@ -100,6 +115,22 @@ ApiKey KeyStore::create(const std::string& label,
     k.scope     = std::move(scope);
     db_.client().upsert(coll_, k.toJson(), k.id);
     reload();
+    // CONFIRM THE KEY CAN BE READ BACK BEFORE HANDING OUT ITS SECRET.
+    //
+    // Without this the route answers 201 with a credential that may never
+    // authenticate, and the operator stores it: the upsert is a WRITE and
+    // `lookup()` only ever sees what a READ returns, so if the write lands
+    // where the read cannot see it - the memory-only direction of the store's
+    // MemoryStore/LMDB split, found on a sibling deployment - the secret is
+    // dead on arrival and nothing says so. Failing here is strictly better: a
+    // 503 is retryable and tells the truth, where a 201 carrying a useless
+    // secret is a silent, permanent failure that looks like success.
+    //
+    // Cheap, because `reload()` has just populated the snapshot in memory.
+    if (!visible(k.id))
+        throw ApiError(ErrCode::Unavailable, "db_error",
+                       "the key was written but cannot be read back, so it would not "
+                       "authenticate; nothing was handed out - retry");
     return k;
 }
 
@@ -117,6 +148,12 @@ bool KeyStore::update(const std::string& id,
     if (scope)    k.scope    = *scope;
     db_.client().upsert(coll_, k.toJson(), id);
     reload();
+    // Same reasoning as create(): a patched key the read path cannot see has
+    // silently stopped authenticating, and reporting success would hide that.
+    if (!visible(id))
+        throw ApiError(ErrCode::Unavailable, "db_error",
+                       "the key was written but cannot be read back, so the change "
+                       "would not take effect - retry");
     return true;
 }
 

+ 4 - 0
src/key_store.hpp

@@ -47,6 +47,10 @@ public:
     /// Subscribe to DB change events so the snapshot stays current automatically.
     void startWatch();
 
+    /// Is this key id in the snapshot that reads - and therefore authentication -
+    /// are served from? Exposed for the tests that pin the read-back guard.
+    bool visible(const std::string& id) const;
+
 private:
     void reload();
 

+ 13 - 2
src/project_secret_store.cpp

@@ -1,4 +1,5 @@
 #include "project_secret_store.hpp"
+#include "db_errors.hpp"
 #include <ctime>
 
 namespace svapi {
@@ -84,8 +85,18 @@ ProjectSecret ProjectSecretStore::put(const std::string& project, const std::str
 bool ProjectSecretStore::remove(const std::string& project, const std::string& name) {
     ensure(project);
     const std::string c = collectionFor(project);
-    if (!db_.client().exists(c, name)) return false;
-    return db_.client().remove(c, name);
+    // See the note in SettingsStore::removeProject: the `exists()` probe is
+    // gone because it could not tell absence from a failed call, and its
+    // caller maps false to an unretryable 404. `remove()`'s Failure& form
+    // distinguishes them, so a transport failure is thrown rather than
+    // reported as "no such secret".
+    smartbotic::database::Client::Failure failure;
+    if (!db_.client().remove(c, name, failure)) {
+        if (failure.code != smartbotic::database::Client::ErrorCode::Ok)
+            throw apiErrorFor(failure, "could not remove the secret");
+        return false;  // genuinely absent
+    }
+    return true;
 }
 
 void ProjectSecretStore::dropAll(const std::string& project) {

+ 18 - 2
src/settings_store.cpp

@@ -1,4 +1,5 @@
 #include "settings_store.hpp"
+#include "db_errors.hpp"
 #include "embedding_cache.hpp"
 #include <spdlog/spdlog.h>
 
@@ -70,8 +71,23 @@ bool SettingsStore::saveProject(const ProjectSettings& p) {
 
 bool SettingsStore::removeProject(const std::string& project) {
     const std::string id = projectSettingsDocId(project);
-    if (!db_.client().exists(coll_, id)) return false;
-    db_.client().remove(coll_, id);
+    // NO `exists()` PROBE. `Client::exists` conflates "no such document" with
+    // "the call failed", so a transport blip became a `false` that this
+    // function's caller maps to 404 - and a 404 is unretryable BY DESIGN for a
+    // careful client, which makes a transient failure permanent. The same
+    // probe was deleted from the documents PATCH route for the same reason.
+    //
+    // `remove()`'s Failure& form reports absence itself: code `Ok` with a
+    // false return means "did not apply", while a transport failure arrives
+    // with a non-Ok code and is thrown as the 503 it is. So `bool` never has
+    // to express "the call failed" - the exception does, which is why this
+    // needed no signature change after all.
+    smartbotic::database::Client::Failure failure;
+    if (!db_.client().remove(coll_, id, failure)) {
+        if (failure.code != smartbotic::database::Client::ErrorCode::Ok)
+            throw apiErrorFor(failure, "could not remove the project settings");
+        return false;  // genuinely absent
+    }
     reloadProjectsFromDb();
     return true;
 }

+ 6 - 1
tests/CMakeLists.txt

@@ -225,7 +225,12 @@ gtest_discover_tests(test_project_secrets)
 add_executable(test_project_secret_store
     test_project_secret_store.cpp
     ${CMAKE_SOURCE_DIR}/src/project_secrets.cpp
-    ${CMAKE_SOURCE_DIR}/src/project_secret_store.cpp)
+    ${CMAKE_SOURCE_DIR}/src/project_secret_store.cpp
+    # The store now reports a transport failure through apiErrorFor() instead of
+    # conflating it with absence, so the error mapping comes along. It is pure
+    # apart from Client::errorDetail, which the file's link-time fake provides.
+    ${CMAKE_SOURCE_DIR}/src/db_errors.cpp
+    ${CMAKE_SOURCE_DIR}/src/errors.cpp)
 target_include_directories(test_project_secret_store PRIVATE
     ${CMAKE_SOURCE_DIR}/src
     $<TARGET_PROPERTY:smartbotic::db-client,INTERFACE_INCLUDE_DIRECTORIES>)

+ 42 - 0
tests/test_api_integration.cpp

@@ -1083,6 +1083,48 @@ TEST_F(ApiFixture, DocumentTtlAcceptedOnInsertAndPatch) {
     EXPECT_EQ(nlohmann::json::parse(got->body)["v"], 2);
 }
 
+TEST_F(ApiFixture, PutRefusesTtlSecondsEvenWhenTheCollectionDoesNotExist) {
+    // THE ORDERING, AND IT IS THE POINT OF THIS TEST RATHER THAN THE REFUSAL.
+    // The rule everywhere in this service is authorize, then the server's own
+    // capability, then the REQUEST, then the resource - a request-level fault
+    // that no amount of creating the collection would fix must not hide behind
+    // the collection's absence.
+    //
+    // Measured on prod before the fix: the SAME refused parameter answered 422
+    // on a collection that existed and 404 on one that did not, because the
+    // handler resolved the collection first. A caller who misspelled the name
+    // therefore never learned the parameter is unsupported - they corrected the
+    // name, retried, and only then met the 422.
+    auto c = admin();
+    const std::string docs = "/api/v1/projects/" + project_ +
+                             "/collections/nosuchcollection_ordering/documents";
+
+    auto refused = c.Put((docs + "/row1?ttl_seconds=3600").c_str(),
+                         nlohmann::json{{"v", 1}}.dump(), "application/json");
+    ASSERT_TRUE(refused);
+    EXPECT_EQ(refused->status, 422) << "the request-level refusal must precede the 404";
+    EXPECT_EQ(nlohmann::json::parse(refused->body)["error"].value("code", ""), "unknown_option");
+
+    // THE PAIRING THAT MAKES IT A TEST OF ORDERING AND NOT OF BLANKET REFUSAL:
+    // the same route, the same absent collection, WITHOUT the offending
+    // parameter, must still answer 404. Without this half the test would pass
+    // just as well against a route that refused everything with a 422, which
+    // would be a worse defect than the one being fixed.
+    auto absent = c.Put((docs + "/row1").c_str(),
+                        nlohmann::json{{"v", 1}}.dump(), "application/json");
+    ASSERT_TRUE(absent);
+    EXPECT_EQ(absent->status, 404);
+    EXPECT_EQ(nlohmann::json::parse(absent->body)["error"].value("code", ""), "not_found");
+
+    // And authorization still comes FIRST: an unknown collection plus the bad
+    // parameter plus no key must be the auth failure, not the 422.
+    auto anon = noAuth();
+    auto unauth = anon.Put((docs + "/row1?ttl_seconds=3600").c_str(),
+                           nlohmann::json{{"v", 1}}.dump(), "application/json");
+    ASSERT_TRUE(unauth);
+    EXPECT_EQ(unauth->status, 401);
+}
+
 TEST_F(ApiFixture, PutRefusesTtlSecondsRatherThanStoringAPermanentRow) {
     // Reported by a consumer: PUT with `?ttl_seconds=3600` answered 201 and
     // stored a PERMANENT row. Their feature existed to stop a restore

+ 14 - 0
tests/test_project_secret_store.cpp

@@ -77,6 +77,20 @@ bool Client::remove(const std::string& collection, const std::string& id) {
     return g_db[collection].erase(id) > 0;
 }
 
+// The Failure& form, which the store now uses instead of an exists() probe.
+// A fake can only ever report the HAPPY shape - code Ok with false meaning
+// "did not apply" - so these tests pin the absence path and say plainly that
+// they cannot reach the transport-failure path the change exists for.
+bool Client::remove(const std::string& collection, const std::string& id, Failure& failureOut) {
+    failureOut = Failure{};
+    return g_db[collection].erase(id) > 0;
+}
+
+// Needed by db_errors.cpp, which the target now links for apiErrorFor(). No
+// test here throws a Client::Error, so answering "no detail" is the honest
+// stub rather than a convenient one.
+const Client::FailureDetail* Client::errorDetail(const Error&) noexcept { return nullptr; }
+
 std::vector<json> Client::find(const std::string& collection, const QueryOptions& options) {
     std::vector<json> page;
     for (const auto& [id, body] : g_db[collection]) {

+ 63 - 0
tests/test_stores.cpp

@@ -165,3 +165,66 @@ TEST(SettingsStore, ProjectDocsDoNotCorruptGlobalSettings) {
 
     db->client().dropCollection(coll);
 }
+
+TEST(KeyStore, CreateConfirmsTheKeyCanBeReadBackBeforeReturningIt) {
+    // WHAT THIS PINS, AND WHAT IT CANNOT: it pins the FACT the new guard rests
+    // on - that a key created through this store is present in the snapshot
+    // that reads, and therefore authentication, are served from. It canNOT
+    // exercise the failure, because nothing here can make a write land where a
+    // read cannot see it; that is the memory-only direction of the database's
+    // own store split, observed on a sibling deployment and absent on prod
+    // (its 2.20.2 boot audit reports 7219 rows disk-only and ZERO memory-only).
+    //
+    // So this test would still pass with the guard deleted. It is here so that
+    // if the property the guard depends on ever breaks, the guard is revealed
+    // as unsafe rather than quietly becoming a no-op.
+    SVAPI_REQUIRE_DB(db);
+    const std::string coll = "svapitest_keys_readback";
+    db->client().dropCollection(coll);
+    KeyStore ks(*db, coll);
+    ks.bootstrap("seed-admin-readback");
+
+    ApiKey made = ks.create("readback-probe", {"projx"}, false);
+    ASSERT_FALSE(made.id.empty());
+    ASSERT_FALSE(made.key.empty());
+
+    // The id is visible to the read path...
+    EXPECT_TRUE(ks.visible(made.id));
+    // ...and the SECRET authenticates through that same snapshot, which is the
+    // property a caller depends on and the one a 201 asserts on its behalf.
+    auto found = ks.lookup(made.key);
+    ASSERT_TRUE(found.has_value());
+    EXPECT_EQ(found->id, made.id);
+
+    // CONTROL: visible() must be capable of answering false, or the assertion
+    // above is a check that cannot fail.
+    EXPECT_FALSE(ks.visible("an-id-that-was-never-created"));
+
+    db->client().dropCollection(coll);
+}
+
+TEST(KeyStore, RemovingAKeyMakesItStopAuthenticating) {
+    // Revocation has to take effect on AUTHENTICATION, not merely on the
+    // listing. Worth its own test because on the deployed database before
+    // 2.20.2 a delete at a disk-only id answered not-found and LEFT the row,
+    // so a revocation could return 404 while the key went on working - the one
+    // failure a credential store cannot absorb. (Swept the production access
+    // log: 3 key deletions ever, all 200, so it was never exercised.)
+    SVAPI_REQUIRE_DB(db);
+    const std::string coll = "svapitest_keys_revoke";
+    db->client().dropCollection(coll);
+    KeyStore ks(*db, coll);
+    ks.bootstrap("seed-admin-revoke");
+
+    ApiKey made = ks.create("revoke-probe", {"projx"}, false);
+    ASSERT_TRUE(ks.lookup(made.key).has_value()) << "precondition: the new key works";
+
+    EXPECT_TRUE(ks.remove(made.id));
+    EXPECT_FALSE(ks.visible(made.id));
+    EXPECT_FALSE(ks.lookup(made.key).has_value()) << "the revoked secret must not authenticate";
+
+    // CONTROL: removing it again reports false, so the first true meant something.
+    EXPECT_FALSE(ks.remove(made.id));
+
+    db->client().dropCollection(coll);
+}