Skip to content

Commit 168099b

Browse files
authored
fix: Query with many subqueries can consume excessive server CPU ([GHSA-963q-5h7v-p8w8](GHSA-963q-5h7v-p8w8)) (#10912)
1 parent 38016b8 commit 168099b

2 files changed

Lines changed: 187 additions & 37 deletions

File tree

‎spec/vulnerabilities.spec.js‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16330,4 +16330,130 @@ describe('Vulnerabilities', () => {
1633016330
}
1633116331
});
1633216332
});
16333+
16334+
describe('(GHSA-963q-5h7v-p8w8) Query with many subqueries', () => {
16335+
const auth = require('../lib/Auth');
16336+
const rest = require('../lib/rest');
16337+
const subquery = group => ({ className: 'Item', where: { group } });
16338+
// Conditions with a subquery for the items of a group
16339+
const conditions = {
16340+
$inQuery: group => ({ parent: { $inQuery: subquery(group) } }),
16341+
$notInQuery: group => ({ parent: { $notInQuery: subquery(group) } }),
16342+
$select: (group, key = 'name') => ({ [key]: { $select: { query: subquery(group), key } } }),
16343+
$dontSelect: group => ({ name: { $dontSelect: { query: subquery(group), key: 'name' } } }),
16344+
};
16345+
const find = where => {
16346+
const config = Config.get(Parse.applicationId);
16347+
return rest.find(config, auth.nobody(config), 'Item', where);
16348+
};
16349+
const names = async where => (await find(where)).results.map(item => item.name).sort();
16350+
// Number of reads of the first condition of an `$or` while the query is processed
16351+
const readsOfFirstCondition = async others => {
16352+
let reads = 0;
16353+
const first = Object.defineProperty({}, 'group', {
16354+
enumerable: true,
16355+
get: () => {
16356+
reads++;
16357+
return 0;
16358+
},
16359+
});
16360+
await find({ $or: [first, ...others] });
16361+
return reads;
16362+
};
16363+
const repeat = (count, condition) => Array.from({ length: count }, () => condition(1));
16364+
16365+
// Items a, b, c, d of the groups 1 to 4; each item after a has the item before it as parent
16366+
beforeEach(async () => {
16367+
let parent;
16368+
for (const [index, name] of ['a', 'b', 'c', 'd'].entries()) {
16369+
const item = new Parse.Object('Item', { name, title: name, group: index + 1 });
16370+
parent = await item.save(parent ? { parent } : {});
16371+
}
16372+
});
16373+
16374+
describe('search for subqueries', () => {
16375+
for (const [operator, condition] of Object.entries(conditions)) {
16376+
it(`reads the conditions as often for many ${operator} subqueries as for few`, async () => {
16377+
const few = await readsOfFirstCondition(repeat(2, condition));
16378+
const many = await readsOfFirstCondition(repeat(30, condition));
16379+
expect(few).toBeGreaterThan(0);
16380+
expect(many).toBe(few);
16381+
});
16382+
}
16383+
16384+
it('reads the conditions as often for many subqueries of all operators as for few', async () => {
16385+
const all = count =>
16386+
Object.values(conditions).flatMap(condition => repeat(count, condition));
16387+
const few = await readsOfFirstCondition(all(1));
16388+
const many = await readsOfFirstCondition(all(10));
16389+
expect(few).toBeGreaterThan(0);
16390+
expect(many).toBe(few);
16391+
});
16392+
16393+
it('runs the subqueries in the order of the conditions', async () => {
16394+
const groups = [];
16395+
Parse.Cloud.beforeFind('Item', ({ query }) => {
16396+
const { group } = query.toJSON().where;
16397+
if (typeof group === 'number') {
16398+
groups.push(group);
16399+
}
16400+
});
16401+
await find({
16402+
$or: [conditions.$inQuery(1), conditions.$inQuery(2)],
16403+
$and: [conditions.$inQuery(3), conditions.$inQuery(4)],
16404+
});
16405+
expect(groups).toEqual([1, 2, 3, 4]);
16406+
});
16407+
16408+
it('rejects conditions that contain themselves', async () => {
16409+
const where = { name: 'a' };
16410+
where.self = where;
16411+
await expectAsync(find(where)).toBeRejected();
16412+
});
16413+
});
16414+
16415+
describe('results', () => {
16416+
it('returns the items of every subquery of an $or', async () => {
16417+
const where = { $or: [1, 2, 3].map(group => conditions.$inQuery(group)) };
16418+
expect(await names(where)).toEqual(['b', 'c', 'd']);
16419+
});
16420+
16421+
it('returns the items that match the subqueries of two keys', async () => {
16422+
const where = {
16423+
...conditions.$select({ $lte: 2 }),
16424+
...conditions.$select({ $gte: 2 }, 'title'),
16425+
};
16426+
expect(await names(where)).toEqual(['b']);
16427+
});
16428+
16429+
it('returns the items that match the subqueries of nested logical operators', async () => {
16430+
const where = {
16431+
$and: [
16432+
{ $or: [conditions.$inQuery(1), conditions.$inQuery(2)] },
16433+
{ $or: [conditions.$inQuery(2), conditions.$inQuery(3)] },
16434+
],
16435+
};
16436+
expect(await names(where)).toEqual(['c']);
16437+
});
16438+
16439+
it('returns the items that match two subqueries of one key', async () => {
16440+
const where = {
16441+
parent: { $inQuery: subquery({ $lte: 2 }), $notInQuery: subquery(1) },
16442+
};
16443+
expect(await names(where)).toEqual(['c']);
16444+
});
16445+
16446+
it('returns the items that match subqueries of all operators', async () => {
16447+
const where = {
16448+
$or: [1, 2, 3].map(group => conditions.$inQuery(group)),
16449+
$and: [
16450+
conditions.$notInQuery(3),
16451+
conditions.$dontSelect(2),
16452+
conditions.$select({ $gte: 2 }),
16453+
],
16454+
};
16455+
expect(await names(where)).toEqual(['c']);
16456+
});
16457+
});
16458+
});
1633316459
});

‎src/RestQuery.js‎

Lines changed: 61 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -574,8 +574,10 @@ _UnsafeRestQuery.prototype.checkSubqueryDepth = function () {
574574
// $inQuery clause.
575575
// The $inQuery clause turns into an $in with values that are just
576576
// pointers to the objects returned in the subquery.
577-
_UnsafeRestQuery.prototype.replaceInQuery = async function () {
578-
var inQueryObject = findObjectWithKey(this.restWhere, '$inQuery');
577+
_UnsafeRestQuery.prototype.replaceInQuery = async function (
578+
search = findObjectsWithKey(this.restWhere, '$inQuery')
579+
) {
580+
var inQueryObject = search.next().value;
579581
if (!inQueryObject) {
580582
return;
581583
}
@@ -616,8 +618,8 @@ _UnsafeRestQuery.prototype.replaceInQuery = async function () {
616618
});
617619
return subquery.execute().then(response => {
618620
transformInQuery(inQueryObject, subquery.className, response.results);
619-
// Recurse to repeat
620-
return this.replaceInQuery();
621+
// Continue the search to repeat
622+
return this.replaceInQuery(search);
621623
});
622624
};
623625

@@ -642,8 +644,10 @@ function transformNotInQuery(notInQueryObject, className, results) {
642644
// $notInQuery clause.
643645
// The $notInQuery clause turns into a $nin with values that are just
644646
// pointers to the objects returned in the subquery.
645-
_UnsafeRestQuery.prototype.replaceNotInQuery = async function () {
646-
var notInQueryObject = findObjectWithKey(this.restWhere, '$notInQuery');
647+
_UnsafeRestQuery.prototype.replaceNotInQuery = async function (
648+
search = findObjectsWithKey(this.restWhere, '$notInQuery')
649+
) {
650+
var notInQueryObject = search.next().value;
647651
if (!notInQueryObject) {
648652
return;
649653
}
@@ -685,8 +689,8 @@ _UnsafeRestQuery.prototype.replaceNotInQuery = async function () {
685689

686690
return subquery.execute().then(response => {
687691
transformNotInQuery(notInQueryObject, subquery.className, response.results);
688-
// Recurse to repeat
689-
return this.replaceNotInQuery();
692+
// Continue the search to repeat
693+
return this.replaceNotInQuery(search);
690694
});
691695
};
692696

@@ -716,8 +720,10 @@ const transformSelect = (selectObject, key, objects) => {
716720
// The $select clause turns into an $in with values selected out of
717721
// the subquery.
718722
// Returns a possible-promise.
719-
_UnsafeRestQuery.prototype.replaceSelect = async function () {
720-
var selectObject = findObjectWithKey(this.restWhere, '$select');
723+
_UnsafeRestQuery.prototype.replaceSelect = async function (
724+
search = findObjectsWithKey(this.restWhere, '$select')
725+
) {
726+
var selectObject = search.next().value;
721727
if (!selectObject) {
722728
return;
723729
}
@@ -767,7 +773,7 @@ _UnsafeRestQuery.prototype.replaceSelect = async function () {
767773
return subquery.execute().then(response => {
768774
transformSelect(selectObject, selectValue.key, response.results);
769775
// Keep replacing $select clauses
770-
return this.replaceSelect();
776+
return this.replaceSelect(search);
771777
});
772778
};
773779

@@ -789,8 +795,10 @@ const transformDontSelect = (dontSelectObject, key, objects) => {
789795
// The $dontSelect clause turns into an $nin with values selected out of
790796
// the subquery.
791797
// Returns a possible-promise.
792-
_UnsafeRestQuery.prototype.replaceDontSelect = async function () {
793-
var dontSelectObject = findObjectWithKey(this.restWhere, '$dontSelect');
798+
_UnsafeRestQuery.prototype.replaceDontSelect = async function (
799+
search = findObjectsWithKey(this.restWhere, '$dontSelect')
800+
) {
801+
var dontSelectObject = search.next().value;
794802
if (!dontSelectObject) {
795803
return;
796804
}
@@ -838,7 +846,7 @@ _UnsafeRestQuery.prototype.replaceDontSelect = async function () {
838846
return subquery.execute().then(response => {
839847
transformDontSelect(dontSelectObject, dontSelectValue.key, response.results);
840848
// Keep replacing $dontSelect clauses
841-
return this.replaceDontSelect();
849+
return this.replaceDontSelect(search);
842850
});
843851
};
844852

@@ -1387,31 +1395,47 @@ function replacePointers(object, path, replace) {
13871395
return answer;
13881396
}
13891397

1390-
// Finds a subobject that has the given key, if there is one.
1391-
// Returns undefined otherwise.
1392-
function findObjectWithKey(root, key) {
1393-
if (typeof root !== 'object') {
1394-
return;
1395-
}
1396-
if (Array.isArray(root)) {
1397-
for (var item of root) {
1398-
const answer = findObjectWithKey(item, key);
1399-
if (answer) {
1400-
return answer;
1398+
// Iterates over the subobjects that have the given key, depth first.
1399+
// A yielded object is searched after the caller has replaced the key.
1400+
function* findObjectsWithKey(root, key) {
1401+
const isObject = value => value !== null && typeof value === 'object';
1402+
const stack = [root].filter(isObject);
1403+
// Ends the search of circular references
1404+
const searched = new WeakSet();
1405+
while (stack.length > 0) {
1406+
const node = stack.pop();
1407+
const start = stack.length;
1408+
if (Array.isArray(node)) {
1409+
for (let i = 0; i < node.length; i++) {
1410+
const item = node[i];
1411+
if (isObject(item)) {
1412+
stack.push(item);
1413+
}
1414+
}
1415+
} else {
1416+
if (node[key]) {
1417+
yield node;
1418+
}
1419+
for (const subkey in node) {
1420+
const value = node[subkey];
1421+
if (isObject(value)) {
1422+
stack.push(value);
1423+
}
14011424
}
14021425
}
1403-
// Arrays are fully traversed above; returning here avoids re-walking the same
1404-
// elements through the `for (subkey in root)` loop below, which would make this
1405-
// function O(2^n) for nested arrays (e.g. deeply nested $or/$and/$nor).
1406-
return;
1407-
}
1408-
if (root && root[key]) {
1409-
return root;
1410-
}
1411-
for (var subkey in root) {
1412-
const answer = findObjectWithKey(root[subkey], key);
1413-
if (answer) {
1414-
return answer;
1426+
if (stack.length === start) {
1427+
continue;
1428+
}
1429+
if (searched.has(node)) {
1430+
stack.length = start;
1431+
continue;
1432+
}
1433+
searched.add(node);
1434+
// The stack returns the last subobject first
1435+
for (let i = start, j = stack.length - 1; i < j; i++, j--) {
1436+
const last = stack[j];
1437+
stack[j] = stack[i];
1438+
stack[i] = last;
14151439
}
14161440
}
14171441
}

0 commit comments

Comments
 (0)