forked from parse-community/parse-server
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRestQuery.spec.js
More file actions
717 lines (656 loc) · 22.7 KB
/
RestQuery.spec.js
File metadata and controls
717 lines (656 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
'use strict';
// These tests check the "find" functionality of the REST API.
const auth = require('../lib/Auth');
const Config = require('../lib/Config');
const rest = require('../lib/rest');
const RestQuery = require('../lib/RestQuery');
const request = require('../lib/request');
const querystring = require('querystring');
let config;
let database;
const nobody = auth.nobody(config);
describe('rest query', () => {
beforeEach(() => {
config = Config.get('test');
database = config.database;
});
it('basic query', done => {
rest
.create(config, nobody, 'TestObject', {})
.then(() => {
return rest.find(config, nobody, 'TestObject', {});
})
.then(response => {
expect(response.results.length).toEqual(1);
done();
});
});
it('query with limit', done => {
rest
.create(config, nobody, 'TestObject', { foo: 'baz' })
.then(() => {
return rest.create(config, nobody, 'TestObject', { foo: 'qux' });
})
.then(() => {
return rest.find(config, nobody, 'TestObject', {}, { limit: 1 });
})
.then(response => {
expect(response.results.length).toEqual(1);
expect(response.results[0].foo).toBeTruthy();
done();
});
});
const data = {
username: 'blah',
password: 'pass',
sessionToken: 'abc123',
};
it_exclude_dbs(['postgres'])(
'query for user w/ legacy credentials without masterKey has them stripped from results',
done => {
database
.create('_User', data)
.then(() => {
return rest.find(config, nobody, '_User');
})
.then(result => {
const user = result.results[0];
expect(user.username).toEqual('blah');
expect(user.sessionToken).toBeUndefined();
expect(user.password).toBeUndefined();
done();
});
}
);
it_exclude_dbs(['postgres'])(
'query for user w/ legacy credentials with masterKey has them stripped from results',
done => {
database
.create('_User', data)
.then(() => {
return rest.find(config, { isMaster: true }, '_User');
})
.then(result => {
const user = result.results[0];
expect(user.username).toEqual('blah');
expect(user.sessionToken).toBeUndefined();
expect(user.password).toBeUndefined();
done();
});
}
);
// Created to test a scenario in AnyPic
it_exclude_dbs(['postgres'])('query with include', done => {
let photo = {
foo: 'bar',
};
let user = {
username: 'aUsername',
password: 'aPassword',
ACL: { '*': { read: true } },
};
const activity = {
type: 'comment',
photo: {
__type: 'Pointer',
className: 'TestPhoto',
objectId: '',
},
fromUser: {
__type: 'Pointer',
className: '_User',
objectId: '',
},
};
const queryWhere = {
photo: {
__type: 'Pointer',
className: 'TestPhoto',
objectId: '',
},
type: 'comment',
};
const queryOptions = {
include: 'fromUser',
order: 'createdAt',
limit: 30,
};
rest
.create(config, nobody, 'TestPhoto', photo)
.then(p => {
photo = p;
return rest.create(config, nobody, '_User', user);
})
.then(u => {
user = u.response;
activity.photo.objectId = photo.objectId;
activity.fromUser.objectId = user.objectId;
return rest.create(config, nobody, 'TestActivity', activity);
})
.then(() => {
queryWhere.photo.objectId = photo.objectId;
return rest.find(config, nobody, 'TestActivity', queryWhere, queryOptions);
})
.then(response => {
const results = response.results;
expect(results.length).toEqual(1);
expect(typeof results[0].objectId).toEqual('string');
expect(typeof results[0].photo).toEqual('object');
expect(typeof results[0].fromUser).toEqual('object');
expect(typeof results[0].fromUser.username).toEqual('string');
done();
})
.catch(error => {
console.log(error);
});
});
it('query non-existent class when disabled client class creation', done => {
const logger = require('../lib/logger').default;
const loggerErrorSpy = spyOn(logger, 'error').and.callThrough();
const customConfig = Object.assign({}, config, {
allowClientClassCreation: false,
});
loggerErrorSpy.calls.reset();
rest.find(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {}).then(
() => {
fail('Should throw an error');
done();
},
err => {
expect(err.code).toEqual(Parse.Error.OPERATION_FORBIDDEN);
expect(err.message).toEqual('Permission denied');
expect(loggerErrorSpy).toHaveBeenCalledWith('Sanitized error:', jasmine.stringContaining('This user is not allowed to access ' + 'non-existent class: ClientClassCreation'));
done();
}
);
});
it('query existent class when disabled client class creation', async () => {
const customConfig = Object.assign({}, config, {
allowClientClassCreation: false,
});
const schema = await config.database.loadSchema();
const actualSchema = await schema.addClassIfNotExists('ClientClassCreation', {});
expect(actualSchema.className).toEqual('ClientClassCreation');
await schema.reloadData({ clearCache: true });
// Should not throw
const result = await rest.find(
customConfig,
auth.nobody(customConfig),
'ClientClassCreation',
{}
);
expect(result.results.length).toEqual(0);
});
it('query internal field', async () => {
const internalFields = [
'_email_verify_token',
'_perishable_token',
'_tombstone',
'_email_verify_token_expires_at',
'_failed_login_count',
'_account_lockout_expires_at',
'_password_changed_at',
'_password_history',
];
// Run rejection and success queries sequentially to avoid orphaned promises
// that can cause unhandled rejections when Promise.all short-circuits
for (const field of internalFields) {
await expectAsync(new Parse.Query(Parse.User).exists(field).find()).toBeRejectedWith(
new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Invalid key name: ${field}`)
);
}
for (const field of internalFields) {
await new Parse.Query(Parse.User).exists(field).find({ useMasterKey: true });
}
});
it('query protected field', async () => {
const user = new Parse.User();
user.setUsername('username1');
user.setPassword('password');
await user.signUp();
const config = Config.get(Parse.applicationId);
const obj = new Parse.Object('Test');
obj.set('owner', user);
obj.set('test', 'test');
obj.set('zip', 1234);
await obj.save();
const schema = await config.database.loadSchema();
await schema.updateClass(
'Test',
{},
{
get: { '*': true },
find: { '*': true },
protectedFields: { [user.id]: ['zip'] },
}
);
await Promise.all([
new Parse.Query('Test').exists('test').find(),
expectAsync(new Parse.Query('Test').exists('zip').find()).toBeRejectedWith(
new Parse.Error(
Parse.Error.OPERATION_FORBIDDEN,
'Permission denied'
)
),
]);
});
it('query protected field with matchesQuery', async () => {
const user = new Parse.User();
user.setUsername('username1');
user.setPassword('password');
await user.signUp();
const test = new Parse.Object('TestObject', { user });
await test.save();
const subQuery = new Parse.Query(Parse.User);
subQuery.exists('_perishable_token');
await expectAsync(
new Parse.Query('TestObject').matchesQuery('user', subQuery).find()
).toBeRejectedWith(
new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'Invalid key name: _perishable_token')
);
});
it('query with wrongly encoded parameter', done => {
rest
.create(config, nobody, 'TestParameterEncode', { foo: 'bar' })
.then(() => {
return rest.create(config, nobody, 'TestParameterEncode', {
foo: 'baz',
});
})
.then(() => {
const headers = {
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
};
const p0 = request({
headers: headers,
url:
'http://localhost:8378/1/classes/TestParameterEncode?' +
querystring
.stringify({
where: '{"foo":{"$ne": "baz"}}',
limit: 1,
})
.replace('=', '%3D'),
}).then(fail, response => {
const error = response.data;
expect(error.code).toEqual(Parse.Error.INVALID_QUERY);
});
const p1 = request({
headers: headers,
url:
'http://localhost:8378/1/classes/TestParameterEncode?' +
querystring
.stringify({
limit: 1,
})
.replace('=', '%3D'),
}).then(fail, response => {
const error = response.data;
expect(error.code).toEqual(Parse.Error.INVALID_QUERY);
});
return Promise.all([p0, p1]);
})
.then(done)
.catch(err => {
jfail(err);
fail('should not fail');
done();
});
});
it('query with limit = 0', done => {
rest
.create(config, nobody, 'TestObject', { foo: 'baz' })
.then(() => {
return rest.create(config, nobody, 'TestObject', { foo: 'qux' });
})
.then(() => {
return rest.find(config, nobody, 'TestObject', {}, { limit: 0 });
})
.then(response => {
expect(response.results.length).toEqual(0);
done();
});
});
it('query with limit = 0 and count = 1', done => {
rest
.create(config, nobody, 'TestObject', { foo: 'baz' })
.then(() => {
return rest.create(config, nobody, 'TestObject', { foo: 'qux' });
})
.then(() => {
return rest.find(config, nobody, 'TestObject', {}, { limit: 0, count: 1 });
})
.then(response => {
expect(response.results.length).toEqual(0);
expect(response.count).toEqual(2);
done();
});
});
it('makes sure null pointers are handed correctly #2189', done => {
const object = new Parse.Object('AnObject');
const anotherObject = new Parse.Object('AnotherObject');
anotherObject
.save()
.then(() => {
object.set('values', [null, null, anotherObject]);
return object.save();
})
.then(() => {
const query = new Parse.Query('AnObject');
query.include('values');
return query.first();
})
.then(
result => {
const values = result.get('values');
expect(values.length).toBe(3);
let anotherObjectFound = false;
let nullCounts = 0;
for (const value of values) {
if (value === null) {
nullCounts++;
} else if (value instanceof Parse.Object) {
anotherObjectFound = true;
}
}
expect(nullCounts).toBe(2);
expect(anotherObjectFound).toBeTruthy();
done();
},
err => {
console.error(err);
fail(err);
done();
}
);
});
it('battle test parallel include with 100 nested includes', async () => {
await reconfigureServer({ requestComplexity: { includeCount: 200 } });
const RootObject = Parse.Object.extend('RootObject');
const Level1Object = Parse.Object.extend('Level1Object');
const Level2Object = Parse.Object.extend('Level2Object');
// Create 100 level2 objects (10 per level1 object)
const level2Objects = [];
for (let i = 0; i < 100; i++) {
const level2 = new Level2Object({
index: i,
value: `level2_${i}`,
});
level2Objects.push(level2);
}
await Parse.Object.saveAll(level2Objects);
// Create 10 level1 objects, each with 10 pointers to level2 objects
const level1Objects = [];
for (let i = 0; i < 10; i++) {
const level1 = new Level1Object({
index: i,
value: `level1_${i}`,
});
// Set 10 pointer fields (level2_0 through level2_9)
for (let j = 0; j < 10; j++) {
level1.set(`level2_${j}`, level2Objects[i * 10 + j]);
}
level1Objects.push(level1);
}
await Parse.Object.saveAll(level1Objects);
// Create 1 root object with 10 pointers to level1 objects
const rootObject = new RootObject({
value: 'root',
});
for (let i = 0; i < 10; i++) {
rootObject.set(`level1_${i}`, level1Objects[i]);
}
await rootObject.save();
// Build include paths: level1_0 through level1_9, and level1_0.level2_0 through level1_9.level2_9
const includePaths = [];
for (let i = 0; i < 10; i++) {
includePaths.push(`level1_${i}`);
for (let j = 0; j < 10; j++) {
includePaths.push(`level1_${i}.level2_${j}`);
}
}
// Query with all includes
const query = new Parse.Query(RootObject);
query.equalTo('objectId', rootObject.id);
for (const path of includePaths) {
query.include(path);
}
console.time('query.find');
const results = await query.find();
console.timeEnd('query.find');
expect(results.length).toBe(1);
const result = results[0];
expect(result.id).toBe(rootObject.id);
// Verify all 10 level1 objects are included
for (let i = 0; i < 10; i++) {
const level1Field = result.get(`level1_${i}`);
expect(level1Field).toBeDefined();
expect(level1Field instanceof Parse.Object).toBe(true);
expect(level1Field.get('index')).toBe(i);
expect(level1Field.get('value')).toBe(`level1_${i}`);
// Verify all 10 level2 objects are included for each level1 object
for (let j = 0; j < 10; j++) {
const level2Field = level1Field.get(`level2_${j}`);
expect(level2Field).toBeDefined();
expect(level2Field instanceof Parse.Object).toBe(true);
expect(level2Field.get('index')).toBe(i * 10 + j);
expect(level2Field.get('value')).toBe(`level2_${i * 10 + j}`);
}
}
});
});
describe('RestQuery.each', () => {
beforeEach(() => {
config = Config.get('test');
});
it_id('3416c90b-ee2e-4bb5-9231-46cd181cd0a2')(it)('should run each', async () => {
const objects = [];
while (objects.length != 10) {
objects.push(new Parse.Object('Object', { value: objects.length }));
}
const config = Config.get('test');
await Parse.Object.saveAll(objects);
const query = await RestQuery({
method: RestQuery.Method.find,
config,
auth: auth.master(config),
className: 'Object',
restWhere: { value: { $gt: 2 } },
restOptions: { limit: 2 },
});
const spy = spyOn(query, 'execute').and.callThrough();
const classSpy = spyOn(RestQuery._UnsafeRestQuery.prototype, 'execute').and.callThrough();
const results = [];
await query.each(result => {
expect(result.value).toBeGreaterThan(2);
results.push(result);
});
expect(spy.calls.count()).toBe(0);
expect(classSpy.calls.count()).toBe(4);
expect(results.length).toBe(7);
});
it_id('0fe22501-4b18-461e-b87d-82ceac4a496e')(it)('should work with query on relations', async () => {
const objectA = new Parse.Object('Letter', { value: 'A' });
const objectB = new Parse.Object('Letter', { value: 'B' });
const object1 = new Parse.Object('Number', { value: '1' });
const object2 = new Parse.Object('Number', { value: '2' });
const object3 = new Parse.Object('Number', { value: '3' });
const object4 = new Parse.Object('Number', { value: '4' });
await Parse.Object.saveAll([object1, object2, object3, object4]);
objectA.relation('numbers').add(object1);
objectB.relation('numbers').add(object2);
await Parse.Object.saveAll([objectA, objectB]);
const config = Config.get('test');
/**
* Two queries needed since objectId are sorted and we can't know which one
* going to be the first and then skip by the $gt added by each
*/
const queryOne = await RestQuery({
method: RestQuery.Method.get,
config,
auth: auth.master(config),
className: 'Letter',
restWhere: {
numbers: {
__type: 'Pointer',
className: 'Number',
objectId: object1.id,
},
},
restOptions: { limit: 1 },
});
const queryTwo = await RestQuery({
method: RestQuery.Method.get,
config,
auth: auth.master(config),
className: 'Letter',
restWhere: {
numbers: {
__type: 'Pointer',
className: 'Number',
objectId: object2.id,
},
},
restOptions: { limit: 1 },
});
const classSpy = spyOn(RestQuery._UnsafeRestQuery.prototype, 'execute').and.callThrough();
const resultsOne = [];
const resultsTwo = [];
await queryOne.each(result => {
resultsOne.push(result);
});
await queryTwo.each(result => {
resultsTwo.push(result);
});
expect(classSpy.calls.count()).toBe(4);
expect(resultsOne.length).toBe(1);
expect(resultsTwo.length).toBe(1);
});
it('test afterSave response object is return', done => {
Parse.Cloud.beforeSave('TestObject2', function (req) {
req.object.set('tobeaddbefore', true);
req.object.set('tobeaddbeforeandremoveafter', true);
});
Parse.Cloud.afterSave('TestObject2', function (req) {
const jsonObject = req.object.toJSON();
delete jsonObject.todelete;
delete jsonObject.tobeaddbeforeandremoveafter;
jsonObject.toadd = true;
return jsonObject;
});
rest.create(config, nobody, 'TestObject2', { todelete: true, tokeep: true }).then(response => {
expect(response.response.toadd).toBeTruthy();
expect(response.response.tokeep).toBeTruthy();
expect(response.response.tobeaddbefore).toBeTruthy();
expect(response.response.tobeaddbeforeandremoveafter).toBeUndefined();
expect(response.response.todelete).toBeUndefined();
done();
});
});
it('test afterSave should not affect save response', async () => {
Parse.Cloud.beforeSave('TestObject2', ({ object }) => {
object.set('addedBeforeSave', true);
});
Parse.Cloud.afterSave('TestObject2', ({ object }) => {
object.set('addedAfterSave', true);
object.unset('initialToRemove');
});
const { response } = await rest.create(config, nobody, 'TestObject2', {
initialSave: true,
initialToRemove: true,
});
expect(Object.keys(response).sort()).toEqual([
'addedAfterSave',
'addedBeforeSave',
'createdAt',
'initialToRemove',
'objectId',
]);
});
});
describe('redirectClassNameForKey security', () => {
let config;
beforeEach(() => {
config = Config.get('test');
});
it('should scope _Session results to the current user when redirected via redirectClassNameForKey', async () => {
// Create two users with sessions (without logging out, to preserve sessions)
const user1 = await Parse.User.signUp('user1', 'password1');
const sessionToken1 = user1.getSessionToken();
// Sign up user2 via REST to avoid logging out user1
await request({
method: 'POST',
url: Parse.serverURL + '/users',
headers: {
'X-Parse-Application-Id': Parse.applicationId,
'X-Parse-REST-API-Key': 'rest',
'Content-Type': 'application/json',
},
body: { username: 'user2', password: 'password2' },
});
// Create a public class with a relation field pointing to _Session
// (using masterKey to create the object and relation schema)
const obj = new Parse.Object('PublicData');
const relation = obj.relation('pivot');
// Add a fake pointer to _Session to establish the relation schema
relation.add(Parse.Object.fromJSON({ className: '_Session', objectId: 'fakeId' }));
await obj.save(null, { useMasterKey: true });
// Authenticated user queries with redirectClassNameForKey
const userAuth = await auth.getAuthForSessionToken({
config,
sessionToken: sessionToken1,
});
const result = await rest.find(config, userAuth, 'PublicData', {}, { redirectClassNameForKey: 'pivot' });
// Should only see user1's own session, not user2's
expect(result.results.length).toBe(1);
expect(result.results[0].user.objectId).toBe(user1.id);
});
it('should reject unauthenticated access to _Session via redirectClassNameForKey', async () => {
// Create a user so a session exists
await Parse.User.signUp('victim', 'password123');
await Parse.User.logOut();
// Create a public class with a relation to _Session
const obj = new Parse.Object('PublicData');
const relation = obj.relation('pivot');
relation.add(Parse.Object.fromJSON({ className: '_Session', objectId: 'fakeId' }));
await obj.save(null, { useMasterKey: true });
// Unauthenticated query with redirectClassNameForKey
await expectAsync(
rest.find(config, auth.nobody(config), 'PublicData', {}, { redirectClassNameForKey: 'pivot' })
).toBeRejectedWith(
jasmine.objectContaining({ code: Parse.Error.INVALID_SESSION_TOKEN })
);
});
it('should block redirectClassNameForKey to master-only classes', async () => {
// Create a public class with a relation to _JobStatus (master-only)
const obj = new Parse.Object('PublicData');
const relation = obj.relation('jobPivot');
relation.add(Parse.Object.fromJSON({ className: '_JobStatus', objectId: 'fakeId' }));
await obj.save(null, { useMasterKey: true });
// Create a user for authenticated access
const user = await Parse.User.signUp('attacker', 'password123');
const sessionToken = user.getSessionToken();
const userAuth = await auth.getAuthForSessionToken({ config, sessionToken });
// Authenticated query should be blocked
await expectAsync(
rest.find(config, userAuth, 'PublicData', {}, { redirectClassNameForKey: 'jobPivot' })
).toBeRejectedWith(
jasmine.objectContaining({ code: Parse.Error.OPERATION_FORBIDDEN })
);
});
it('should allow redirectClassNameForKey between regular classes', async () => {
// Create target class objects
const wheel1 = new Parse.Object('Wheel');
await wheel1.save();
// Create source class with relation to Wheel
const car = new Parse.Object('Car');
const relation = car.relation('wheels');
relation.add(wheel1);
await car.save();
// Query with redirectClassNameForKey should work normally
const result = await rest.find(config, auth.nobody(config), 'Car', {}, { redirectClassNameForKey: 'wheels' });
expect(result.results.length).toBe(1);
expect(result.results[0].objectId).toBe(wheel1.id);
});
});