Преглед изворни кода

fix: a scope refusal names the collection, the op and what the key holds

requireCapabilityCore answered 403 "scope does not permit this operation"
with no collection, no op and no hint of what the caller CAN reach, so a
misspelled name, an ungranted one and a never-provisioned one were
byte-identical. That cost three days on a live site: toloajto:kitchen_presets
403'd on every page load, and the identical refusal sent its owner to
re-verify their KEY rather than the string - the wrong half of the system. It
also led me to guess which of the two causes it was, and to guess wrong.

THE STATUS DOES NOT MOVE. Answering 404 for an absent collection and 403 for
an ungranted one would let a scoped key probe which collections exist in its
project outside its own scope, a leak closed deliberately in 0.13.0. Only the
message changed, and an integration test asserts 403 rather than 404 for
exactly that reason.

The message now names the collection and the op, echoes the collections the
key IS granted, and says outright that the same refusal is returned whether
the collection is out of scope or does not exist - because the status cannot
distinguish them and the holder is the only party who can. That sentence is
the one that would have saved the three days. details carries collection,
operation and granted.

Two smaller decisions: the granted list is NOT filtered to rules mentioning
the requested collection, since the caller's problem is usually that they are
asking about the wrong name and such a list would be empty exactly when it is
most needed; and a key with no rules says so in words, because an empty list
reads like a failure to render.

The disclosure boundary is unit-tested rather than inferred. One test asserts
the refusal names no collection the key does not hold; another asserts it is
byte-identical for two names the key equally lacks, once the caller's own
input is normalised out - so a later change that passed collection EXISTENCE
into the message has to delete that assertion deliberately rather than by
accident. 8 tests, one of them driving the route. Suite 1333/1333 serially.
fszontagh пре 1 месец
родитељ
комит
302bfee13c
9 измењених фајлова са 264 додато и 3 уклоњено
  1. 0 1
      CLAUDE.md
  2. 2 0
      api/llms.txt
  3. 1 0
      src/CMakeLists.txt
  4. 57 0
      src/scope_refusal.cpp
  5. 42 0
      src/scope_refusal.hpp
  6. 8 2
      src/server.cpp
  7. 5 0
      tests/CMakeLists.txt
  8. 33 0
      tests/test_api_integration.cpp
  9. 116 0
      tests/test_scope_refusal.cpp

Разлика између датотеке није приказан због своје велике величине
+ 0 - 1
CLAUDE.md


+ 2 - 0
api/llms.txt

@@ -36,6 +36,8 @@ A non-admin key may carry a `scope` object that restricts what it can do. Scoped
 - `rate_limit_per_min` (integer, default 0 = unlimited) - Per-key request rate limit. When the limit is exceeded the server returns **429** with a `Retry-After: 60` header.
 - `expires_at` (integer, default 0 = never) - Unix epoch seconds after which the key is treated as expired; auth returns 401.
 
+
+**A scope refusal names what it refused and what you hold** (0.15.0+). A 403 `forbidden` from a scoped key carries a message naming the collection and the operation asked, plus the collections the key IS granted, and `error.details` with `collection`, `operation` and `granted` (each `{collection, ops}`). **The status is 403 whether the collection is outside your scope OR does not exist, and that is deliberate** - answering 404 for an absent collection would let a scoped key discover which collections exist in its project outside its own scope. So the message says as much: only you can tell a misspelled name from one nobody provisioned, and the answer will not tell you. Before 0.15.0 the message was just "scope does not permit this operation", which named neither and sent people to re-verify their key rather than the string.
 ### CAPTCHA-gated operations
 
 A scope rule may set `require_human_token: true`. When this flag is active, the client must supply an `X-Captcha-Token` request header containing the CAPTCHA challenge response. The server verifies the token via the configured provider endpoint and returns **403** `captcha_required` if the token is absent, invalid, or if no provider is configured. Configure the provider via the settings API: `captcha_provider` (`"turnstile"` or `"hcaptcha"`), `captcha_secret` (server-side secret), and `captcha_verify_url` (full verify endpoint URL).

+ 1 - 0
src/CMakeLists.txt

@@ -56,6 +56,7 @@ add_library(vectorapi_core STATIC
     functions/fn_gate.cpp
     functions/error_hook.cpp
     function_error_dispatch.cpp
+    scope_refusal.cpp
     functions/net_guard.cpp
 )
 target_include_directories(vectorapi_core PUBLIC

+ 57 - 0
src/scope_refusal.cpp

@@ -0,0 +1,57 @@
+#include "scope_refusal.hpp"
+#include <algorithm>
+
+namespace svapi {
+
+ScopeRefusal describeScopeRefusal(const KeyScope& scope, const std::string& collection,
+                                  KeyOp op) {
+    ScopeRefusal out;
+    const std::string opName = keyOpToString(op);
+
+    nlohmann::json granted = nlohmann::json::array();
+    // Every rule, in the order the key declares them. Deliberately NOT
+    // filtered to rules mentioning the requested collection: the caller's
+    // problem is usually that they are asking about the wrong name, and a
+    // list filtered by that same wrong name would be empty exactly when it
+    // is most needed.
+    for (const KeyScopeRule& rule : scope.rules) {
+        nlohmann::json ops = nlohmann::json::array();
+        for (KeyOp o : rule.ops) ops.push_back(keyOpToString(o));
+        granted.push_back({{"collection", rule.collection}, {"ops", std::move(ops)}});
+    }
+
+    out.message = "this key may not " + opName + " '" + collection + "'";
+    if (scope.rules.empty()) {
+        // A key with no rules at all is a different mistake from a key with
+        // the wrong rules, and saying so saves the holder reading an empty
+        // list and wondering whether it failed to render.
+        out.message += ": its scope grants no collections at all";
+    } else {
+        out.message += ". This key is granted: ";
+        bool first = true;
+        for (const KeyScopeRule& rule : scope.rules) {
+            if (!first) out.message += ", ";
+            first = false;
+            out.message += rule.collection + " (";
+            bool firstOp = true;
+            for (KeyOp o : rule.ops) {
+                if (!firstOp) out.message += "/";
+                firstOp = false;
+                out.message += keyOpToString(o);
+            }
+            out.message += ")";
+        }
+        // The sentence a reader needs most, because the status cannot say it:
+        // the refusal is identical whether the collection is misspelled,
+        // ungranted or was never created, and only the holder can tell which.
+        out.message +=
+            ". Note this same refusal is returned whether '" + collection +
+            "' is outside this key's scope or does not exist - the status cannot "
+            "distinguish them, by design";
+    }
+
+    out.details = {{"collection", collection}, {"operation", opName}, {"granted", granted}};
+    return out;
+}
+
+} // namespace svapi

+ 42 - 0
src/scope_refusal.hpp

@@ -0,0 +1,42 @@
+#pragma once
+#include "apikey.hpp"
+#include <nlohmann/json.hpp>
+#include <string>
+
+namespace svapi {
+
+/// The message and details a scope refusal carries.
+///
+/// WHY THIS EXISTS: the refusal used to be 403 "scope does not permit this
+/// operation" with no collection, no op and no hint of what the caller CAN
+/// reach - so a misspelled collection name, an ungranted one and a
+/// never-provisioned one were byte-identical in the answer. That cost three
+/// days on a live site: `toloajto:kitchen_presets` 403'd on every page load,
+/// and the identical refusal sent its owner to re-verify their KEY rather
+/// than the string, which is the wrong half of the system. It also led me to
+/// guess which of the two causes it was, and to guess wrong.
+///
+/// THE STATUS STAYS 403. Answering 404 for an absent collection and 403 for
+/// an ungranted one would let a scoped key probe which collections exist in
+/// its project outside its own scope - a leak closed deliberately in 0.13.0.
+/// Only the MESSAGE changes.
+///
+/// THE DISCLOSURE BOUNDARY: echoing the collections this key IS granted
+/// discloses nothing the holder cannot already read off their own key, which
+/// is the same reasoning that makes `scope_filtered` safe to send
+/// unconditionally. It must NOT name collections outside the grant, must not
+/// say whether the requested collection exists, and must not vary with its
+/// existence - otherwise the leak comes back through the message instead of
+/// the status.
+///
+/// Pure, so the boundary is unit-tested rather than inferred from a handler.
+struct ScopeRefusal {
+    std::string message;
+    /// `collection`, `operation`, and `granted` - the rules this key holds,
+    /// each as `{"collection": name, "ops": [...]}`.
+    nlohmann::json details;
+};
+
+ScopeRefusal describeScopeRefusal(const KeyScope& scope, const std::string& collection, KeyOp op);
+
+} // namespace svapi

+ 8 - 2
src/server.cpp

@@ -1,3 +1,4 @@
+#include "scope_refusal.hpp"
 #include "server.hpp"
 #include "captcha.hpp"
 #include "db_errors.hpp"
@@ -53,8 +54,13 @@ void requireCapabilityCore(const Principal& p, const std::string& project,
     requireProjectAccess(p, project);
     if (!p.scope) return;                                   // unscoped: full access
     const KeyScope& sc = *p.scope;
-    if (!sc.findRule(collection, op))
-        throw ApiError(ErrCode::Forbidden, "forbidden", "scope does not permit this operation");
+    if (!sc.findRule(collection, op)) {
+        // Names the collection and the op, and echoes what this key IS
+        // granted. Status stays 403 on purpose - see scope_refusal.hpp for
+        // why 404-for-absent would reopen a closed leak.
+        const ScopeRefusal r = describeScopeRefusal(sc, collection, op);
+        throw ApiError(ErrCode::Forbidden, "forbidden", r.message, r.details);
+    }
     if (!rateLimiter().allow(p.id, sc.rateLimitPerMin))
         throw ApiError(ErrCode::TooManyRequests, "rate_limited", "rate limit exceeded");
 }

+ 5 - 0
tests/CMakeLists.txt

@@ -96,6 +96,11 @@ target_link_libraries(test_functions_descriptor PRIVATE
     nlohmann_json::nlohmann_json GTest::gtest_main)
 gtest_discover_tests(test_functions_descriptor)
 
+# What a scope refusal may disclose.
+add_executable(test_scope_refusal test_scope_refusal.cpp)
+target_link_libraries(test_scope_refusal PRIVATE vectorapi_core GTest::gtest_main)
+gtest_discover_tests(test_scope_refusal)
+
 # The error-handler trigger: selection, the loop guard and the payload.
 add_executable(test_error_hook
     test_error_hook.cpp

+ 33 - 0
tests/test_api_integration.cpp

@@ -4572,3 +4572,36 @@ TEST_F(ApiFixture, TheGateIsCheckedBeforeTheRunnerSoItDoesNotNeedOne) {
     EXPECT_EQ(res->status, 401) << "the gate must answer before the missing runner does: "
                                 << res->body;
 }
+
+// ─── The scope refusal names things now (task #83) ────────────────────────
+//
+// test_scope_refusal.cpp pins the disclosure boundary on the pure function.
+// This drives the ROUTE, because the message is only useful if it is the one
+// a real caller actually receives - and because the status must NOT have
+// moved while the message improved.
+TEST_F(ApiFixture, AScopeRefusalNamesTheCollectionTheOpAndWhatTheKeyHolds) {
+    auto mk = admin().Post("/api/v1/keys",
+        nlohmann::json{{"label", "narrow"}, {"projects", {project_}}, {"admin", false},
+                       {"scope", {{"rules", {{{"collection", "designs"}, {"ops", {"read"}}}}}}}}
+            .dump(), "application/json");
+    ASSERT_EQ(mk->status, 201) << mk->body;
+    const std::string scoped = nlohmann::json::parse(mk->body)["key"];
+
+    // A collection this key is not granted, and which does not exist either -
+    // the two causes that used to be byte-identical AND unnamed.
+    auto res = request("GET", "/api/v1/projects/" + project_ + "/collections/kitchen_presets/documents",
+                       "", "", scoped);
+    ASSERT_TRUE(res);
+    EXPECT_EQ(res->status, 403) << "the status must NOT have moved to 404: that would let a "
+                                  "scoped key probe which collections exist: " << res->body;
+    const auto body = nlohmann::json::parse(res->body);
+    EXPECT_EQ(body["error"]["code"], "forbidden") << res->body;
+    const std::string msg = body["error"]["message"];
+    EXPECT_NE(msg.find("kitchen_presets"), std::string::npos) << msg;
+    EXPECT_NE(msg.find("designs"), std::string::npos)
+        << "the holder must be told what the key DOES reach: " << msg;
+    ASSERT_TRUE(body["error"].contains("details"));
+    EXPECT_EQ(body["error"]["details"]["collection"], "kitchen_presets");
+    ASSERT_EQ(body["error"]["details"]["granted"].size(), 1u);
+    EXPECT_EQ(body["error"]["details"]["granted"][0]["collection"], "designs");
+}

+ 116 - 0
tests/test_scope_refusal.cpp

@@ -0,0 +1,116 @@
+// What a scope refusal is allowed to say.
+//
+// The status stays 403; only the message changed. These tests pin the
+// DISCLOSURE BOUNDARY, which is the part that could quietly reopen the leak
+// closed in 0.13.0: a scoped key must not be able to learn which collections
+// exist in its project outside its own scope. Echoing what the key IS granted
+// is safe - the holder can read that off their own key - while anything that
+// varied with the requested collection's EXISTENCE would move the leak from
+// the status code into the message.
+#include "scope_refusal.hpp"
+#include <gtest/gtest.h>
+
+using namespace svapi;
+
+namespace {
+
+KeyScope scopeWith(std::vector<KeyScopeRule> rules) {
+    KeyScope s;
+    s.rules = std::move(rules);
+    return s;
+}
+
+KeyScopeRule rule(const std::string& coll, std::set<KeyOp> ops) {
+    KeyScopeRule r;
+    r.collection = coll;
+    r.ops = std::move(ops);
+    return r;
+}
+
+} // namespace
+
+TEST(ScopeRefusal, NamesTheCollectionAndTheOperation) {
+    // The whole complaint: the old message named neither, so a misspelling and
+    // a missing grant read identically and sent the holder to check their KEY.
+    const ScopeRefusal r =
+        describeScopeRefusal(scopeWith({rule("designs", {KeyOp::Read})}), "kitchen_presets",
+                             KeyOp::Read);
+    EXPECT_NE(r.message.find("kitchen_presets"), std::string::npos);
+    EXPECT_NE(r.message.find("read"), std::string::npos);
+    EXPECT_EQ(r.details["collection"], "kitchen_presets");
+    EXPECT_EQ(r.details["operation"], "read");
+}
+
+TEST(ScopeRefusal, EchoesWhatTheKeyISGranted) {
+    const ScopeRefusal r = describeScopeRefusal(
+        scopeWith({rule("designs", {KeyOp::Read, KeyOp::List}), rule("quotes", {KeyOp::Insert})}),
+        "nope", KeyOp::Read);
+    EXPECT_NE(r.message.find("designs"), std::string::npos);
+    EXPECT_NE(r.message.find("quotes"), std::string::npos);
+    ASSERT_EQ(r.details["granted"].size(), 2u);
+    EXPECT_EQ(r.details["granted"][0]["collection"], "designs");
+    EXPECT_EQ(r.details["granted"][1]["collection"], "quotes");
+}
+
+// THE BOUNDARY TEST. Nothing in the answer may name a collection the key does
+// not hold, other than the one the caller themselves asked about.
+TEST(ScopeRefusal, LeaksNoCollectionTheKeyDoesNotHold) {
+    const ScopeRefusal r =
+        describeScopeRefusal(scopeWith({rule("designs", {KeyOp::Read})}), "asked", KeyOp::Read);
+    for (const char* secret : {"catalog_kitchen_modules", "settings", "quotes", "vectorapi_keys"}) {
+        EXPECT_EQ(r.message.find(secret), std::string::npos)
+            << "the refusal must not name " << secret;
+        EXPECT_EQ(r.details.dump().find(secret), std::string::npos)
+            << "the details must not name " << secret;
+    }
+}
+
+// The refusal cannot depend on whether the collection exists, and the cheapest
+// way to guarantee that is structural: this function is never TOLD. Pinned as
+// a test so a later "helpful" change that passes existence in has to delete
+// this assertion deliberately rather than by accident.
+TEST(ScopeRefusal, IsIdenticalForTwoNamesTheKeyEquallyLacks) {
+    const KeyScope s = scopeWith({rule("designs", {KeyOp::Read})});
+    const ScopeRefusal a = describeScopeRefusal(s, "exists_but_ungranted", KeyOp::Read);
+    const ScopeRefusal b = describeScopeRefusal(s, "never_created", KeyOp::Read);
+    // They may differ ONLY by the name the caller themselves supplied, which
+    // is echoed more than once, so normalise that out and demand the rest be
+    // byte-identical.
+    auto normalise = [](std::string msg, const std::string& name) {
+        for (size_t at = msg.find(name); at != std::string::npos; at = msg.find(name, at + 5))
+            msg.replace(at, name.size(), "NAME");
+        return msg;
+    };
+    EXPECT_EQ(normalise(a.message, "exists_but_ungranted"),
+              normalise(b.message, "never_created"))
+        << "the refusal must not vary with anything but the caller's own input";
+    EXPECT_EQ(a.details["granted"], b.details["granted"]);
+}
+
+TEST(ScopeRefusal, SaysTheTwoCausesAreIndistinguishable) {
+    // The sentence that would have saved three days on a live site: the holder
+    // is the only party who can tell a misspelling from an unprovisioned
+    // collection, so the message has to tell them that is the question.
+    const ScopeRefusal r =
+        describeScopeRefusal(scopeWith({rule("designs", {KeyOp::Read})}), "kitchen_presets",
+                             KeyOp::Read);
+    EXPECT_NE(r.message.find("does not exist"), std::string::npos) << r.message;
+}
+
+TEST(ScopeRefusal, AKeyWithNoRulesSaysSoRatherThanShowingAnEmptyList) {
+    // A different mistake from the wrong rules, and an empty list reads like a
+    // rendering failure.
+    const ScopeRefusal r = describeScopeRefusal(scopeWith({}), "anything", KeyOp::Read);
+    EXPECT_NE(r.message.find("no collections at all"), std::string::npos) << r.message;
+    EXPECT_TRUE(r.details["granted"].empty());
+}
+
+TEST(ScopeRefusal, ReportsTheOpsOfEachGrantedRule) {
+    const ScopeRefusal r = describeScopeRefusal(
+        scopeWith({rule("designs", {KeyOp::Read, KeyOp::Insert})}), "x", KeyOp::Delete);
+    const std::string dumped = r.details["granted"].dump();
+    EXPECT_NE(dumped.find("read"), std::string::npos);
+    EXPECT_NE(dumped.find("insert"), std::string::npos);
+    EXPECT_EQ(r.details["operation"], "delete")
+        << "the op asked for must be the one reported, not one the key happens to hold";
+}

Неке датотеке нису приказане због велике количине промена