Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 39 additions & 3 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -2968,6 +2968,42 @@ function _getAllPathsToValidate(doc) {
return [paths, doValidateOptionsByPath];
}

/**
* When a document array is validated as a whole, every element is validated
* with it, so remove the paths underneath each element, like `arr.0.name` or
* `arr.0.nested.1.prop` (gh-16484). Scans `paths` once, so the cost depends on
* the number of paths to validate, not on the size of element values like
* Buffers, primitive arrays or Mixed objects (gh-16765).
*
* @param {Set<string>} paths
* @param {string} arrayPath
* @param {Array<Document>} subdocs
* @api private
*/

function _deleteDocumentArrayElementDescendants(paths, arrayPath, subdocs) {
const indexes = new Set();
for (const subdoc of subdocs) {
if (subdoc?.$basePath) {
indexes.add(String(subdoc.__index));
}
}
if (indexes.size === 0) {
return;
}

const prefix = arrayPath + '.';
for (const path of paths) {
if (!path.startsWith(prefix)) {
continue;
}
const indexEnd = path.indexOf('.', prefix.length);
if (indexEnd !== -1 && indexes.has(path.slice(prefix.length, indexEnd))) {
paths.delete(path);
}
}
}

/*!
* ignore
*/
Expand Down Expand Up @@ -3181,6 +3217,9 @@ function _getPathsToValidate(doc, pathsToValidate, pathsToSkip) {
// are redundant. They can be seeded before the array is, so drop them
// here rather than relying on the array being seen first.
const arrayCoversElements = schemaType.$isMongooseDocumentArray && covered[path] === true;
if (arrayCoversElements) {
_deleteDocumentArrayElementDescendants(paths, path, subdocs);
}

for (const subdoc of subdocs) {
if (subdoc == null || !subdoc.$basePath) {
Expand All @@ -3195,9 +3234,6 @@ function _getPathsToValidate(doc, pathsToValidate, pathsToSkip) {
}
if (arrayCoversElements) {
paths.delete(fullPathToSubdoc);
for (const modifiedPath of subdoc.modifiedPaths({ includeChildren: true })) {
paths.delete(fullPathToSubdoc + '.' + modifiedPath);
}
if (path !== schemaType.path && Object.hasOwn(activeStates.modify, fullPathToSubdoc)) {
doValidateOptions[fullPathToSubdoc] = { skipSchemaValidators: false };
}
Expand Down
68 changes: 68 additions & 0 deletions test/document.validate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1361,6 +1361,74 @@ describe('document validation', function() {
assert.equal(arrayValidatorCalls, 1);
});
});

describe('large values in document array elements (gh-16765)', function() {
// Validation cost must follow the schema, not the data: a large Buffer,
// primitive array or Mixed object in an element must not be expanded
// into one modified path per byte, element or key.
const maxModifiedPaths = 100;

afterEach(() => sinon.restore());

async function assertValidatesWithoutExpansion(doc) {
const spy = sinon.spy(mongoose.Document.prototype, 'modifiedPaths');

await doc.validate();
assert.ifError(doc.validateSync());

const largest = Math.max(0, ...spy.returnValues.map(paths => paths.length));
assert.ok(largest < maxModifiedPaths, `modifiedPaths() returned ${largest} paths`);
}

it('does not enumerate the bytes of a Buffer', async function() {
const Model = db.model('Test', new Schema({
attachments: [new Schema({ data: Buffer })]
}));
const doc = new Model({ attachments: [{ data: Buffer.alloc(4 * 1024 * 1024) }] });

await assertValidatesWithoutExpansion(doc);
});

it('does not enumerate the elements of a primitive array', async function() {
const Model = db.model('Test', new Schema({
arr: [new Schema({ values: [Number] })]
}));
const values = Array.from({ length: 100000 }, (_, i) => i);
const doc = new Model({ arr: [{ values }] });

await assertValidatesWithoutExpansion(doc);
});

it('does not enumerate the keys of a Mixed object', async function() {
const Model = db.model('Test', new Schema({
arr: [new Schema({ meta: Schema.Types.Mixed })]
}));
const meta = {};
for (let i = 0; i < 100000; ++i) {
meta['k' + i] = i;
}
const doc = new Model({ arr: [{ meta }] });

await assertValidatesWithoutExpansion(doc);
});

it('still reports errors on element subpaths next to a large Buffer', async function() {
const Model = db.model('Test', new Schema({
attachments: [new Schema({
data: Buffer,
name: { type: String, required: true }
})]
}));
const doc = new Model({
attachments: [{ data: Buffer.alloc(1024 * 1024), name: 'a' }, { data: Buffer.alloc(1024 * 1024) }]
});

const error = await doc.validate().then(() => null, error => error);
assert.ok(error?.errors['attachments.1.name'], error);
assert.ok(!error.errors['attachments.0.name'], error);
assert.ok(doc.validateSync()?.errors['attachments.1.name']);
});
});
});

describe('#validate', function() {
Expand Down