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
126 changes: 126 additions & 0 deletions spec/vulnerabilities.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -16330,4 +16330,130 @@ describe('Vulnerabilities', () => {
}
});
});

describe('(GHSA-963q-5h7v-p8w8) Query with many subqueries', () => {
const auth = require('../lib/Auth');
const rest = require('../lib/rest');
const subquery = group => ({ className: 'Item', where: { group } });
// Conditions with a subquery for the items of a group
const conditions = {
$inQuery: group => ({ parent: { $inQuery: subquery(group) } }),
$notInQuery: group => ({ parent: { $notInQuery: subquery(group) } }),
$select: (group, key = 'name') => ({ [key]: { $select: { query: subquery(group), key } } }),
$dontSelect: group => ({ name: { $dontSelect: { query: subquery(group), key: 'name' } } }),
};
const find = where => {
const config = Config.get(Parse.applicationId);
return rest.find(config, auth.nobody(config), 'Item', where);
};
const names = async where => (await find(where)).results.map(item => item.name).sort();
// Number of reads of the first condition of an `$or` while the query is processed
const readsOfFirstCondition = async others => {
let reads = 0;
const first = Object.defineProperty({}, 'group', {
enumerable: true,
get: () => {
reads++;
return 0;
},
});
await find({ $or: [first, ...others] });
return reads;
};
const repeat = (count, condition) => Array.from({ length: count }, () => condition(1));

// Items a, b, c, d of the groups 1 to 4; each item after a has the item before it as parent
beforeEach(async () => {
let parent;
for (const [index, name] of ['a', 'b', 'c', 'd'].entries()) {
const item = new Parse.Object('Item', { name, title: name, group: index + 1 });
parent = await item.save(parent ? { parent } : {});
}
});

describe('search for subqueries', () => {
for (const [operator, condition] of Object.entries(conditions)) {
it(`reads the conditions as often for many ${operator} subqueries as for few`, async () => {
const few = await readsOfFirstCondition(repeat(2, condition));
const many = await readsOfFirstCondition(repeat(30, condition));
expect(few).toBeGreaterThan(0);
expect(many).toBe(few);
});
}

it('reads the conditions as often for many subqueries of all operators as for few', async () => {
const all = count =>
Object.values(conditions).flatMap(condition => repeat(count, condition));
const few = await readsOfFirstCondition(all(1));
const many = await readsOfFirstCondition(all(10));
expect(few).toBeGreaterThan(0);
expect(many).toBe(few);
});

it('runs the subqueries in the order of the conditions', async () => {
const groups = [];
Parse.Cloud.beforeFind('Item', ({ query }) => {
const { group } = query.toJSON().where;
if (typeof group === 'number') {
groups.push(group);
}
});
await find({
$or: [conditions.$inQuery(1), conditions.$inQuery(2)],
$and: [conditions.$inQuery(3), conditions.$inQuery(4)],
});
expect(groups).toEqual([1, 2, 3, 4]);
});

it('rejects conditions that contain themselves', async () => {
const where = { name: 'a' };
where.self = where;
await expectAsync(find(where)).toBeRejected();
});
});

describe('results', () => {
it('returns the items of every subquery of an $or', async () => {
const where = { $or: [1, 2, 3].map(group => conditions.$inQuery(group)) };
expect(await names(where)).toEqual(['b', 'c', 'd']);
});

it('returns the items that match the subqueries of two keys', async () => {
const where = {
...conditions.$select({ $lte: 2 }),
...conditions.$select({ $gte: 2 }, 'title'),
};
expect(await names(where)).toEqual(['b']);
});

it('returns the items that match the subqueries of nested logical operators', async () => {
const where = {
$and: [
{ $or: [conditions.$inQuery(1), conditions.$inQuery(2)] },
{ $or: [conditions.$inQuery(2), conditions.$inQuery(3)] },
],
};
expect(await names(where)).toEqual(['c']);
});

it('returns the items that match two subqueries of one key', async () => {
const where = {
parent: { $inQuery: subquery({ $lte: 2 }), $notInQuery: subquery(1) },
};
expect(await names(where)).toEqual(['c']);
});

it('returns the items that match subqueries of all operators', async () => {
const where = {
$or: [1, 2, 3].map(group => conditions.$inQuery(group)),
$and: [
conditions.$notInQuery(3),
conditions.$dontSelect(2),
conditions.$select({ $gte: 2 }),
],
};
expect(await names(where)).toEqual(['c']);
});
});
});
});
98 changes: 61 additions & 37 deletions src/RestQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -574,8 +574,10 @@ _UnsafeRestQuery.prototype.checkSubqueryDepth = function () {
// $inQuery clause.
// The $inQuery clause turns into an $in with values that are just
// pointers to the objects returned in the subquery.
_UnsafeRestQuery.prototype.replaceInQuery = async function () {
var inQueryObject = findObjectWithKey(this.restWhere, '$inQuery');
_UnsafeRestQuery.prototype.replaceInQuery = async function (
search = findObjectsWithKey(this.restWhere, '$inQuery')
) {
var inQueryObject = search.next().value;
if (!inQueryObject) {
return;
}
Expand Down Expand Up @@ -616,8 +618,8 @@ _UnsafeRestQuery.prototype.replaceInQuery = async function () {
});
return subquery.execute().then(response => {
transformInQuery(inQueryObject, subquery.className, response.results);
// Recurse to repeat
return this.replaceInQuery();
// Continue the search to repeat
return this.replaceInQuery(search);
});
};

Expand All @@ -642,8 +644,10 @@ function transformNotInQuery(notInQueryObject, className, results) {
// $notInQuery clause.
// The $notInQuery clause turns into a $nin with values that are just
// pointers to the objects returned in the subquery.
_UnsafeRestQuery.prototype.replaceNotInQuery = async function () {
var notInQueryObject = findObjectWithKey(this.restWhere, '$notInQuery');
_UnsafeRestQuery.prototype.replaceNotInQuery = async function (
search = findObjectsWithKey(this.restWhere, '$notInQuery')
) {
var notInQueryObject = search.next().value;
if (!notInQueryObject) {
return;
}
Expand Down Expand Up @@ -685,8 +689,8 @@ _UnsafeRestQuery.prototype.replaceNotInQuery = async function () {

return subquery.execute().then(response => {
transformNotInQuery(notInQueryObject, subquery.className, response.results);
// Recurse to repeat
return this.replaceNotInQuery();
// Continue the search to repeat
return this.replaceNotInQuery(search);
});
};

Expand Down Expand Up @@ -716,8 +720,10 @@ const transformSelect = (selectObject, key, objects) => {
// The $select clause turns into an $in with values selected out of
// the subquery.
// Returns a possible-promise.
_UnsafeRestQuery.prototype.replaceSelect = async function () {
var selectObject = findObjectWithKey(this.restWhere, '$select');
_UnsafeRestQuery.prototype.replaceSelect = async function (
search = findObjectsWithKey(this.restWhere, '$select')
) {
var selectObject = search.next().value;
if (!selectObject) {
return;
}
Expand Down Expand Up @@ -767,7 +773,7 @@ _UnsafeRestQuery.prototype.replaceSelect = async function () {
return subquery.execute().then(response => {
transformSelect(selectObject, selectValue.key, response.results);
// Keep replacing $select clauses
return this.replaceSelect();
return this.replaceSelect(search);
});
};

Expand All @@ -789,8 +795,10 @@ const transformDontSelect = (dontSelectObject, key, objects) => {
// The $dontSelect clause turns into an $nin with values selected out of
// the subquery.
// Returns a possible-promise.
_UnsafeRestQuery.prototype.replaceDontSelect = async function () {
var dontSelectObject = findObjectWithKey(this.restWhere, '$dontSelect');
_UnsafeRestQuery.prototype.replaceDontSelect = async function (
search = findObjectsWithKey(this.restWhere, '$dontSelect')
) {
var dontSelectObject = search.next().value;
if (!dontSelectObject) {
return;
}
Expand Down Expand Up @@ -838,7 +846,7 @@ _UnsafeRestQuery.prototype.replaceDontSelect = async function () {
return subquery.execute().then(response => {
transformDontSelect(dontSelectObject, dontSelectValue.key, response.results);
// Keep replacing $dontSelect clauses
return this.replaceDontSelect();
return this.replaceDontSelect(search);
});
};

Expand Down Expand Up @@ -1387,31 +1395,47 @@ function replacePointers(object, path, replace) {
return answer;
}

// Finds a subobject that has the given key, if there is one.
// Returns undefined otherwise.
function findObjectWithKey(root, key) {
if (typeof root !== 'object') {
return;
}
if (Array.isArray(root)) {
for (var item of root) {
const answer = findObjectWithKey(item, key);
if (answer) {
return answer;
// Iterates over the subobjects that have the given key, depth first.
// A yielded object is searched after the caller has replaced the key.
function* findObjectsWithKey(root, key) {
const isObject = value => value !== null && typeof value === 'object';
const stack = [root].filter(isObject);
// Ends the search of circular references
const searched = new WeakSet();
while (stack.length > 0) {
const node = stack.pop();
const start = stack.length;
if (Array.isArray(node)) {
for (let i = 0; i < node.length; i++) {
const item = node[i];
if (isObject(item)) {
stack.push(item);
}
}
} else {
if (node[key]) {
yield node;
}
for (const subkey in node) {
const value = node[subkey];
if (isObject(value)) {
stack.push(value);
}
}
}
// Arrays are fully traversed above; returning here avoids re-walking the same
// elements through the `for (subkey in root)` loop below, which would make this
// function O(2^n) for nested arrays (e.g. deeply nested $or/$and/$nor).
return;
}
if (root && root[key]) {
return root;
}
for (var subkey in root) {
const answer = findObjectWithKey(root[subkey], key);
if (answer) {
return answer;
if (stack.length === start) {
continue;
}
if (searched.has(node)) {
stack.length = start;
continue;
}
searched.add(node);
// The stack returns the last subobject first
for (let i = start, j = stack.length - 1; i < j; i++, j--) {
const last = stack[j];
stack[j] = stack[i];
stack[i] = last;
}
}
}
Expand Down
Loading