浏览代码

fix: PUT accepted ?ttl_seconds= and stored a PERMANENT row with a 201

Reported by the justice-pa consumer, measured on prod. They PUT a row with
?ttl_seconds=3600, got 201, and read it back with no _expires_at at all. The
reference did say PUT does not take the parameter, so this was not a doc gap -
the shape is what made it expensive.

Their framing is the reason this is a defect and not an ergonomic wish: the
feature they were building existed to stop a restore recreating an IMMORTAL
at-most-once marker, so the silent drop produced precisely the bug it was
written to prevent, and the restore reported success either way. Only a
read-back caught it.

It cannot be fixed by honouring the parameter: the client's update path takes
no ttlSeconds (only insert, upsert and patchWithTtl do), and honouring it on
the create half of this upsert while dropping it on the replace half would be
worse than either - a parameter that works until the row exists. So it is
refused, via the existing requireHonourableParams idiom, scoped to
ttl_seconds rather than blanket: a query string legitimately carries a
cache-buster, and refusing `_=1760000000` would be a regression while refusing
ttl_seconds is the point. POST and PATCH both genuinely honour it, which is
what makes a caller reaching for it here non-hypothetical.

Blast radius measured before changing a 201 into a 422: exactly ONE PUT with
ttl_seconds in the entire prod access log, which is their probe today, and zero
on PATCH.

Three tests, and both mutations were checked rather than assumed:
- the refusal names the parameter, points at POST and PATCH, and asserts
  NOTHING WAS STORED - a 422 that still wrote the row would leave the very
  permanent document this prevents
- the pairing asserts an ordinary PUT, a cache-buster and if_version all still
  pass, which is the only thing proving the refusal is selective
- a third asserts POST and PATCH still honour ttl_seconds, so the fix cannot be
  confused with having broken the TTL feature everywhere

Mutation A, pointing the candidate list at a different name: the refusal test
goes red, both pairings stay green. Mutation B, making it blanket by adding `_`
and if_version: the pairing goes red, the refusal stays green. 1349/1349 pass
restored.

Ships in the next release, not 0.16.0 - that version is published.
fszontagh 1 月之前
父节点
当前提交
2ca1d3c932
共有 3 个文件被更改,包括 115 次插入 和 1 次删除
  1. 1 1
      api/llms.txt
  2. 31 0
      src/handlers/documents.cpp
  3. 83 0
      tests/test_api_integration.cpp

+ 1 - 1
api/llms.txt

@@ -114,7 +114,7 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
 
   **FILTERING on `_expires_at` (`lt`, `exists`) needs a database SERVER at 2.19.0 or newer**, unlike reading it, which needs only the client we ship. On an older server the field still comes back on reads and a filter naming it simply matches nothing useful. A row with no expiry is ABSENT for those filters rather than zero, so an upper bound cannot sweep up permanent rows.
   **FILTERING on `_expires_at` (`lt`, `exists`) needs a database SERVER at 2.19.0 or newer**, unlike reading it, which needs only the client we ship. On an older server the field still comes back on reads and a filter naming it simply matches nothing useful. A row with no expiry is ABSENT for those filters rather than zero, so an upper bound cannot sweep up permanent rows.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID. The body is the stored document **plus the database's read-only metadata**: `_id`, `_version` (an integer, starting at 1 and incremented by every write), `_created_at`, `_updated_at` (epoch ms), `_created_by`, `_updated_by`. `_version` is the value `?if_version=` takes, and it is also returned as an `ETag` header. These names are reserved: a field of your own called `_version` cannot be stored or read back.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID. The body is the stored document **plus the database's read-only metadata**: `_id`, `_version` (an integer, starting at 1 and incremented by every write), `_created_at`, `_updated_at` (epoch ms), `_created_by`, `_updated_by`. `_version` is the value `?if_version=` takes, and it is also returned as an `ETag` header. These names are reserved: a field of your own called `_version` cannot be stored or read back.
-- `PUT   /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace the document at `{id}`, **creating it when it does not exist** (a real upsert, as the method means). Accepts the same two body shapes as POST. **201** `{id, created:true, version:1}` with a `Location` header when it created, **200** `{id, created:false, version:N}` when it replaced. A replace is not a merge: fields the body omits are dropped. Creating counts as an insert for authorization, so a capability-scoped key granted `update` but not `insert` on the collection gets **403** on a PUT to an id that does not exist yet and can only replace. PUT does not take `?ttl_seconds=`; use POST with an `id` to create with an expiry.
+- `PUT   /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace the document at `{id}`, **creating it when it does not exist** (a real upsert, as the method means). Accepts the same two body shapes as POST. **201** `{id, created:true, version:1}` with a `Location` header when it created, **200** `{id, created:false, version:N}` when it replaced. A replace is not a merge: fields the body omits are dropped. Creating counts as an insert for authorization, so a capability-scoped key granted `update` but not `insert` on the collection gets **403** on a PUT to an id that does not exist yet and can only replace. **PUT REFUSES `?ttl_seconds=` with 422 `unknown_option` rather than ignoring it** (previously it answered 201 and stored a PERMANENT row). The parameter cannot be honoured here at all - the database's update path takes no TTL - and honouring it on the create half of this upsert while dropping it on the replace half would be worse than either, since it would work only until the row existed. `details.unsupported` names it. **To create a row with an expiry, POST with an `id`; to set or clear one on a row that already exists, PATCH with `?ttl_seconds=`.** This was a consumer's measured defect and is worth knowing why it mattered: a silent drop stored a permanent row where the caller had asked for a 1-hour one, their write returned 201, and the feature they were building existed precisely to stop a restore recreating an immortal at-most-once marker - so the drop produced exactly the bug the feature was written to prevent, and nothing but a read-back could see it.
 - `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (RFC 7396 merge: a `null` removes a field); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. Returns `{id, version}`. **404** when the document does not exist - unlike PUT, PATCH never creates, because merging fields into nothing has no defined result and a patch body is not a whole document. Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
 - `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (RFC 7396 merge: a `null` removes a field); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. Returns `{id, version}`. **404** when the document does not exist - unlike PUT, PATCH never creates, because merging fields into nothing has no defined result and a patch body is not a whole document. Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
 
 
   **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` (**422** `conditional_unsupported`): the version-checked write has no expiry field, and silently dropping one of the two would be worse than refusing. It IS available on a `kind=vector` collection - a conditional PATCH is a server-side MERGE and preserves the stored embedding (measured). What is refused there is a whole-document **replace**: see `PUT` below.
   **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` (**422** `conditional_unsupported`): the version-checked write has no expiry field, and silently dropping one of the two would be worse than refusing. It IS available on a `kind=vector` collection - a conditional PATCH is a server-side MERGE and preserves the stored embedding (measured). What is refused there is a whole-document **replace**: see `PUT` below.

+ 31 - 0
src/handlers/documents.cpp

@@ -286,6 +286,37 @@ void registerDocumentRoutes(ApiServer& s) {
     svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
     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);
         Target t = scoped(d, req, 1, 2, KeyOp::Update);
         std::string id = req.matches[3];
         std::string id = req.matches[3];
+
+        // REFUSE `?ttl_seconds=` HERE, because this route CANNOT honour it and
+        // was answering 201 as though it had.
+        //
+        // Reported by a consumer 2026-10-22, and the cost is the reason this
+        // is a defect rather than an ergonomic wish: they PUT a row with
+        // `?ttl_seconds=3600`, got a **201**, and read it back with no
+        // `_expires_at` at all - i.e. PERMANENT. The whole point of their
+        // change was to stop a restore recreating an immortal at-most-once
+        // marker, so the silent drop produced exactly the bug the feature
+        // existed to prevent, and their restore reported success either way.
+        // Only a read-back caught it.
+        //
+        // It cannot be repaired by honouring it instead: the database client's
+        // update path takes NO ttlSeconds (only insert, upsert and
+        // `patchWithTtl` do), so a replace has nowhere to put an expiry. And
+        // honouring it on the create half of this route while dropping it on
+        // the replace half would be worse than either - a parameter that works
+        // until the row exists.
+        //
+        // Scoped to `ttl_seconds` deliberately rather than refusing every
+        // unknown parameter: a query string legitimately carries a
+        // cache-buster or a proxy's addition, and this route's siblings POST
+        // and PATCH both DO honour `ttl_seconds`, which is what makes a caller
+        // reaching for it here non-hypothetical rather than invented.
+        requireHonourableParams(
+            req, {{"ttl_seconds"}}, {"if_version"},
+            "a whole-document replace cannot carry an expiry - the database's update path takes "
+            "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");
+
         const auto ifVersion = ifVersionParam(req);
         const auto ifVersion = ifVersionParam(req);
         nlohmann::json data = documentBody(bodyJson(req));
         nlohmann::json data = documentBody(bodyJson(req));
 
 

+ 83 - 0
tests/test_api_integration.cpp

@@ -1083,6 +1083,89 @@ TEST_F(ApiFixture, DocumentTtlAcceptedOnInsertAndPatch) {
     EXPECT_EQ(nlohmann::json::parse(got->body)["v"], 2);
     EXPECT_EQ(nlohmann::json::parse(got->body)["v"], 2);
 }
 }
 
 
+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
+    // recreating an immortal at-most-once marker, so the silent drop produced
+    // precisely the bug it was written to prevent - and the restore reported
+    // success either way.
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","ttlput"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    std::string docs = base + "/ttlput/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);
+    const auto err = nlohmann::json::parse(refused->body)["error"];
+    EXPECT_EQ(err.value("code", ""), "unknown_option");
+    // Names the parameter, so the caller does not have to guess which one.
+    ASSERT_TRUE(err.contains("details"));
+    const auto unsup = err["details"]["unsupported"];
+    ASSERT_TRUE(unsup.is_array());
+    EXPECT_EQ(unsup.size(), 1u);
+    EXPECT_EQ(unsup[0], "ttl_seconds");
+    // And points at the routes that CAN carry an expiry.
+    const std::string msg = err.value("message", "");
+    EXPECT_NE(msg.find("POST"), std::string::npos) << msg;
+    EXPECT_NE(msg.find("PATCH"), std::string::npos) << msg;
+
+    // THE REFUSAL MUST NOT HAVE STORED ANYTHING. A 422 that still wrote the
+    // row would leave exactly the permanent document this refusal exists to
+    // prevent, which is the failure the consumer actually met.
+    EXPECT_EQ(c.Get((docs + "/row1").c_str())->status, 404);
+}
+
+TEST_F(ApiFixture, PutWithoutTtlSecondsStillWorksAndAnIncidentalParamIsNotRefused) {
+    // The PAIRING, and the only thing that proves the refusal is SELECTIVE
+    // rather than a blanket break of PUT. Without it the test above would pass
+    // just as well against a route that refused everything.
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","ttlput2"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    std::string docs = base + "/ttlput2/documents";
+
+    // An ordinary PUT is untouched.
+    auto ok = c.Put((docs + "/row1").c_str(), nlohmann::json{{"v",1}}.dump(), "application/json");
+    ASSERT_TRUE(ok); EXPECT_TRUE(ok->status == 200 || ok->status == 201) << ok->status;
+
+    // A cache-buster is NOT an option anybody is asking us to honour, so it
+    // must still pass - refusing `ttl_seconds` is the point, refusing `_=...`
+    // would be a regression.
+    auto bust = c.Put((docs + "/row2?_=1760000000").c_str(),
+                      nlohmann::json{{"v",2}}.dump(), "application/json");
+    ASSERT_TRUE(bust); EXPECT_TRUE(bust->status == 200 || bust->status == 201) << bust->status;
+
+    // `if_version` is a real PUT parameter and must not be swept up either.
+    auto ver = c.Put((docs + "/row2?if_version=1").c_str(),
+                     nlohmann::json{{"v",3}}.dump(), "application/json");
+    ASSERT_TRUE(ver); EXPECT_NE(ver->status, 422) << ver->status;
+}
+
+TEST_F(ApiFixture, TheSiblingRoutesThatDoHonourTtlSecondsAreUnaffected) {
+    // The second half of the pairing: POST and PATCH both genuinely honour
+    // `ttl_seconds`, and this fix must not have touched them. If it had, the
+    // refusal above would be indistinguishable from having broken the TTL
+    // feature everywhere.
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","ttlsib"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    std::string docs = base + "/ttlsib/documents";
+
+    auto made = c.Post((docs + "?ttl_seconds=3600").c_str(),
+                       nlohmann::json{{"v",1}}.dump(), "application/json");
+    ASSERT_TRUE(made); EXPECT_EQ(made->status, 201);
+    const std::string id = nlohmann::json::parse(made->body)["id"];
+
+    auto patched = c.Patch((docs + "/" + id + "?ttl_seconds=7200").c_str(),
+                           nlohmann::json{{"v",2}}.dump(), "application/json");
+    ASSERT_TRUE(patched); EXPECT_EQ(patched->status, 200);
+}
+
 TEST_F(ApiFixture, DocumentTtlRejectsNonNumeric) {
 TEST_F(ApiFixture, DocumentTtlRejectsNonNumeric) {
     auto c = admin();
     auto c = admin();
     std::string base = "/api/v1/projects/" + project_ + "/collections";
     std::string base = "/api/v1/projects/" + project_ + "/collections";