Skip to content
Merged
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
149 changes: 149 additions & 0 deletions spec/RequestComplexity.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,155 @@ describe('request complexity', () => {
rest.find(config, auth.nobody(config), '_User', where)
).toBeResolved();
});

describe('request context', () => {
const headers = {
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
'Content-Type': 'application/json',
};
const find = (where, context, className = '_User') =>
request({
method: 'POST',
url: `http://localhost:8378/1/classes/${className}`,
headers: context
? { ...headers, 'X-Parse-Cloud-Context': JSON.stringify(context) }
: headers,
body: JSON.stringify({ _method: 'GET', where }),
});
const depthError = (limit = 3) =>
jasmine.objectContaining({
status: 400,
data: {
code: Parse.Error.INVALID_QUERY,
error: `Subquery nesting depth exceeds maximum allowed depth of ${limit}`,
},
});
const builders = {
$inQuery: buildNestedInQuery,
$notInQuery: buildNestedNotInQuery,
$select: buildNestedSelect,
$dontSelect: buildNestedDontSelect,
};

for (const [operator, build] of Object.entries(builders)) {
it(`should reject ${operator} exceeding depth limit when context header sets negative depth`, async () => {
await expectAsync(find(build(4), { _subqueryDepth: -100 })).toBeRejectedWith(
depthError()
);
});
}

for (const value of ['x', {}, -1]) {
it(`should reject $inQuery exceeding depth limit when context header sets depth to ${JSON.stringify(value)}`, async () => {
await expectAsync(
find(buildNestedInQuery(4), { _subqueryDepth: value })
).toBeRejectedWith(depthError());
});
}

it('should reject $inQuery exceeding depth limit when body context sets negative depth', async () => {
let context;
Parse.Cloud.beforeFind('_User', req => {
context = { ...req.context };
});
await expectAsync(
request({
method: 'POST',
url: 'http://localhost:8378/1/classes/_User',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
_method: 'GET',
_ApplicationId: 'test',
_JavaScriptKey: 'test',
_context: { _subqueryDepth: -100 },
where: buildNestedInQuery(4),
}),
})
).toBeRejectedWith(depthError());
expect(context).toEqual({ _subqueryDepth: -100 });
});

it('should reject $inQuery exceeding depth limit when context of rest.find sets negative depth', async () => {
const context = { _subqueryDepth: -100 };
await expectAsync(
rest.find(config, auth.nobody(config), '_User', buildNestedInQuery(4), {}, context)
).toBeRejectedWith(
jasmine.objectContaining({
code: Parse.Error.INVALID_QUERY,
message: 'Subquery nesting depth exceeds maximum allowed depth of 3',
})
);
});

it('should allow $inQuery within depth limit when context header sets depth above limit', async () => {
await expectAsync(find(buildNestedInQuery(3), { _subqueryDepth: 100 })).toBeResolvedTo(
jasmine.objectContaining({ status: 200 })
);
});

it('should pass request context unchanged to beforeFind trigger of subquery', async () => {
const contexts = [];
Parse.Cloud.beforeFind('SubqueryDepthItem', req => {
contexts.push({ ...req.context });
});
const where = { item: { $inQuery: { className: 'SubqueryDepthItem', where: {} } } };
await expectAsync(find(where, { key: 'value' }, 'SubqueryDepthItem')).toBeResolvedTo(
jasmine.objectContaining({ status: 200 })
);
expect(contexts).toEqual([{ key: 'value' }, { key: 'value' }]);
});

for (const [operator, build] of Object.entries(builders)) {
it(`should not pass context changes of ${operator} beforeFind trigger to sibling subquery`, async () => {
const contexts = [];
Parse.Cloud.beforeFind('SubqueryDepthInner', req => {
contexts.push({ ...req.context });
req.context.changed = true;
});
const where = { $or: [build(1, 'SubqueryDepthInner'), build(1, 'SubqueryDepthInner')] };
await expectAsync(find(where, { key: 'value' }, 'SubqueryDepthOuter')).toBeResolvedTo(
jasmine.objectContaining({ status: 200 })
);
expect(contexts).toEqual([{ key: 'value' }, { key: 'value' }]);
});
}

it('should count subquery of included class from depth of including subquery', async () => {
await reconfigureServer({
requestComplexity: { subqueryDepth: 1 },
});
const target = await new Parse.Object('SubqueryDepthTarget').save();
await new Parse.Object('SubqueryDepthInner', { target }).save();
Parse.Cloud.beforeFind('SubqueryDepthInner', req => {
req.query.include('target');
});
Parse.Cloud.beforeFind('SubqueryDepthTarget', req => {
req.query.matchesQuery('item', new Parse.Query('SubqueryDepthOther'));
});
const where = { item: { $inQuery: { className: 'SubqueryDepthInner', where: {} } } };
await expectAsync(find(where, undefined, 'SubqueryDepthOuter')).toBeRejectedWith(
depthError(1)
);
});

it('should not count nesting of outer query for query that trigger runs with request context', async () => {
await reconfigureServer({
requestComplexity: { subqueryDepth: 1 },
});
let triggerResults;
Parse.Cloud.beforeFind('SubqueryDepthInner', async req => {
const query = new Parse.Query('SubqueryDepthOther');
query.matchesQuery('item', new Parse.Query('SubqueryDepthOther'));
triggerResults = await query.find({ context: req.context });
});
const where = { item: { $inQuery: { className: 'SubqueryDepthInner', where: {} } } };
await expectAsync(find(where, undefined, 'SubqueryDepthOuter')).toBeResolvedTo(
jasmine.objectContaining({ status: 200 })
);
expect(triggerResults).toEqual([]);
});
});
});

describe('query depth', () => {
Expand Down
35 changes: 21 additions & 14 deletions src/RestQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const Utils = require('./Utils');
* @param options.runAfterFind {boolean} Whether to run the afterFind trigger
* @param options.runBeforeFind {boolean} Whether to run the beforeFind trigger
* @param options.context {object} The context object for the query
* @param options.subqueryDepth {number} The subquery nesting depth of the query
* @returns {Promise<_UnsafeRestQuery>} A promise that is resolved with the _UnsafeRestQuery object
*/
async function RestQuery({
Expand All @@ -48,6 +49,7 @@ async function RestQuery({
runAfterFind = true,
runBeforeFind = true,
context,
subqueryDepth = 0,
}) {
if (![RestQuery.Method.find, RestQuery.Method.get].includes(method)) {
throw new Parse.Error(Parse.Error.INVALID_QUERY, 'bad query type');
Expand Down Expand Up @@ -75,7 +77,8 @@ async function RestQuery({
result.restOptions || restOptions,
runAfterFind,
context,
isGet
isGet,
subqueryDepth
);
}

Expand All @@ -94,6 +97,8 @@ RestQuery.Method = Object.freeze({
* @param restOptions
* @param runAfterFind
* @param context
* @param isGet
* @param subqueryDepth
*/
function _UnsafeRestQuery(
config,
Expand All @@ -103,7 +108,8 @@ function _UnsafeRestQuery(
restOptions = {},
runAfterFind = true,
context,
isGet
isGet,
subqueryDepth = 0
) {
this.config = config;
this.auth = auth;
Expand All @@ -115,6 +121,7 @@ function _UnsafeRestQuery(
this.findOptions = {};
this.context = context || {};
this.isGet = isGet;
this.subqueryDepth = subqueryDepth;
if (!this.auth.isMaster) {
if (this.className == '_Session') {
if (!this.auth.user) {
Expand Down Expand Up @@ -556,8 +563,7 @@ _UnsafeRestQuery.prototype.checkSubqueryDepth = function () {
if (!rc || rc.subqueryDepth === -1) {
return;
}
const depth = this.context._subqueryDepth || 0;
if (depth > rc.subqueryDepth) {
if (this.subqueryDepth > rc.subqueryDepth) {
const message = `Subquery nesting depth exceeds maximum allowed depth of ${rc.subqueryDepth}`;
logger.warn(message);
throw new Parse.Error(Parse.Error.INVALID_QUERY, message);
Expand Down Expand Up @@ -598,15 +604,15 @@ _UnsafeRestQuery.prototype.replaceInQuery = async function () {
}
}

const childContext = { ...this.context, _subqueryDepth: (this.context._subqueryDepth || 0) + 1 };
const subquery = await RestQuery({
method: RestQuery.Method.find,
config: this.config,
auth: this.auth,
className: inQueryValue.className,
restWhere: inQueryValue.where,
restOptions: additionalOptions,
context: childContext,
context: { ...this.context },
subqueryDepth: this.subqueryDepth + 1,
});
return subquery.execute().then(response => {
transformInQuery(inQueryObject, subquery.className, response.results);
Expand Down Expand Up @@ -666,15 +672,15 @@ _UnsafeRestQuery.prototype.replaceNotInQuery = async function () {
}
}

const childContext = { ...this.context, _subqueryDepth: (this.context._subqueryDepth || 0) + 1 };
const subquery = await RestQuery({
method: RestQuery.Method.find,
config: this.config,
auth: this.auth,
className: notInQueryValue.className,
restWhere: notInQueryValue.where,
restOptions: additionalOptions,
context: childContext,
context: { ...this.context },
subqueryDepth: this.subqueryDepth + 1,
});

return subquery.execute().then(response => {
Expand Down Expand Up @@ -747,15 +753,15 @@ _UnsafeRestQuery.prototype.replaceSelect = async function () {
}
}

const childContext = { ...this.context, _subqueryDepth: (this.context._subqueryDepth || 0) + 1 };
const subquery = await RestQuery({
method: RestQuery.Method.find,
config: this.config,
auth: this.auth,
className: selectValue.query.className,
restWhere: selectValue.query.where,
restOptions: additionalOptions,
context: childContext,
context: { ...this.context },
subqueryDepth: this.subqueryDepth + 1,
});

return subquery.execute().then(response => {
Expand Down Expand Up @@ -818,15 +824,15 @@ _UnsafeRestQuery.prototype.replaceDontSelect = async function () {
}
}

const childContext = { ...this.context, _subqueryDepth: (this.context._subqueryDepth || 0) + 1 };
const subquery = await RestQuery({
method: RestQuery.Method.find,
config: this.config,
auth: this.auth,
className: dontSelectValue.query.className,
restWhere: dontSelectValue.query.where,
restOptions: additionalOptions,
context: childContext,
context: { ...this.context },
subqueryDepth: this.subqueryDepth + 1,
});

return subquery.execute().then(response => {
Expand Down Expand Up @@ -1113,7 +1119,7 @@ _UnsafeRestQuery.prototype.handleInclude = async function () {
path,
this.context,
this.restOptions,
this,
this.subqueryDepth
);
if (pathResponse.then) {
const newResponse = await pathResponse
Expand Down Expand Up @@ -1200,7 +1206,7 @@ _UnsafeRestQuery.prototype.handleAuthAdapters = async function () {
// Adds included values to the response.
// Path is a list of field names.
// Returns a promise for an augmented response.
function includePath(config, auth, response, path, context, restOptions = {}) {
function includePath(config, auth, response, path, context, restOptions = {}, subqueryDepth = 0) {
var pointers = findPointers(response.results, path);
if (pointers.length == 0) {
return response;
Expand Down Expand Up @@ -1280,6 +1286,7 @@ function includePath(config, auth, response, path, context, restOptions = {}) {
restWhere: where,
restOptions: includeRestOptions,
context: context,
subqueryDepth,
});
return query.execute({ op: 'get' }).then(results => {
results.className = className;
Expand Down
Loading