Bläddra i källkod

fix: the collections listing answers to the key's scope, not just the grant

A key granted exactly ONE collection could read every collection's name,
document count and size in its project, because the listing checked only
requireProjectAccess, which never consults the scope rules. The tell was
internal inconsistency rather than a report: the index-values route next
door authorizes through requireCapability, which does consult them.

Three decisions worth keeping:

The op asked is "does ANY rule mention this collection"
(KeyScope::reachesCollection), deliberately weaker than a `list` grant. A
key that may read one document there already knows the collection exists,
so hiding the name buys nothing while costing the thing the listing was
added for - a consumer had to hardcode four names into a backup script and
silently missed a collection added later. What it must not do is enumerate
collections the key cannot touch at all.

The rule is looked up directly rather than through requireCapabilityCore
per collection, because that also CHARGES THE RATE LIMITER: one listing of
fifty collections would have spent fifty of the key's tokens and could
rate-limit a caller for a single request. A test pins that a
two-per-minute key affords one listing of several collections.

An out-of-scope collection is ABSENT rather than refused, and the response
carries `scope_filtered`, true for every scoped key whether or not anything
was withheld. "Something was hidden" would leak one bit about a collection
outside the caller's scope; "your view is partial" leaks nothing a holder
cannot derive from their own key - and it stops an empty list reading as an
empty project.

BREAKING for scoped keys. 1268/1268 green; docs updated.
fszontagh 1 månad sedan
förälder
incheckning
ebd7e1ab66
7 ändrade filer med 140 tillägg och 2 borttagningar
  1. 4 0
      CLAUDE.md
  2. 3 0
      api/llms.txt
  3. 5 1
      api/openapi.json
  4. 6 0
      src/apikey.cpp
  5. 16 0
      src/apikey.hpp
  6. 39 1
      src/handlers/collections.cpp
  7. 67 0
      tests/test_api_integration.cpp

+ 4 - 0
CLAUDE.md

@@ -37,6 +37,10 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - `src/` - the server. `vectorapi_core` static lib + `main.cpp`. Namespace `svapi`. Flat headers, quoted includes.
   - `db_gateway` (`qualify(project,coll)` + `DbGateway` over `smartbotic::database::Client`), `settings_store` (global settings **and per-project embedding overrides**, hot-reload, one subscribe stream for both), `project_settings` (`ProjectEmbeddingSettings` + the pure `resolveEmbedding()`), `outbound_http` (User-Agent + TLS defaults for every external call), `key_store` (API keys, hot-reload, bootstrap admin key), `collection_registry` (per-project metadata), `embeddings` (OpenAI), `auth` (sessions, bearer/cookie), `server` (ApiServer + auth helpers), `handlers/*` (one file per route group).
   - Auth model: pre-routing **authenticates** `/api/*` (401); each handler **authorizes** via `requireKey` → `requireAdmin` / `requireProjectAccess` (403). Keys are referenced by a stable **`id`** (not the secret).
+    **THE COLLECTIONS LISTING ANSWERS TO THE SCOPE RULES AS WELL AS THE PROJECT GRANT** (2026-10-13). It used to check only `requireProjectAccess`, which never consults the rules, so a key granted exactly ONE collection could read every collection's name, document count and size in its project. The tell was internal inconsistency rather than a report: the index-values route next door authorizes through `requireCapability`, which does consult them. Three decisions in the fix are load-bearing:
+    - **The op asked is "does ANY rule mention this collection" (`KeyScope::reachesCollection`), deliberately weaker than `findRule(name, KeyOp::List)`.** A key that may read one document there already knows the collection exists, so hiding the name buys nothing and costs the thing the listing was added for - a consumer had to hardcode four collection names into a backup script, and a collection added later was silently missed. What the listing must not do is enumerate collections the key cannot touch AT ALL. A `read`-only rule therefore still shows the name, which keeps `AScopedKeyMayListCollectionsButNotCreateThem` true.
+    - **The rule is looked up DIRECTLY, not via `requireCapabilityCore` per collection, because that function also CHARGES THE RATE LIMITER.** One listing of fifty collections would have spent fifty of the key's tokens and could rate-limit a caller for a single request. The limit is charged once, for the one request it is, and a test pins that a two-per-minute key affords one listing of several collections. The "one implementation" rule is still honoured - `reachesCollection` calls the same `collMatches`; what is not reused is the throwing-and-charging wrapper, which is wrong for a filter.
+    - **An out-of-scope collection is ABSENT, not refused**, like a disabled function being 404 on `/fn` rather than 403; and the response carries **`scope_filtered`, which is true for EVERY scoped key whether or not anything was withheld.** "Something was hidden" would leak one bit about the existence of a collection outside the caller's scope; "your view is partial" leaks nothing a holder cannot derive from their own key. It exists because an empty list would otherwise be indistinguishable from an empty project, which is this file's most repeated trap.
     **CONSEQUENCE WORTH KNOWING BEFORE YOU PROBE ANYTHING: an unauthenticated request to a NONEXISTENT `/api/*` path answers 401, not 404**, because the pre-routing filter runs before routing and never consults the route table. So a 401 cannot distinguish "the route exists and I lack a key" from "there is no such route" - and reading one as "the service is alive" is a check that answers confidently about a different question. Measured during the 0.12.0 deploy: `/api/v1/healthz` gave 401 unauthenticated and **404 with a valid admin key**, because the health route is `/healthz` and is NOT under `/api/`. Probe liveness at `/healthz`, and when a path matters, send a key so the 404 can reach you.
 - `webui/` - React 19 + Vite + TS (strict, `erasableSyntaxOnly`) + Tailwind + Monaco. **`npx tsc --noEmit` is NOT the build check** - it passed on a malformed import that `npm run build` (`tsc -b && vite build`) rejected, because the project build uses different settings. Verify a UI change with `npm run build`.
   - **A `Functions` settings tab exists and is ADMIN-ONLY**, matching its route (`requireAdmin`, not `requireProjectManage`): it bounds what one project may take from a runner every other project shares. It carries the per-kind wall caps and `network_egress`, both of which were previously reachable only by curl - and a control nobody can see is a control nobody knows exists, which mattered most for egress, where an operator could not tell whether a project's functions had outbound access. Egress renders THREE states, because `network_egress` is the effective value and `network_egress_set` says whether it was chosen or inherited: "allow (inherited)" is a different statement from "allow, set here". An empty wall-cap field means NO project cap, which is not a cap of zero, so it is held as a string to keep an empty input and a zero distinguishable all the way to the request.

+ 3 - 0
api/llms.txt

@@ -56,6 +56,9 @@ Project-scoped. A key must be granted the project.
 
 - `POST   /api/v1/projects/{project}/collections` `{name, kind:"json"|"vector", vector_dimension?, embedding_model?}` - Create a collection. `vector_dimension` is required for `kind=vector`. `embedding_model` defaults to the server's `default_embedding_model` setting.
 - `GET    /api/v1/projects/{project}/collections` - List collections with metadata (incl. `document_count`, `size_bytes`). Query params (all applied server-side): `q` (case-insensitive name substring filter), `sort` (`name`|`kind`|`documents`|`size`|`created_at`, default `name`), `desc` (bool).
+  **BREAKING FOR SCOPED KEYS: this listing is now FILTERED BY YOUR KEY'S SCOPE.** A key with scope rules sees only the collections at least one of its rules mentions; previously a project grant alone was enough, so a key granted exactly one collection could read every collection's name, document count and size in that project. A full (unscoped) key is unaffected.
+  The op asked is "does any rule mention this collection", deliberately weaker than a `list` grant: if your key may read one document there, the collection's existence is not a secret from it, so a `read`-only rule still shows the name. What you no longer get is an enumeration of collections your key cannot touch at all. A collection outside your scope is simply ABSENT - there is no 403 and nothing names what was withheld, the same way a disabled function is 404 on `/fn` rather than 403.
+  **The response now carries `scope_filtered`** (always present): true for any scoped key, false for a full one. It means "this listing shows only what your scope permits" and NOT "something was hidden" - it is true even when nothing was withheld, so it leaks nothing a key holder cannot already derive from their own scope. Read it before concluding a project is empty: an empty `collections` with `scope_filtered: true` means your key reaches nothing here, which is a different fact from the project having no collections.
 - `GET    /api/v1/projects/{project}/collections/{name}` - Get collection metadata.
 - `DELETE /api/v1/projects/{project}/collections/{name}` - Drop a collection and all its documents.
 

+ 5 - 1
api/openapi.json

@@ -1162,6 +1162,10 @@
                       "items": {
                         "$ref": "#/components/schemas/CollectionMeta"
                       }
+                    },
+                    "scope_filtered": {
+                      "type": "boolean",
+                      "description": "True for any scoped key: the listing shows only what the key's scope permits. Always present."
                     }
                   }
                 }
@@ -1175,7 +1179,7 @@
             "description": "Forbidden"
           }
         },
-        "description": "List collections in a project\n\n**Refuses a query parameter it cannot honour** (422 `unknown_option`) rather than accepting and ignoring it. Incidental parameters (a cache-buster, `_=<timestamp>`, `utm_*`) are still ignored - what is refused is the set a caller plausibly sends expecting an effect, which is mostly this API's OTHER routes' spellings of the same idea. The error carries `details.unsupported` and, where this route has an equivalent, `details.instead`. Accepted here: `q`, `sort`, `desc`. This listing is NOT paginated, so `limit`, `offset`, `page` and `cursor` are refused rather than ignored."
+        "description": "List collections in a project\n\n**Refuses a query parameter it cannot honour** (422 `unknown_option`) rather than accepting and ignoring it. Incidental parameters (a cache-buster, `_=<timestamp>`, `utm_*`) are still ignored - what is refused is the set a caller plausibly sends expecting an effect, which is mostly this API's OTHER routes' spellings of the same idea. The error carries `details.unsupported` and, where this route has an equivalent, `details.instead`. Accepted here: `q`, `sort`, `desc`. This listing is NOT paginated, so `limit`, `offset`, `page` and `cursor` are refused rather than ignored.\n\n**Filtered by the key's scope.** A scoped key sees only collections at least one of its rules mentions (any op - a `read` rule is enough, since a key that may read a document already knows the collection exists). A collection outside the scope is absent rather than refused. `scope_filtered` is always present and is true for any scoped key, meaning \"this listing shows only what your scope permits\" rather than \"something was hidden\" - so an empty list with `scope_filtered: true` means your key reaches nothing here, which is not the same as the project being empty."
       },
       "post": {
         "summary": "Create a collection in a project",

+ 6 - 0
src/apikey.cpp

@@ -66,6 +66,12 @@ const KeyScopeRule* KeyScope::findRule(const std::string& collection, KeyOp op)
     return nullptr;
 }
 
+bool KeyScope::reachesCollection(const std::string& collection) const {
+    for (const auto& r : rules)
+        if (collMatches(r.collection, collection) && !r.ops.empty()) return true;
+    return false;
+}
+
 bool KeyScope::originAllowed(const std::string& origin) const {
     if (origins.empty()) return true;
     for (const auto& o : origins) if (o == origin) return true;

+ 16 - 0
src/apikey.hpp

@@ -23,6 +23,22 @@ struct KeyScope {
     uint32_t rateLimitPerMin = 0;      // 0 = unlimited
     uint64_t expiresAt       = 0;      // epoch seconds; 0 = never
     const KeyScopeRule* findRule(const std::string& collection, KeyOp op) const;
+
+    /// Whether ANY rule mentions this collection, whatever the op.
+    ///
+    /// The question a LISTING asks, and it is deliberately weaker than
+    /// `findRule(name, KeyOp::List)`. If a key may do anything at all with a
+    /// collection - read one document, insert one - then its existence is not
+    /// a secret from that key, and hiding the name buys nothing while costing
+    /// the thing the listing was added for: a consumer had to hardcode four
+    /// collection names into a backup script, so a collection added later was
+    /// silently missed. What the listing must not do is enumerate collections
+    /// the key cannot touch AT ALL.
+    ///
+    /// Pure and op-free, so it also charges no rate limit - unlike
+    /// `requireCapabilityCore`, which would spend one token per collection
+    /// examined and could rate-limit a caller for a single listing.
+    bool reachesCollection(const std::string& collection) const;
     bool originAllowed(const std::string& origin) const;
     bool expired(uint64_t nowEpochSec) const;
     static KeyScope fromJson(const nlohmann::json& j);

+ 39 - 1
src/handlers/collections.cpp

@@ -2,6 +2,7 @@
 #include "errors.hpp"
 #include "json_http.hpp"
 #include "query_params.hpp"
+#include "rate_limiter.hpp"
 #include "server.hpp"
 #include <algorithm>
 #include <cctype>
@@ -89,6 +90,27 @@ void registerCollectionRoutes(ApiServer& s) {
         // full key below.
         requireProjectAccess(k, project);
 
+        // AND THE LISTING ANSWERS TO THE SCOPE RULES, not merely to the
+        // project grant. Project access alone let a key granted exactly ONE
+        // collection read every collection's name, document count and size in
+        // its project - the index-values route next door consults the rules
+        // through `requireCapability` while this one did not, which is what
+        // made it an oversight rather than a design.
+        //
+        // The op asked is "does ANY rule mention this collection" rather than
+        // `List` specifically - see `reachesCollection`. A key that may read
+        // one document already knows the collection exists.
+        //
+        // The rule is looked up DIRECTLY rather than by calling
+        // `requireCapabilityCore` per collection, and the reason is not
+        // style: that function also charges the rate limiter, so one listing
+        // of fifty collections would have spent fifty of the key's tokens and
+        // could rate-limit a caller for a single request. The rate limit is
+        // charged ONCE here, for the one request it is.
+        const bool scoped = k.scope.has_value();
+        if (scoped && !rateLimiter().allow(k.id, k.scope->rateLimitPerMin))
+            throw ApiError(ErrCode::TooManyRequests, "rate_limited", "rate limit exceeded");
+
         auto lower = [](std::string s) {
             std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::tolower(c); });
             return s;
@@ -115,6 +137,12 @@ void registerCollectionRoutes(ApiServer& s) {
         std::vector<nlohmann::json> items;
         for (const auto& m : d->registry.list(project)) {
             if (!q.empty() && lower(m.name).find(q) == std::string::npos) continue;
+            // Absent from the listing rather than refused: a 403 on the whole
+            // listing would be useless to a key that legitimately reaches one
+            // collection, and naming what was withheld would defeat the point.
+            // Same reasoning as a disabled function being 404 on `/fn` rather
+            // than 403.
+            if (scoped && !k.scope->reachesCollection(m.name)) continue;
             nlohmann::json e = m.toJson();
             const std::string qc = qualify(project, m.name);
             // count() is the authoritative document count; getCollectionInfo()'s
@@ -147,7 +175,17 @@ void registerCollectionRoutes(ApiServer& s) {
 
         nlohmann::json out = nlohmann::json::array();
         for (auto& e : items) out.push_back(std::move(e));
-        sendJson(res, 200, {{"collections", out}});
+        // `scope_filtered` says "this listing shows only what your scope
+        // permits" and is true for EVERY scoped key, whether or not anything
+        // was actually withheld.
+        //
+        // Deliberately not "something was hidden": that would leak one bit
+        // about the existence of a collection outside the caller's scope,
+        // where this phrasing leaks nothing - a holder can derive it from
+        // their own key. It exists because an empty list would otherwise be
+        // indistinguishable from an empty project, and reading absence as
+        // information is the trap this service keeps finding.
+        sendJson(res, 200, {{"collections", out}, {"scope_filtered", scoped}});
     });
 
     svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {

+ 67 - 0
tests/test_api_integration.cpp

@@ -4261,3 +4261,70 @@ TEST_F(ApiFixture, NoListingRouteRefusesAnIncidentalParameter) {
         EXPECT_EQ(res->status, 200) << path << ": " << res->body;
     }
 }
+
+// A COLLECTION-SCOPED KEY MUST NOT ENUMERATE THE WHOLE PROJECT. Project access
+// alone used to be the only check here, so a key granted exactly one
+// collection could read every collection's name, document count and size -
+// while the index-values route next door consulted the scope rules through
+// `requireCapability`. That inconsistency is what marked it an oversight.
+TEST_F(ApiFixture, TheCollectionsListingIsFilteredByTheKeysScope) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    for (const char* n : {"scopemine", "scopetheirs"}) {
+        c.Delete((base + "/" + n).c_str());
+        ASSERT_EQ(c.Post(base.c_str(),
+                         nlohmann::json{{"name", n}, {"kind", "json"}}.dump(),
+                         "application/json")->status, 201) << n;
+    }
+
+    auto mk = c.Post("/api/v1/keys",
+        nlohmann::json{{"label", "scopedlister"}, {"projects", {project_}}, {"admin", false},
+                       {"scope", {{"rules", {{{"collection", "scopemine"},
+                                              {"ops", {"read"}}}}}}}}
+            .dump(), "application/json");
+    ASSERT_TRUE(mk); ASSERT_EQ(mk->status, 201) << mk->body;
+    const std::string scoped = nlohmann::json::parse(mk->body)["key"];
+
+    auto listed = request("GET", base, "", "", scoped);
+    ASSERT_TRUE(listed);
+    ASSERT_EQ(listed->status, 200) << listed->body;
+    const nlohmann::json j = nlohmann::json::parse(listed->body);
+    bool sawMine = false, sawTheirs = false;
+    for (const auto& m : j["collections"]) {
+        if (m["name"] == "scopemine")   sawMine = true;
+        if (m["name"] == "scopetheirs") sawTheirs = true;
+    }
+    // BOTH directions, or this proves nothing: a check that only asserts the
+    // absence would pass against a route that returns an empty list, and one
+    // that only asserts the presence would pass against no filtering at all.
+    EXPECT_TRUE(sawMine) << "a key granted a collection must still see it: " << listed->body;
+    EXPECT_FALSE(sawTheirs) << "scope does not reach this collection: " << listed->body;
+
+    // `read` is enough. The op asked is "any rule mentions it", deliberately
+    // weaker than `list`: a key that may read a document already knows the
+    // collection exists, and the listing exists so nobody has to hardcode
+    // names into a backup script.
+    EXPECT_TRUE(j["scope_filtered"].get<bool>()) << listed->body;
+
+    // An unscoped key is told its view is COMPLETE, which is what keeps an
+    // empty list from reading as an empty project for everyone else.
+    auto full = c.Get(base.c_str());
+    ASSERT_EQ(full->status, 200) << full->body;
+    EXPECT_FALSE(nlohmann::json::parse(full->body)["scope_filtered"].get<bool>()) << full->body;
+
+    // One listing must cost ONE rate-limit token, not one per collection
+    // examined. Charging per collection would let a caller rate-limit itself
+    // on a single request, which is why the rule is looked up directly rather
+    // than through requireCapabilityCore.
+    auto mk2 = c.Post("/api/v1/keys",
+        nlohmann::json{{"label", "scopedlister2"}, {"projects", {project_}}, {"admin", false},
+                       {"scope", {{"rate_limit_per_min", 2},
+                                  {"rules", {{{"collection", "*"}, {"ops", {"read"}}}}}}}}
+            .dump(), "application/json");
+    ASSERT_EQ(mk2->status, 201) << mk2->body;
+    const std::string limited = nlohmann::json::parse(mk2->body)["key"];
+    auto one = request("GET", base, "", "", limited);
+    ASSERT_TRUE(one);
+    EXPECT_EQ(one->status, 200) << "a two-per-minute key must afford one listing of "
+                                   "several collections: " << one->body;
+}