mongoose 6.13.12 → 6.13.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cast.js CHANGED
@@ -105,6 +105,11 @@ module.exports = function cast(schema, obj, options, context) {
105
105
  } else if (path === '$comment' && !schema.paths.hasOwnProperty('$comment')) {
106
106
  val = castString(val, path);
107
107
  obj[path] = val;
108
+ } else if (isOperator(path)) {
109
+ // Pass through other top-level operators, like `$jsonSchema`, without casting.
110
+ // MongoDB doesn't allow querying top-level `$` fields, so these can't be paths
111
+ // and `strict` or `strictQuery` shouldn't strip them.
112
+ continue;
108
113
  } else {
109
114
  if (!schema) {
110
115
  // no casting for Mixed types
@@ -66,7 +66,14 @@ function QueryCursor(query, options) {
66
66
  // Max out the number of documents we'll populate in parallel at 5000.
67
67
  this.options._populateBatchSize = Math.min(this.options.batchSize, 5000);
68
68
  }
69
- Object.assign(this.options, query._optionsForExec());
69
+ // `_optionsForExec()` can throw, for example if casting the projection fails
70
+ try {
71
+ Object.assign(this.options, query._optionsForExec());
72
+ } catch (err) {
73
+ _this._markError(err);
74
+ _this.listeners('error').length > 0 && _this.emit('error', err);
75
+ return;
76
+ }
70
77
  model.collection.find(query._conditions, this.options, (err, cursor) => {
71
78
  if (err != null) {
72
79
  _this._markError(err);
@@ -9,7 +9,9 @@ function isBsonType(obj, typename) {
9
9
  return (
10
10
  typeof obj === 'object' &&
11
11
  obj !== null &&
12
- obj._bsontype === typename
12
+ obj._bsontype === typename &&
13
+ // bson defines `_bsontype` on the prototype, so an own `_bsontype` means a plain object pretending to be a bson value
14
+ !Object.prototype.hasOwnProperty.call(obj, '_bsontype')
13
15
  );
14
16
  }
15
17
 
@@ -24,7 +24,7 @@ module.exports = function sanitizeFilter(filter) {
24
24
  if (key === '$and' || key === '$or' || key === '$nor') {
25
25
  sanitizeFilter(value);
26
26
  continue;
27
- } else if (key === '$jsonSchema' || key === '$where' || key === '$expr' || key === '$text') {
27
+ } else if (key[0] === '$') {
28
28
  throw new MongooseError(key + ' is not allowed with sanitizeFilter');
29
29
  }
30
30
 
@@ -7,7 +7,24 @@ module.exports = function sanitizeProjection(projection) {
7
7
 
8
8
  const keys = Object.keys(projection);
9
9
  for (let i = 0; i < keys.length; ++i) {
10
- if (typeof projection[keys[i]] === 'string') {
10
+ const value = projection[keys[i]];
11
+ if (typeof value === 'string') {
12
+ projection[keys[i]] = 1;
13
+ continue;
14
+ }
15
+ if (value == null || typeof value !== 'object') {
16
+ continue;
17
+ }
18
+ // Only allow `$meta: 'textScore'`, `$elemMatch`, and numeric `$slice`. Nested sub-projections, arrays, and
19
+ // expressions like `{ name: { $concat: ['$password'] } }` become `1`. Note that
20
+ // `{ $slice: ['$otherArray', 1] }` is an expression that can read another field, and
21
+ // `$meta: 'indexKey'` and `$meta: 'sortKey'` can return values of `select: false` paths.
22
+ const slice = value.$slice;
23
+ const isAllowedProjectionOperator = value.$meta === 'textScore' ||
24
+ value.$elemMatch != null ||
25
+ typeof slice === 'number' ||
26
+ (Array.isArray(slice) && slice.every(v => typeof v === 'number'));
27
+ if (!isAllowedProjectionOperator) {
11
28
  projection[keys[i]] = 1;
12
29
  }
13
30
  }
@@ -26,6 +26,11 @@ module.exports = function wrapThunk(fn) {
26
26
  }
27
27
  this._executionStack = new Error().stack;
28
28
 
29
- fn.call(this, cb);
29
+ // Thunks can throw synchronously, for example if `_optionsForExec()` fails to cast the projection
30
+ try {
31
+ fn.call(this, cb);
32
+ } catch (err) {
33
+ cb(err);
34
+ }
30
35
  };
31
36
  };
package/lib/query.js CHANGED
@@ -1135,6 +1135,11 @@ Query.prototype.select = function select() {
1135
1135
  arg = parseProjection(arg);
1136
1136
 
1137
1137
  if (utils.isObject(arg)) {
1138
+ // `fields['__proto__'] = value` would re-point the projection's prototype
1139
+ if (Object.prototype.hasOwnProperty.call(arg, '__proto__')) {
1140
+ arg = { ...arg };
1141
+ delete arg['__proto__'];
1142
+ }
1138
1143
  if (this.selectedInclusively()) {
1139
1144
  Object.entries(arg).forEach(([key, value]) => {
1140
1145
  if (value) {
@@ -3715,15 +3720,9 @@ Query.prototype._findOneAndDelete = wrapThunk(function(callback) {
3715
3720
 
3716
3721
  const filter = this._conditions;
3717
3722
  const options = this._optionsForExec();
3718
- let fields = null;
3719
3723
 
3720
3724
  if (this._fields != null) {
3721
3725
  options.projection = this._castFields(utils.clone(this._fields));
3722
- fields = options.projection;
3723
- if (fields instanceof Error) {
3724
- callback(fields);
3725
- return null;
3726
- }
3727
3726
  }
3728
3727
 
3729
3728
  this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => {
@@ -5426,11 +5425,7 @@ Query.prototype._castFields = function _castFields(fields) {
5426
5425
 
5427
5426
  if (selected) {
5428
5427
  // they passed $elemMatch, cast em
5429
- try {
5430
- out = this.cast(this.model, selected);
5431
- } catch (err) {
5432
- return err;
5433
- }
5428
+ out = this.cast(this.model, selected);
5434
5429
 
5435
5430
  // apply the casted field args
5436
5431
  i = elemMatchKeys.length;
@@ -5453,6 +5448,20 @@ Query.prototype._applyPaths = function applyPaths() {
5453
5448
  return;
5454
5449
  }
5455
5450
  this._fields = this._fields || {};
5451
+
5452
+ let shouldSanitizeProjection = undefined;
5453
+ if (utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeProjection')) {
5454
+ shouldSanitizeProjection = this.model.db.options.sanitizeProjection;
5455
+ } else if (utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeProjection')) {
5456
+ shouldSanitizeProjection = this.model.base.options.sanitizeProjection;
5457
+ } else {
5458
+ shouldSanitizeProjection = this._mongooseOptions.sanitizeProjection;
5459
+ }
5460
+ // Strip expressions at exec time, because projections may be set before `sanitizeProjection`
5461
+ if (shouldSanitizeProjection) {
5462
+ sanitizeProjection(this._fields);
5463
+ }
5464
+
5456
5465
  helpers.applyPaths(this._fields, this.model.schema);
5457
5466
 
5458
5467
  let _selectPopulatedPaths = true;
@@ -5514,8 +5523,10 @@ Query.prototype.cursor = function cursor(opts) {
5514
5523
  this.setOptions(opts);
5515
5524
  }
5516
5525
 
5517
- const options = this._optionsForExec();
5526
+ let options;
5518
5527
  try {
5528
+ // `_optionsForExec()` throws if casting the projection fails
5529
+ options = this._optionsForExec();
5519
5530
  this._castConditions();
5520
5531
  } catch (err) {
5521
5532
  // `_castConditions()` reports cast errors on the query, but `sanitizeFilter`
@@ -11,7 +11,9 @@ const get = require('./helpers/get');
11
11
  const getDiscriminatorByValue =
12
12
  require('./helpers/discriminator/getDiscriminatorByValue');
13
13
  const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
14
+ const isExclusive = require('./helpers/projection/isExclusive');
14
15
  const clone = require('./helpers/clone');
16
+ const utils = require('./utils');
15
17
 
16
18
  /**
17
19
  * Prepare a set of path options for query population.
@@ -154,6 +156,7 @@ exports.applyPaths = function applyPaths(fields, schema) {
154
156
  if (fields) {
155
157
  keys = Object.keys(fields);
156
158
  keyIndex = keys.length;
159
+ let hasElemMatch = false;
157
160
 
158
161
  while (keyIndex--) {
159
162
  if (keys[keyIndex][0] === '+') {
@@ -164,14 +167,32 @@ exports.applyPaths = function applyPaths(fields, schema) {
164
167
  if (!isDefiningProjection(field)) {
165
168
  continue;
166
169
  }
170
+ // `$elemMatch` is inclusive on its own, but MongoDB treats `{ arr: { $elemMatch }, name: 0 }` as exclusive
171
+ if (field != null && field.$elemMatch != null) {
172
+ hasElemMatch = true;
173
+ continue;
174
+ }
167
175
  // `_id: 1, name: 0` is a mixed inclusive/exclusive projection in
168
176
  // MongoDB 4.0 and earlier, but not in later versions.
169
177
  if (keys[keyIndex] === '_id' && keys.length > 1) {
170
178
  continue;
171
179
  }
180
+ // Nested sub-projections like `{ profile: { bio: 0 } }` are exclusive or inclusive based on their
181
+ // nested values, unlike expressions like `{ $concat: [...] }`, which are always inclusive
182
+ if (utils.isPOJO(field) && !Object.keys(field).some(key => key.startsWith('$'))) {
183
+ const nestedExclude = isExclusive(field);
184
+ if (nestedExclude == null) {
185
+ continue;
186
+ }
187
+ exclude = nestedExclude;
188
+ break;
189
+ }
172
190
  exclude = !field;
173
191
  break;
174
192
  }
193
+ if (exclude === undefined && hasElemMatch) {
194
+ exclude = false;
195
+ }
175
196
  }
176
197
 
177
198
  // if selecting, apply default schematype select:true fields
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "6.13.12",
4
+ "version": "6.13.13",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
package/types/query.d.ts CHANGED
@@ -138,7 +138,15 @@ declare module 'mongoose' {
138
138
  */
139
139
  returnDocument?: 'before' | 'after';
140
140
  runValidators?: boolean;
141
- /* Set to `true` to automatically sanitize potentially unsafe user-generated query projections */
141
+ /**
142
+ * Set to `true` to automatically sanitize potentially unsafe user-generated query projections.
143
+ * Converts projection values that aren't numbers or booleans to `1`, including strings like `'$password'`
144
+ * and expressions like `{ $concat: ['$password'] }`, so projections can't copy one field's value into another.
145
+ * The only projection operators that are allowed are `$elemMatch`, `$slice` with numbers, and `$meta: 'textScore'`.
146
+ *
147
+ * In Mongoose 6, `sanitizeProjection` does **not** prevent projecting in fields that the schema deselects
148
+ * with `select: false`: `select('+password')` and `select({ password: 1 })` still include `password`.
149
+ */
142
150
  sanitizeProjection?: boolean;
143
151
  /**
144
152
  * Set to `true` to automatically sanitize potentially unsafe query filters by stripping out query selectors that