Skip to content

Commit aa06ea7

Browse files
taplinclaude
andcommitted
Reject invalid legacy queries; pass count options through; reject multi replace
_perfect_split_legacy_query treated a $query that isn't a document as an empty filter, so find() and count() matched every document. It also merged non-$ fields next to $query into the filter. libmongoc 1.x's legacy find rejected both ("Cannot mix $query with non-dollar field", "Invalid BSON in $query subdocument"), and now the shim does too: count() returns the error, find() returns nil (libmongoc 2 can't hand back a cursor carrying the error, and MongoCursor exposes no error), and GridFS list(filter:) throws. A duplicate $query now means the last one wins, as in 1.x; before, the two were merged. (1.x's legacy count never unwrapped $query at all; current servers reject a raw $query in count.) _perfect_collection_count built the legacy find options and threw them away. hint, maxTimeMS, comment and collation now reach count_documents. $orderby, $max, $min and the other find-only modifiers are still ignored, and the doc comment says so. A negative legacy limit is passed as its absolute value, as the old count command treated it; before, the $limit stage rejected it. INT64_MIN, which has no absolute value, is an error. The doc comment also notes that count() can't use $where, $near or $nearSphere, since count_documents runs the query as a $match. update() with .multiUpdate and a replacement document replaced one document and reported success. It now returns an error without writing, with the server's own message for this case ("multi update is not supported for replacement-style update"; the server's code is 9, this is a client-side MONGOC_ERROR_COMMAND_INVALID_ARG). Tests: 4 new tests. 14 of their checks fail on main (the rest are baseline checks that pass either way). The comment check uses the profiler in a database of its own, which it drops, and skips when the server refuses profiling. All 40 tests pass against mongod 8.3.11 on macOS (debug and release) and on Linux (Scripts/test-linux.sh). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent cf6120f commit aa06ea7

3 files changed

Lines changed: 181 additions & 23 deletions

File tree

‎Sources/PerfectCMongo/shim.h‎

Lines changed: 71 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include <mongoc/mongoc.h>
2+
#include <stdlib.h>
23
#include <string.h>
34

45
static bool _mongoc_cursor_next(mongoc_cursor_t *cursor, const void **bson)
@@ -16,40 +17,51 @@ static bool _mongoc_cursor_next(mongoc_cursor_t *cursor, const void **bson)
1617
// Split a legacy query document into a filter and find options.
1718
// { $query: {...}, $orderby: {...}, $hint: ... } becomes filter {...} and opts { sort: {...}, hint: ... }.
1819
// A query without $query is copied into filter unchanged.
19-
static void _perfect_split_legacy_query(const bson_t *query, bson_t *filter, bson_t *opts)
20+
// Like libmongoc 1.x, a $query that isn't a document, or a non-$ field next to $query, is an error.
21+
static bool _perfect_split_legacy_query(const bson_t *query, bson_t *filter, bson_t *opts, bson_error_t *error)
2022
{
2123
bson_iter_t iter;
2224
if (!query || !bson_iter_init_find(&iter, query, "$query")) {
2325
if (query) {
2426
bson_concat(filter, query);
2527
}
26-
return;
28+
return true;
2729
}
2830
bson_iter_init(&iter, query);
2931
while (bson_iter_next(&iter)) {
3032
const char *key = bson_iter_key(&iter);
33+
if (key[0] != '$') {
34+
bson_set_error(error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR,
35+
"Cannot mix $query with non-dollar field '%s'", key);
36+
return false;
37+
}
3138
if (strcmp(key, "$query") == 0) {
32-
if (BSON_ITER_HOLDS_DOCUMENT(&iter)) {
33-
uint32_t len = 0;
34-
const uint8_t *data = NULL;
35-
bson_t sub;
36-
bson_iter_document(&iter, &len, &data);
37-
if (bson_init_static(&sub, data, len)) {
38-
bson_concat(filter, &sub);
39-
}
39+
uint32_t len = 0;
40+
const uint8_t *data = NULL;
41+
bson_t sub;
42+
if (!BSON_ITER_HOLDS_DOCUMENT(&iter)) {
43+
bson_set_error(error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "$query must be a document");
44+
return false;
45+
}
46+
bson_iter_document(&iter, &len, &data);
47+
if (!bson_init_static(&sub, data, len)) {
48+
bson_set_error(error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid BSON in $query subdocument");
49+
return false;
4050
}
51+
// As in libmongoc 1.x, the last $query wins.
52+
bson_reinit(filter);
53+
bson_concat(filter, &sub);
4154
} else if (strcmp(key, "$orderby") == 0) {
4255
bson_append_iter(opts, "sort", -1, &iter);
4356
} else if (strcmp(key, "$showDiskLoc") == 0) {
4457
bson_append_iter(opts, "showRecordId", -1, &iter);
4558
} else if (strcmp(key, "$explain") == 0 || strcmp(key, "$snapshot") == 0) {
4659
// no longer supported by the server
47-
} else if (key[0] == '$') {
48-
bson_append_iter(opts, key + 1, -1, &iter);
4960
} else {
50-
bson_append_iter(filter, key, -1, &iter);
61+
bson_append_iter(opts, key + 1, -1, &iter);
5162
}
5263
}
64+
return true;
5365
}
5466

5567
// Convert legacy query flags to find options. Returns true when MONGOC_QUERY_SECONDARY_OK is set.
@@ -88,8 +100,15 @@ static mongoc_cursor_t *_perfect_collection_find(mongoc_collection_t *collection
88100
bson_t opts = BSON_INITIALIZER;
89101
mongoc_read_prefs_t *prefs = NULL;
90102
mongoc_cursor_t *cursor;
103+
bson_error_t error;
91104

92-
_perfect_split_legacy_query(query, &filter, &opts);
105+
// libmongoc 2.x can't hand back a cursor that carries this error, so an invalid legacy query
106+
// returns NULL (find() returns nil).
107+
if (!_perfect_split_legacy_query(query, &filter, &opts, &error)) {
108+
bson_destroy(&filter);
109+
bson_destroy(&opts);
110+
return NULL;
111+
}
93112
if (_perfect_flags_to_opts(flags, &opts)) {
94113
prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY_PREFERRED);
95114
}
@@ -114,30 +133,51 @@ static mongoc_cursor_t *_perfect_collection_find(mongoc_collection_t *collection
114133
return cursor;
115134
}
116135

136+
// Legacy count on top of count_documents, which runs { $match: filter } in an aggregate.
137+
// From the legacy query only hint, maxTimeMS, comment and collation carry over; $orderby, $max,
138+
// $min, $returnKey, $showDiskLoc and the other find-only options are ignored. Because the filter is a $match, it can't use
139+
// $where, $near or $nearSphere (the server rejects them); use $expr, $geoWithin with $center,
140+
// or $geoWithin with $centerSphere instead.
117141
static int64_t _perfect_collection_count(mongoc_collection_t *collection,
118142
mongoc_query_flags_t flags,
119143
const bson_t *query,
120144
int64_t skip,
121145
int64_t limit,
122146
bson_error_t *error)
123147
{
148+
static const char *const passed_opts[] = { "hint", "maxTimeMS", "comment", "collation" };
124149
bson_t filter = BSON_INITIALIZER;
125150
bson_t find_opts = BSON_INITIALIZER;
126151
bson_t opts = BSON_INITIALIZER;
127152
mongoc_read_prefs_t *prefs = NULL;
128-
int64_t count;
153+
bson_iter_t iter;
154+
size_t i;
155+
int64_t count = -1;
129156

130-
_perfect_split_legacy_query(query, &filter, &find_opts);
157+
if (!_perfect_split_legacy_query(query, &filter, &find_opts, error)) {
158+
goto done;
159+
}
131160
if (_perfect_flags_to_opts(flags, &find_opts)) {
132161
prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY_PREFERRED);
133162
}
163+
for (i = 0; i < sizeof(passed_opts) / sizeof(passed_opts[0]); i++) {
164+
if (bson_iter_init_find(&iter, &find_opts, passed_opts[i])) {
165+
bson_append_iter(&opts, passed_opts[i], -1, &iter);
166+
}
167+
}
134168
if (skip) {
135169
BSON_APPEND_INT64(&opts, "skip", skip);
136170
}
171+
// The legacy count command treated a negative limit like a positive one.
172+
if (limit == INT64_MIN) {
173+
bson_set_error(error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "limit cannot be INT64_MIN");
174+
goto done;
175+
}
137176
if (limit) {
138-
BSON_APPEND_INT64(&opts, "limit", limit);
177+
BSON_APPEND_INT64(&opts, "limit", llabs(limit));
139178
}
140179
count = mongoc_collection_count_documents(collection, &filter, &opts, prefs, NULL, error);
180+
done:
141181
if (prefs) {
142182
mongoc_read_prefs_destroy(prefs);
143183
}
@@ -151,10 +191,12 @@ static mongoc_gridfs_file_list_t *_perfect_gridfs_find(mongoc_gridfs_t *gridfs,
151191
{
152192
bson_t filter = BSON_INITIALIZER;
153193
bson_t opts = BSON_INITIALIZER;
154-
mongoc_gridfs_file_list_t *list;
194+
mongoc_gridfs_file_list_t *list = NULL;
195+
bson_error_t error;
155196

156-
_perfect_split_legacy_query(query, &filter, &opts);
157-
list = mongoc_gridfs_find_with_opts(gridfs, &filter, &opts);
197+
if (_perfect_split_legacy_query(query, &filter, &opts, &error)) {
198+
list = mongoc_gridfs_find_with_opts(gridfs, &filter, &opts);
199+
}
158200
bson_destroy(&filter);
159201
bson_destroy(&opts);
160202
return list;
@@ -185,22 +227,30 @@ static bool _perfect_collection_insert(mongoc_collection_t *collection,
185227
}
186228

187229
// Legacy update accepted either an update-operator document or a replacement document.
230+
// A replacement document can only replace one document, so MULTI_UPDATE with one is an error,
231+
// as the server reported it for the legacy update.
188232
static bool _perfect_collection_update(mongoc_collection_t *collection,
189233
mongoc_update_flags_t flags,
190234
const bson_t *selector,
191235
const bson_t *update,
192236
bson_error_t *error)
193237
{
194238
bson_t opts = BSON_INITIALIZER;
239+
bool replacement = !_perfect_is_update_document(update);
195240
bool ret;
196241

242+
if (replacement && (flags & MONGOC_UPDATE_MULTI_UPDATE)) {
243+
bson_set_error(error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG,
244+
"multi update is not supported for replacement-style update");
245+
return false;
246+
}
197247
if (flags & MONGOC_UPDATE_UPSERT) {
198248
BSON_APPEND_BOOL(&opts, "upsert", true);
199249
}
200250
if (flags & MONGOC_UPDATE_NO_VALIDATE) {
201251
BSON_APPEND_BOOL(&opts, "validate", false);
202252
}
203-
if (!_perfect_is_update_document(update)) {
253+
if (replacement) {
204254
ret = mongoc_collection_replace_one(collection, selector, update, &opts, NULL, error);
205255
} else if (flags & MONGOC_UPDATE_MULTI_UPDATE) {
206256
ret = mongoc_collection_update_many(collection, selector, update, &opts, NULL, error);

‎Sources/PerfectMongoDB/MongoCollection.swift‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@ public class MongoCollection {
322322
*
323323
* - parameter selector: BSON document with selection criteria
324324
* - parameter update: BSON document to be used to update
325-
* - parameter flag: Optional MongoUpdateFlag defaults to .None
325+
* - parameter flag: Optional MongoUpdateFlag defaults to .None. `.multiUpdate` needs an update-operator document such as `{ $set: ... }`; with a replacement document it returns an error.
326326
*
327327
* - returns: Result object with status of update
328328
*/
@@ -555,7 +555,7 @@ public class MongoCollection {
555555
* - parameter limit: Optional. return no more than the supplied number of records.
556556
* - parameter batchSize: Optional. Change number of automatically iterated documents.
557557
*
558-
* - returns: A cursor to the documents that match the query criteria. When the find() method “returns documents,” the method is actually returning a cursor to the documents.
558+
* - returns: A cursor to the documents that match the query criteria. When the find() method “returns documents,” the method is actually returning a cursor to the documents. nil when a legacy `$query` query is invalid: `$query` isn't a document, or it's mixed with fields that don't start with `$`.
559559
*/
560560
public func find(query: BSON = BSON(), fields: BSON? = nil, flags: MongoQueryFlag = MongoQueryFlag.none, skip: Int = 0, limit: Int = 0, batchSize: Int = 0) -> MongoCursor? {
561561
// @available(*, deprecated, message: "Use find(filter: BSON, options: BSON?)")
@@ -672,6 +672,8 @@ public class MongoCollection {
672672
* - parameter batchSize: Optional. Change number of automatically iterated documents.
673673
*
674674
* - returns: the count of documents that would match a find() query. The count() method does not perform the find() operation but instead counts and returns the number of results that match a query.
675+
*
676+
* The count runs as an aggregate `$match`, so the query can't use `$where`, `$near` or `$nearSphere`; use `$expr`, or `$geoWithin` with `$center` / `$centerSphere`. In a legacy `$query` query, `$hint`, `$maxTimeMS`, `$comment` and `$collation` apply to the count; other modifiers such as `$orderby`, `$max` and `$min` are ignored. A negative `limit` counts like a positive one.
675677
*/
676678
public func count(query: BSON, flags: MongoQueryFlag = MongoQueryFlag.none, skip: Int = 0, limit: Int = 0, batchSize: Int = 0) -> Result {
677679
guard let ptr = self.ptr else {

‎Tests/PerfectMongoDBTests/PerfectMongoDBTests.swift‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -988,6 +988,112 @@ class PerfectMongoDBTests: XCTestCase {
988988
XCTAssertEqual(count(collection), 0)
989989
}
990990

991+
private func assertCountFails(_ collection: MongoCollection, _ json: String, containing text: String? = nil, file: StaticString = #filePath, line: UInt = #line) {
992+
switch collection.count(query: try! BSON(json: json)) {
993+
case .error(_, _, let message):
994+
if let text {
995+
XCTAssert(message.contains(text), message, file: file, line: line)
996+
}
997+
case let other:
998+
XCTFail("count(\(json)) should fail, got \(other)", file: file, line: line)
999+
}
1000+
}
1001+
1002+
func testInvalidLegacyQueriesAreRejected() {
1003+
let (client, collection) = freshCollection("testinvalidlegacy")
1004+
defer { withExtendedLifetime(client) {} }
1005+
defer { _ = collection.drop() }
1006+
1007+
// A $query that isn't a document used to match every document.
1008+
let notDocument = "{\"$query\": 5}"
1009+
XCTAssertNil(collection.find(query: try! BSON(json: notDocument)))
1010+
assertCountFails(collection, notDocument, containing: "$query must be a document")
1011+
1012+
// A non-$ field next to $query used to be merged into the filter.
1013+
let mixed = "{\"$query\": {\"a\": 1}, \"b\": \"value 1\"}"
1014+
XCTAssertNil(collection.find(query: try! BSON(json: mixed)))
1015+
assertCountFails(collection, mixed, containing: "Cannot mix $query with non-dollar field 'b'")
1016+
1017+
let gridfs = try! client.gridFS(database: "test")
1018+
defer { gridfs.close() }
1019+
XCTAssertThrowsError(try gridfs.list(filter: try! BSON(json: notDocument)))
1020+
1021+
// Well-formed legacy queries still work.
1022+
let valid = "{\"$query\": {\"a\": {\"$gte\": 2}}, \"$orderby\": {\"a\": 1}}"
1023+
XCTAssertEqual(collection.find(query: try! BSON(json: valid))?.map { $0 }.count, 2)
1024+
XCTAssertEqual(count(collection, valid), 2)
1025+
}
1026+
1027+
func testLegacyCountOptions() {
1028+
let (client, collection) = freshCollection("testlegacycount")
1029+
defer { withExtendedLifetime(client) {} }
1030+
defer { _ = collection.drop() }
1031+
1032+
// A negative legacy limit counts like a positive one.
1033+
if case .replyInt(let limited) = collection.count(query: BSON(), limit: -2) {
1034+
XCTAssertEqual(limited, 2)
1035+
} else {
1036+
XCTFail("count with a negative limit failed")
1037+
}
1038+
1039+
// hint reaches the server: an unknown index is an error.
1040+
assertCountFails(collection, "{\"$query\": {}, \"$hint\": \"no_such_index\"}")
1041+
XCTAssertEqual(count(collection, "{\"$query\": {}, \"$hint\": {\"_id\": 1}}"), 3)
1042+
1043+
// maxTimeMS reaches the server: a negative value is rejected.
1044+
assertCountFails(collection, "{\"$query\": {}, \"$maxTimeMS\": -1}")
1045+
1046+
// collation reaches the server: case-insensitive match.
1047+
XCTAssertEqual(count(collection, "{\"$query\": {\"b\": \"VALUE 1\"}}"), 0)
1048+
XCTAssertEqual(count(collection, "{\"$query\": {\"b\": \"VALUE 1\"}, \"$collation\": {\"locale\": \"en\", \"strength\": 2}}"), 1)
1049+
1050+
// Duplicate $query: the last one wins, as in libmongoc 1.x.
1051+
XCTAssertEqual(count(collection, "{\"$query\": {\"a\": 1}, \"$query\": {\"a\": 2}}"), 1)
1052+
XCTAssertEqual(count(collection, "{\"$query\": {\"a\": 1}, \"$query\": {\"b\": \"value 2\"}}"), 1)
1053+
1054+
// Int.min has no absolute value; it's rejected before llabs.
1055+
if case .error(_, _, let message) = collection.count(query: BSON(), limit: Int.min) {
1056+
XCTAssert(message.contains("INT64_MIN"), message)
1057+
} else {
1058+
XCTFail("count with limit Int.min should fail")
1059+
}
1060+
}
1061+
1062+
func testLegacyCountComment() throws {
1063+
// Checked through the profiler, in a database of its own so the test's profiling
1064+
// level and profile entries don't touch the shared test database.
1065+
let client = try MongoClient(uri: testURI)
1066+
let db = client.getDatabase(name: "perfect_test_count_comment")
1067+
defer { _ = db.drop() }
1068+
guard case .replyCollection(let collection) = db.createCollection(name: "c", options: nil) else {
1069+
return XCTFail("could not create collection")
1070+
}
1071+
guard case .success = collection.insert(document: try BSON(json: "{\"a\": 1}")) else {
1072+
return XCTFail("insert failed")
1073+
}
1074+
guard case .replyDoc = collection.runCommand(try BSON(json: "{\"profile\": 2}")) else {
1075+
throw XCTSkip("profiling isn't available on this server")
1076+
}
1077+
defer { _ = collection.runCommand(try! BSON(json: "{\"profile\": 0}")) }
1078+
let comment = "perfect-count-\(UUID().uuidString)"
1079+
XCTAssertEqual(count(collection, "{\"$query\": {}, \"$comment\": \"\(comment)\"}"), 1)
1080+
let profile = client.getCollection(databaseName: "perfect_test_count_comment", collectionName: "system.profile")
1081+
XCTAssertEqual(profile.find(query: try BSON(json: "{\"command.comment\": \"\(comment)\"}"))?.map { $0 }.count, 1)
1082+
}
1083+
1084+
func testMultiUpdateWithReplacementIsRejected() {
1085+
let (client, collection) = freshCollection("testmultireplace")
1086+
defer { withExtendedLifetime(client) {} }
1087+
defer { _ = collection.drop() }
1088+
1089+
guard case .error(_, _, let message) = collection.update(selector: try! BSON(json: "{}"), update: try! BSON(json: "{\"replaced\": true}"), flag: .multiUpdate) else {
1090+
return XCTFail("multi update with a replacement document succeeded")
1091+
}
1092+
XCTAssert(message.contains("replacement"), message)
1093+
XCTAssertEqual(count(collection, "{\"replaced\": true}"), 0)
1094+
XCTAssertEqual(count(collection, "{\"a\": {\"$exists\": true}}"), 3)
1095+
}
1096+
9911097
func testBulkWrites() {
9921098
let (client, collection) = freshCollection("testbulkwrites")
9931099
defer { withExtendedLifetime(client) {} }

0 commit comments

Comments
 (0)