Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make modifiedPaths safer. #12719

Merged
merged 8 commits into from Nov 28, 2022
16 changes: 14 additions & 2 deletions lib/helpers/common.js
Expand Up @@ -67,7 +67,19 @@ function flatten(update, path, options, schema) {
* ignore
*/

function modifiedPaths(update, path, result) {
function modifiedPaths(update, path, result, recursion=null) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this not work?

Suggested change
function modifiedPaths(update, path, result, recursion=null) {
function modifiedPaths(update, path, result, recursion={count: 0, raw: {update, path}}) {

if(recursion == null){
recursion = {
count: 0,
raw: {update, path}
};
}

recursion.count++;
if(recursion.count >= 1024){
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a bit brittle. Admittedly we're unlikely to have depth >= 1024 unless there's an infinite recursion. But I think a better approach would be to use a WeakSet or WeakMap to track what objects we've seen in the recursion, similar to how getIndexes() does it.

throw new Error(`Mongoose: bad update value, ${recursion.raw.update}, ${recursion.raw.path}`);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe create a new MongooseError?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was just worried that it would cause a circular reference.

I will make a new commit tomorrow.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dont worry, I just think a new MongooseRecursionError or something like that would be nicer.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree that this should at least be a MongooseError. Not sure it is worth it to create a new recursion error.

}

const keys = Object.keys(update || {});
const numKeys = keys.length;
result = result || {};
Expand All @@ -83,7 +95,7 @@ function modifiedPaths(update, path, result) {
val = val.toObject({ transform: false, virtuals: false });
}
if (shouldFlatten(val)) {
modifiedPaths(val, path + key, result);
modifiedPaths(val, path + key, result, recursion);
}
}

Expand Down