Selaa lähdekoodia

fix: the collections listing answers to the Origin allow-list too

Measured by a consumer with their own publishable key: GET
/projects/{p}/collections answered 200 with the full inventory - names,
document counts, sizes, kind - from a bogus Origin, while a document read
with that same Origin answered 403.

The cause is the shape this repo keeps paying for: the check lived in a
function the route does not call. requireCapability consults the allow-list;
the listing authorizes through requireProjectAccess plus the scope filter and
never reached it. A publishable key ships in the browser, so "any origin
holding the key" is effectively anyone, and it sat directly against the
reason a scope refusal is 403 rather than 404 - we deliberately stop a scoped
key discovering which collections exist outside its scope, while this route
handed over the whole list for free.

One requireAllowedOrigin() is now called by both routes rather than a second
copy, so they cannot drift apart again.

An ABSENT Origin is refused when a list is set, and that was left IDENTICAL
rather than softened for the listing. The reporter asked for the opposite -
refuse a present non-allowlisted Origin, never a missing one - and the reason
not to is that the defect being fixed WAS the listing behaving differently
from its siblings, so a gentler rule here would replace one inconsistency
with another. The constraint they were protecting against already applies to
document reads today: a key intended for server-side use must carry no
allow-list, because a non-browser client sends no Origin and can never
satisfy one. A test pins both routes to the same answer for an absent Origin,
which is the evidence for telling them so rather than asserting it.

4 tests. The pairing is that the allowlisted origin still gets 200 and a key
with no allow-list still lists from anywhere - without those, the refusal
test would pass against a listing that refused everyone. Falsified by
removing the gate, which turns two red. Suite 1336/1336 serially.

One trap worth noting: a braced-init-list Headers argument made
httplib::Client::Get ambiguous, the same overload-ambiguity shape CLAUDE.md
records for imapUidFetch. Name the type.
fszontagh 1 kuukausi sitten
vanhempi
sitoutus
1e8cffc294
6 muutettua tiedostoa jossa 133 lisäystä ja 4 poistoa
  1. 2 0
      CLAUDE.md
  2. 4 0
      api/llms.txt
  3. 6 0
      src/handlers/collections.cpp
  4. 16 4
      src/server.cpp
  5. 14 0
      src/server.hpp
  6. 91 0
      tests/test_api_integration.cpp

+ 2 - 0
CLAUDE.md

@@ -37,6 +37,8 @@ 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).
+    **AND TO THE ORIGIN ALLOW-LIST, FROM 0.15.0 - IT SKIPPED IT ENTIRELY BEFORE, AND THE REASON IS THE SHAPE THIS FILE KEEPS RECORDING: THE CHECK LIVED IN A FUNCTION THE ROUTE DOES NOT CALL.** `requireCapability` consults the allow-list; the listing authorizes through `requireProjectAccess` plus the scope filter and therefore never reached it. Measured by a consumer 2026-10-16 with their own publishable key: the listing answered **200 with the full inventory** (names, document counts, sizes, kind) from `Origin: https://evil.example.com`, while a document read with that same Origin answered 403. A publishable key ships in the browser, so "any origin holding the key" is effectively anyone - and it sat directly against the reason the scope refusal is 403 rather than 404, where we deliberately stop a scoped key discovering which collections exist outside its scope while this route handed over the whole list.
+    Now one `requireAllowedOrigin()` is called by both, so they cannot drift. **An ABSENT Origin is refused when a list is set** (`originAllowed("")` is false for a non-empty list), and that was left IDENTICAL on purpose rather than softened for the listing: the defect was the listing behaving differently from its siblings, and a second, gentler rule would have replaced one inconsistency with another. The consequence is worth telling consumers plainly - **a key meant for server-side use must carry no allow-list**, since a non-browser client sends no Origin and can never satisfy one. That was already true of document reads, so it is not a new constraint; a test now pins both routes to the same answer for an absent Origin, which is the evidence for saying so.
     **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.

+ 4 - 0
api/llms.txt

@@ -37,6 +37,10 @@ A non-admin key may carry a `scope` object that restricts what it can do. Scoped
 - `expires_at` (integer, default 0 = never) - Unix epoch seconds after which the key is treated as expired; auth returns 401.
 
 
+**The Origin allow-list now covers the collections LISTING too** (0.15.0+). It always covered document and vector operations; the listing authorized through the project grant plus the scope filter and never consulted the list, so a key with an allow-list could enumerate a project's collection names, document counts and sizes from ANY origin while being refused every document in them. That mattered because a browser-publishable key is, by definition, a key anyone can read. Now `GET /projects/{p}/collections` answers **403** `forbidden` for an origin outside the list, exactly as a document read does.
+- **A key with NO `origins` is unaffected** - an empty list means any origin, which is what a server-side key should use.
+- **An ABSENT `Origin` header is refused when a list IS set**, on the listing and on every other capability-checked route alike. This is long-standing behaviour rather than new, and it is why **a key intended for server-side use must not carry an allow-list at all**: a non-browser client sends no Origin, so it can never satisfy one. A test pins the two routes to the same answer so they cannot drift apart again.
+
 **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
 

+ 6 - 0
src/handlers/collections.cpp

@@ -89,6 +89,12 @@ void registerCollectionRoutes(ApiServer& s) {
         // the failure a listing prevents. Create, alter and drop stay behind a
         // full key below.
         requireProjectAccess(k, project);
+        // AND TO THE ORIGIN ALLOW-LIST, which this route used to skip entirely
+        // because it authorizes through requireProjectAccess rather than
+        // requireCapability. A publishable key ships in the browser, so any
+        // origin holding it could enumerate the whole project inventory while
+        // being refused every document in it.
+        requireAllowedOrigin(k, req);
 
         // AND THE LISTING ANSWERS TO THE SCOPE RULES, not merely to the
         // project grant. Project access alone let a key granted exactly ONE

+ 16 - 4
src/server.cpp

@@ -80,6 +80,21 @@ void requireProjectManage(const ApiKey& k, const std::string& project) {
         throw ApiError(ErrCode::Forbidden, "forbidden", "scoped keys cannot manage collections");
 }
 
+void requireAllowedOrigin(const ApiKey& k, const httplib::Request& req) {
+    if (!k.scope) return;  // legacy full-access key: no allow-list to enforce
+    std::string origin;
+    if (auto it = req.headers.find("Origin"); it != req.headers.end()) origin = it->second;
+    // NOTE an ABSENT Origin is refused when a list is set, because
+    // originAllowed("") is false for a non-empty list. That is pre-existing
+    // behaviour on every capability-checked route, not something this gate
+    // introduced, and it is why a key meant for server-side use must not
+    // carry an allow-list at all. Kept identical here deliberately: the bug
+    // being fixed was the listing behaving DIFFERENTLY from its siblings, so
+    // a second, softer rule here would replace one inconsistency with another.
+    if (!k.scope->originAllowed(origin))
+        throw ApiError(ErrCode::Forbidden, "forbidden", "origin not allowed for this key");
+}
+
 void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& req,
                        const std::string& project, const std::string& collection, KeyOp op) {
     // Grant, rule and rate limit are the caller-agnostic part.
@@ -87,10 +102,7 @@ void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& r
     if (!k.scope) return;                                   // legacy full-access key
     const KeyScope& sc = *k.scope;
     const KeyScopeRule* rule = sc.findRule(collection, op);  // re-read for requireHumanToken
-    std::string origin;
-    if (auto it = req.headers.find("Origin"); it != req.headers.end()) origin = it->second;
-    if (!sc.originAllowed(origin))
-        throw ApiError(ErrCode::Forbidden, "forbidden", "origin not allowed for this key");
+    requireAllowedOrigin(k, req);
     if (rule->requireHumanToken) {
         std::string token;
         if (auto it = req.headers.find("X-Captcha-Token"); it != req.headers.end()) token = it->second;

+ 14 - 0
src/server.hpp

@@ -59,6 +59,20 @@ std::optional<ApiKey> resolveKey(ServerDeps& d, const httplib::Request& req);
 ApiKey requireKey(ServerDeps& d, const httplib::Request& req);              // throws Unauthorized
 void   requireAdmin(const ApiKey& k);                                      // throws Forbidden
 void   requireProjectAccess(const ApiKey& k, const std::string& project);  // throws Forbidden
+/// Enforce a scoped key's Origin allow-list.
+///
+/// ONE implementation, so a route that consults the allow-list cannot drift
+/// from the rest. It was two behaviours by accident: `requireCapability`
+/// checked the list and the collections LISTING, which authorizes through
+/// `requireProjectAccess` plus the scope filter, never reached it - so a
+/// publishable key (which ships in the browser, so effectively anyone) could
+/// enumerate every collection in a project from any origin, with names,
+/// document counts and sizes, while being refused a single document from any
+/// of them. Measured by a consumer 2026-10-16.
+///
+/// A key with no allow-list is unaffected: an empty list means any origin.
+void requireAllowedOrigin(const ApiKey& k, const httplib::Request& req);
+
 // Like requireProjectAccess, but additionally denies capability-scoped keys —
 // collection/project management is not expressible in a key scope, so a scoped
 // (publishable) key must never reach these routes.

+ 91 - 0
tests/test_api_integration.cpp

@@ -4605,3 +4605,94 @@ TEST_F(ApiFixture, AScopeRefusalNamesTheCollectionTheOpAndWhatTheKeyHolds) {
     ASSERT_EQ(body["error"]["details"]["granted"].size(), 1u);
     EXPECT_EQ(body["error"]["details"]["granted"][0]["collection"], "designs");
 }
+
+// ─── The listing answers to the Origin allow-list too (task #87) ──────────
+//
+// Found by a consumer measuring their own publishable key: the listing
+// answered 200 from a bogus Origin while a document read from that same
+// Origin answered 403. A publishable key ships in the browser, so any origin
+// holding it could enumerate the project inventory - names, document counts,
+// sizes - while being refused every document in it.
+TEST_F(ApiFixture, TheCollectionsListingAnswersToTheOriginAllowList) {
+    ASSERT_EQ(admin().Post(("/api/v1/projects/" + project_ + "/collections").c_str(),
+                           nlohmann::json{{"name", "designs"}, {"kind", "json"}}.dump(),
+                           "application/json")->status, 201);
+
+    auto mk = admin().Post("/api/v1/keys",
+        nlohmann::json{{"label", "publishable"}, {"projects", {project_}}, {"admin", false},
+                       {"scope", {{"origins", {"https://good.example.com"}},
+                                  {"rules", {{{"collection", "*"}, {"ops", {"read", "list"}}}}}}}}
+            .dump(), "application/json");
+    ASSERT_EQ(mk->status, 201) << mk->body;
+    const std::string pub = nlohmann::json::parse(mk->body)["key"];
+
+    const std::string listing = "/api/v1/projects/" + project_ + "/collections";
+    auto get = [&](const char* origin) {
+        httplib::Client c("127.0.0.1", port_);
+        httplib::Headers h{{"Authorization", "Bearer " + pub}};
+        if (origin) h.emplace("Origin", origin);
+        return c.Get(listing.c_str(), h);
+    };
+
+    auto bogus = get("https://evil.example.com");
+    ASSERT_TRUE(bogus);
+    EXPECT_EQ(bogus->status, 403) << "a non-allowlisted origin must not enumerate the "
+                                     "project inventory: " << bogus->body;
+
+    // The pairing: the gate is selective, not blanket. Without this the test
+    // above would pass against a listing that refused everyone, which would
+    // break every legitimate browser caller.
+    auto good = get("https://good.example.com");
+    ASSERT_TRUE(good);
+    EXPECT_EQ(good->status, 200) << "the allowlisted origin must still work: " << good->body;
+    EXPECT_TRUE(nlohmann::json::parse(good->body).contains("collections")) << good->body;
+}
+
+// The behaviour a consumer explicitly asked about, pinned because I am telling
+// them it is pre-existing rather than introduced: an ABSENT Origin is refused
+// when an allow-list is set, and it is refused IDENTICALLY on the listing and
+// on a document read. So a key intended for server-side use must carry no
+// allow-list - which was already true before the listing was gated.
+TEST_F(ApiFixture, AnAbsentOriginIsRefusedTheSameWayOnBothRoutes) {
+    ASSERT_EQ(admin().Post(("/api/v1/projects/" + project_ + "/collections").c_str(),
+                           nlohmann::json{{"name", "designs"}, {"kind", "json"}}.dump(),
+                           "application/json")->status, 201);
+    auto mk = admin().Post("/api/v1/keys",
+        nlohmann::json{{"label", "pinned"}, {"projects", {project_}}, {"admin", false},
+                       {"scope", {{"origins", {"https://good.example.com"}},
+                                  {"rules", {{{"collection", "*"}, {"ops", {"read", "list"}}}}}}}}
+            .dump(), "application/json");
+    ASSERT_EQ(mk->status, 201) << mk->body;
+    const std::string pub = nlohmann::json::parse(mk->body)["key"];
+
+    httplib::Client c("127.0.0.1", port_);
+    const httplib::Headers noOrigin{{"Authorization", "Bearer " + pub}};
+    auto listing = c.Get(("/api/v1/projects/" + project_ + "/collections").c_str(), noOrigin);
+    auto document = c.Get(
+        ("/api/v1/projects/" + project_ + "/collections/designs/documents?limit=1").c_str(),
+        noOrigin);
+    ASSERT_TRUE(listing);
+    ASSERT_TRUE(document);
+    EXPECT_EQ(listing->status, document->status)
+        << "the two routes must agree about an absent Origin; listing=" << listing->body
+        << " document=" << document->body;
+    EXPECT_EQ(listing->status, 403);
+}
+
+// And a key with NO allow-list is untouched by any of this: an empty list
+// means any origin, which is what every server-side key uses.
+TEST_F(ApiFixture, AKeyWithNoOriginAllowListStillListsFromAnywhere) {
+    auto mk = admin().Post("/api/v1/keys",
+        nlohmann::json{{"label", "serverside"}, {"projects", {project_}}, {"admin", false},
+                       {"scope", {{"rules", {{{"collection", "*"}, {"ops", {"read", "list"}}}}}}}}
+            .dump(), "application/json");
+    ASSERT_EQ(mk->status, 201) << mk->body;
+    const std::string key = nlohmann::json::parse(mk->body)["key"];
+
+    httplib::Client c("127.0.0.1", port_);
+    const httplib::Headers headers{{"Authorization", "Bearer " + key},
+                                   {"Origin", "https://anywhere.example.com"}};
+    auto res = c.Get(("/api/v1/projects/" + project_ + "/collections").c_str(), headers);
+    ASSERT_TRUE(res);
+    EXPECT_EQ(res->status, 200) << "an empty allow-list means ANY origin: " << res->body;
+}