-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathMiddlewares.spec.js
More file actions
664 lines (601 loc) · 25.6 KB
/
Middlewares.spec.js
File metadata and controls
664 lines (601 loc) · 25.6 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
const middlewares = require('../lib/middlewares');
const AppCache = require('../lib/cache').AppCache;
const { BlockList } = require('net');
const AppCachePut = (appId, config) =>
AppCache.put(appId, {
...config,
maintenanceKeyIpsStore: new Map(),
masterKeyIpsStore: new Map(),
readOnlyMasterKeyIpsStore: new Map(),
});
describe('middlewares', () => {
let fakeReq, fakeRes;
beforeEach(() => {
fakeReq = {
ip: '127.0.0.1',
originalUrl: 'http://example.com/parse/',
url: 'http://example.com/',
body: {
_ApplicationId: 'FakeAppId',
},
headers: {},
get: key => {
return fakeReq.headers[key.toLowerCase()];
},
};
fakeRes = jasmine.createSpyObj('fakeRes', ['end', 'status']);
AppCachePut(fakeReq.body._ApplicationId, {});
});
afterEach(() => {
AppCache.del(fakeReq.body._ApplicationId);
});
it_id('4cc18d90-1763-4725-97fa-f63fb4692fc4')(it)('should use _ContentType if provided', done => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKeyIps: ['127.0.0.1'],
});
expect(fakeReq.headers['content-type']).toEqual(undefined);
const contentType = 'image/jpeg';
fakeReq.body._ContentType = contentType;
middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeReq.headers['content-type']).toEqual(contentType);
expect(fakeReq.body._ContentType).toEqual(undefined);
done();
});
});
it('should give invalid response when keys are configured but no key supplied', async () => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKey: 'masterKey',
restAPIKey: 'restAPIKey',
});
await middlewares.handleParseHeaders(fakeReq, fakeRes);
expect(fakeRes.status).toHaveBeenCalledWith(403);
});
it('should give invalid response when keys are configured but supplied key is incorrect', async () => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKey: 'masterKey',
restAPIKey: 'restAPIKey',
});
fakeReq.headers['x-parse-rest-api-key'] = 'wrongKey';
await middlewares.handleParseHeaders(fakeReq, fakeRes);
expect(fakeRes.status).toHaveBeenCalledWith(403);
});
it('should give invalid response when keys are configured but different key is supplied', async () => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKey: 'masterKey',
restAPIKey: 'restAPIKey',
});
fakeReq.headers['x-parse-client-key'] = 'clientKey';
await middlewares.handleParseHeaders(fakeReq, fakeRes);
expect(fakeRes.status).toHaveBeenCalledWith(403);
});
it('should succeed when any one of the configured keys supplied', done => {
AppCachePut(fakeReq.body._ApplicationId, {
clientKey: 'clientKey',
masterKey: 'masterKey',
restAPIKey: 'restAPIKey',
});
fakeReq.headers['x-parse-rest-api-key'] = 'restAPIKey';
middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeRes.status).not.toHaveBeenCalled();
done();
});
});
it('should succeed when client key supplied but empty', done => {
AppCachePut(fakeReq.body._ApplicationId, {
clientKey: '',
masterKey: 'masterKey',
restAPIKey: 'restAPIKey',
});
fakeReq.headers['x-parse-client-key'] = '';
middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeRes.status).not.toHaveBeenCalled();
done();
});
});
it('should succeed when no keys are configured and none supplied', done => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKey: 'masterKey',
});
middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeRes.status).not.toHaveBeenCalled();
done();
});
});
const BodyParams = {
clientVersion: '_ClientVersion',
installationId: '_InstallationId',
sessionToken: '_SessionToken',
masterKey: '_MasterKey',
javascriptKey: '_JavaScriptKey',
};
const BodyKeys = Object.keys(BodyParams);
BodyKeys.forEach(infoKey => {
const bodyKey = BodyParams[infoKey];
const keyValue = 'Fake' + bodyKey;
// javascriptKey is the only one that gets defaulted,
const otherKeys = BodyKeys.filter(
otherKey => otherKey !== infoKey && otherKey !== 'javascriptKey'
);
it_id('f9abd7ac-b1f4-4607-b9b0-365ff0559d84')(it)(`it should pull ${bodyKey} into req.info`, done => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKeyIps: ['0.0.0.0/0'],
});
fakeReq.ip = '127.0.0.1';
fakeReq.body[bodyKey] = keyValue;
middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeReq.body[bodyKey]).toEqual(undefined);
expect(fakeReq.info[infoKey]).toEqual(keyValue);
otherKeys.forEach(otherKey => {
expect(fakeReq.info[otherKey]).toEqual(undefined);
});
done();
});
});
});
it_id('4a0bce41-c536-4482-a873-12ed023380e2')(it)('should not succeed and log if the ip does not belong to masterKeyIps list', async () => {
const logger = require('../lib/logger').logger;
spyOn(logger, 'error').and.callFake(() => {});
AppCachePut(fakeReq.body._ApplicationId, {
masterKey: 'masterKey',
masterKeyIps: ['10.0.0.1'],
});
fakeReq.ip = '127.0.0.1';
fakeReq.headers['x-parse-master-key'] = 'masterKey';
const error = await middlewares.handleParseHeaders(fakeReq, fakeRes, () => {}).catch(e => e);
expect(error).toBeDefined();
expect(error.message).toEqual(`unauthorized`);
expect(logger.error).toHaveBeenCalledWith(
`Request using master key rejected as the request IP address '127.0.0.1' is not set in Parse Server option 'masterKeyIps'.`
);
});
it('should not succeed and log if the ip does not belong to maintenanceKeyIps list', async () => {
const logger = require('../lib/logger').logger;
spyOn(logger, 'error').and.callFake(() => {});
AppCachePut(fakeReq.body._ApplicationId, {
maintenanceKey: 'masterKey',
maintenanceKeyIps: ['10.0.0.0', '10.0.0.1'],
});
fakeReq.ip = '10.0.0.2';
fakeReq.headers['x-parse-maintenance-key'] = 'masterKey';
const error = await middlewares.handleParseHeaders(fakeReq, fakeRes, () => {}).catch(e => e);
expect(error).toBeDefined();
expect(error.message).toEqual(`unauthorized`);
expect(logger.error).toHaveBeenCalledWith(
`Request using maintenance key rejected as the request IP address '10.0.0.2' is not set in Parse Server option 'maintenanceKeyIps'.`
);
});
it_id('5b8b9280-53ec-445a-b868-6992931d2236')(it)('should reject maintenance key from non-allowed IP instead of downgrading to anonymous auth', async () => {
await reconfigureServer({
maintenanceKeyIps: ['10.0.0.1'],
});
const logger = require('../lib/logger').logger;
spyOn(logger, 'error').and.callFake(() => {});
AppCachePut(fakeReq.body._ApplicationId, {
maintenanceKey: 'maintenanceKey',
maintenanceKeyIps: ['10.0.0.1'],
masterKey: 'masterKey',
masterKeyIps: ['0.0.0.0/0', '::0'],
});
fakeReq.ip = '127.0.0.1';
fakeReq.headers['x-parse-maintenance-key'] = 'maintenanceKey';
const error = await middlewares.handleParseHeaders(fakeReq, fakeRes, () => {}).catch(e => e);
expect(error).toBeDefined();
expect(error.status).toBe(403);
expect(error.message).toEqual('unauthorized');
expect(logger.error).toHaveBeenCalledWith(
`Request using maintenance key rejected as the request IP address '127.0.0.1' is not set in Parse Server option 'maintenanceKeyIps'.`
);
});
it_id('2f7fadec-a87c-4626-90d1-65c75653aea9')(it)('should succeed if the ip does belong to masterKeyIps list', async () => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKey: 'masterKey',
masterKeyIps: ['10.0.0.1'],
});
fakeReq.ip = '10.0.0.1';
fakeReq.headers['x-parse-master-key'] = 'masterKey';
await new Promise(resolve => middlewares.handleParseHeaders(fakeReq, fakeRes, resolve));
expect(fakeReq.auth.isMaster).toBe(true);
});
it_id('2b251fd4-d43c-48f4-ada9-c8458e40c12a')(it)('should allow any ip to use masterKey if masterKeyIps is empty', async () => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKey: 'masterKey',
masterKeyIps: ['0.0.0.0/0'],
});
fakeReq.ip = '10.0.0.1';
fakeReq.headers['x-parse-master-key'] = 'masterKey';
await new Promise(resolve => middlewares.handleParseHeaders(fakeReq, fakeRes, resolve));
expect(fakeReq.auth.isMaster).toBe(true);
});
it('should not succeed and log if the ip does not belong to readOnlyMasterKeyIps list', async () => {
const logger = require('../lib/logger').logger;
spyOn(logger, 'error').and.callFake(() => {});
AppCachePut(fakeReq.body._ApplicationId, {
masterKeyIps: ['0.0.0.0/0'],
readOnlyMasterKey: 'readOnlyMasterKey',
readOnlyMasterKeyIps: ['10.0.0.1'],
});
fakeReq.ip = '127.0.0.1';
fakeReq.headers['x-parse-application-id'] = fakeReq.body._ApplicationId;
fakeReq.headers['x-parse-master-key'] = 'readOnlyMasterKey';
const error = await middlewares.handleParseHeaders(fakeReq, fakeRes, () => {}).catch(e => e);
expect(error).toBeDefined();
expect(error.message).toEqual('unauthorized');
expect(logger.error).toHaveBeenCalledWith(
`Request using read-only master key rejected as the request IP address '127.0.0.1' is not set in Parse Server option 'readOnlyMasterKeyIps'.`
);
});
it('should succeed if the ip does belong to readOnlyMasterKeyIps list', async () => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKeyIps: ['0.0.0.0/0'],
readOnlyMasterKey: 'readOnlyMasterKey',
readOnlyMasterKeyIps: ['10.0.0.1'],
});
fakeReq.ip = '10.0.0.1';
fakeReq.headers['x-parse-application-id'] = fakeReq.body._ApplicationId;
fakeReq.headers['x-parse-master-key'] = 'readOnlyMasterKey';
await new Promise(resolve => middlewares.handleParseHeaders(fakeReq, fakeRes, resolve));
expect(fakeReq.auth.isMaster).toBe(true);
expect(fakeReq.auth.isReadOnly).toBe(true);
});
it('should allow any ip to use readOnlyMasterKey if readOnlyMasterKeyIps is 0.0.0.0/0', async () => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKeyIps: ['0.0.0.0/0'],
readOnlyMasterKey: 'readOnlyMasterKey',
readOnlyMasterKeyIps: ['0.0.0.0/0'],
});
fakeReq.ip = '10.0.0.1';
fakeReq.headers['x-parse-application-id'] = fakeReq.body._ApplicationId;
fakeReq.headers['x-parse-master-key'] = 'readOnlyMasterKey';
await new Promise(resolve => middlewares.handleParseHeaders(fakeReq, fakeRes, resolve));
expect(fakeReq.auth.isMaster).toBe(true);
expect(fakeReq.auth.isReadOnly).toBe(true);
});
it('can set trust proxy', async () => {
const server = await reconfigureServer({ trustProxy: 1 });
expect(server.app.parent.settings['trust proxy']).toBe(1);
});
it('should properly expose the headers', () => {
const headers = {};
const res = {
header: (key, value) => {
headers[key] = value;
},
};
const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);
allowCrossDomain(fakeReq, res, () => {});
expect(Object.keys(headers).length).toBe(4);
expect(headers['Access-Control-Expose-Headers']).toBe(
'X-Parse-Job-Status-Id, X-Parse-Push-Status-Id'
);
});
it('should set default Access-Control-Allow-Headers if allowHeaders are empty', () => {
AppCachePut(fakeReq.body._ApplicationId, {
allowHeaders: undefined,
});
const headers = {};
const res = {
header: (key, value) => {
headers[key] = value;
},
};
const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS);
AppCachePut(fakeReq.body._ApplicationId, {
allowHeaders: [],
});
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS);
});
it('should append custom headers to Access-Control-Allow-Headers if allowHeaders provided', () => {
AppCachePut(fakeReq.body._ApplicationId, {
allowHeaders: ['Header-1', 'Header-2'],
});
const headers = {};
const res = {
header: (key, value) => {
headers[key] = value;
},
};
const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Headers']).toContain('Header-1, Header-2');
expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS);
});
it('should append configured header aliases to Access-Control-Allow-Headers', () => {
AppCachePut(fakeReq.body._ApplicationId, {
headerAliases: {
'X-Parse-Application-Id': ['X-App-Id'],
'X-Parse-Session-Token': ['X-Session-Token-Alias'],
},
});
const headers = {};
const res = {
header: (key, value) => {
headers[key] = value;
},
};
const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Headers']).toContain('X-App-Id');
expect(headers['Access-Control-Allow-Headers']).toContain('X-Session-Token-Alias');
});
it('should set default Access-Control-Allow-Origin if allowOrigin is empty', () => {
AppCachePut(fakeReq.body._ApplicationId, {
allowOrigin: undefined,
});
const headers = {};
const res = {
header: (key, value) => {
headers[key] = value;
},
};
const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Origin']).toEqual('*');
});
it('should set custom origin to Access-Control-Allow-Origin if allowOrigin is provided', () => {
AppCachePut(fakeReq.body._ApplicationId, {
allowOrigin: 'https://parseplatform.org/',
});
const headers = {};
const res = {
header: (key, value) => {
headers[key] = value;
},
};
const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Origin']).toEqual('https://parseplatform.org/');
});
it('should support multiple origins if several are defined in allowOrigin as an array', () => {
AppCache.put(fakeReq.body._ApplicationId, {
allowOrigin: ['https://a.com', 'https://b.com', 'https://c.com'],
});
const headers = {};
const res = {
header: (key, value) => {
headers[key] = value;
},
};
const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId);
// Test with the first domain
fakeReq.headers.origin = 'https://a.com';
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Origin']).toEqual('https://a.com');
// Test with the second domain
fakeReq.headers.origin = 'https://b.com';
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Origin']).toEqual('https://b.com');
// Test with the third domain
fakeReq.headers.origin = 'https://c.com';
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Origin']).toEqual('https://c.com');
// Test with an unauthorized domain
fakeReq.headers.origin = 'https://unauthorized.com';
allowCrossDomain(fakeReq, res, () => {});
expect(headers['Access-Control-Allow-Origin']).toEqual('https://a.com');
});
it('should use user provided on field userFromJWT', done => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKey: 'masterKey',
});
fakeReq.userFromJWT = 'fake-user';
middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeReq.auth.user).toEqual('fake-user');
done();
});
});
it('should resolve app id from configured header alias', done => {
AppCachePut(fakeReq.body._ApplicationId, {
headerAliases: {
'X-Parse-Application-Id': ['X-App-Id'],
},
masterKeyIps: ['0.0.0.0/0'],
});
fakeReq.headers['x-app-id'] = fakeReq.body._ApplicationId;
middlewares.handleHeaderAliases(fakeReq.body._ApplicationId)(fakeReq, fakeRes, () => {
expect(fakeReq.headers['x-parse-application-id']).toEqual(fakeReq.body._ApplicationId);
middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeReq.info.appId).toEqual(fakeReq.body._ApplicationId);
done();
});
});
});
it('should resolve session token from configured header alias', done => {
const sessionToken = 'session-token-via-alias';
AppCachePut(fakeReq.body._ApplicationId, {
headerAliases: {
'X-Parse-Session-Token': ['X-Session-Token-Alias'],
},
masterKeyIps: ['0.0.0.0/0'],
});
fakeReq.headers['x-session-token-alias'] = sessionToken;
middlewares.handleHeaderAliases(fakeReq.body._ApplicationId)(fakeReq, fakeRes, () => {
middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeReq.info.sessionToken).toEqual(sessionToken);
done();
});
});
});
it('should resolve master key from configured alias in handleParseAuth', async () => {
AppCachePut(fakeReq.body._ApplicationId, {
headerAliases: {
'X-Parse-Master-Key': ['X-Master-Key-Alias'],
},
masterKey: 'masterKey',
masterKeyIps: ['0.0.0.0/0'],
});
fakeReq.headers['x-master-key-alias'] = 'masterKey';
await new Promise(resolve =>
middlewares.handleHeaderAliases(fakeReq.body._ApplicationId)(fakeReq, fakeRes, resolve)
);
await new Promise(resolve =>
middlewares.handleParseAuth(fakeReq.body._ApplicationId)(fakeReq, fakeRes, resolve)
);
expect(fakeReq.auth.isMaster).toBe(true);
});
it('should give invalid response when upload file without x-parse-application-id in header', () => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKey: 'masterKey',
});
fakeReq.body = Buffer.from('fake-file');
middlewares.handleParseHeaders(fakeReq, fakeRes);
expect(fakeRes.status).toHaveBeenCalledWith(403);
});
it('should match address', () => {
const ipv6 = '2001:0db8:85a3:0000:0000:8a2e:0370:7334';
const anotherIpv6 = '::ffff:101.10.0.1';
const ipv4 = '192.168.0.101';
const localhostV6 = '::1';
const localhostV62 = '::ffff:127.0.0.1';
const localhostV4 = '127.0.0.1';
const v6 = [ipv6, anotherIpv6];
v6.forEach(ip => {
expect(middlewares.checkIp(ip, ['::/0'], new Map())).toBe(true);
expect(middlewares.checkIp(ip, ['::'], new Map())).toBe(true);
expect(middlewares.checkIp(ip, ['0.0.0.0'], new Map())).toBe(false);
expect(middlewares.checkIp(ip, ['0.0.0.0/0'], new Map())).toBe(false);
expect(middlewares.checkIp(ip, ['123.123.123.123'], new Map())).toBe(false);
});
expect(middlewares.checkIp(ipv6, [anotherIpv6], new Map())).toBe(false);
expect(middlewares.checkIp(ipv6, [ipv6], new Map())).toBe(true);
expect(middlewares.checkIp(ipv6, ['2001:db8:85a3:0:0:8a2e:0:0/100'], new Map())).toBe(true);
expect(middlewares.checkIp(ipv4, ['::'], new Map())).toBe(false);
expect(middlewares.checkIp(ipv4, ['::/0'], new Map())).toBe(false);
expect(middlewares.checkIp(ipv4, ['0.0.0.0'], new Map())).toBe(true);
expect(middlewares.checkIp(ipv4, ['0.0.0.0/0'], new Map())).toBe(true);
expect(middlewares.checkIp(ipv4, ['123.123.123.123'], new Map())).toBe(false);
expect(middlewares.checkIp(ipv4, [ipv4], new Map())).toBe(true);
expect(middlewares.checkIp(ipv4, ['192.168.0.0/24'], new Map())).toBe(true);
expect(middlewares.checkIp(localhostV4, ['::1'], new Map())).toBe(false);
expect(middlewares.checkIp(localhostV6, ['::1'], new Map())).toBe(true);
// ::ffff:127.0.0.1 is a padded ipv4 address but not ::1
expect(middlewares.checkIp(localhostV62, ['::1'], new Map())).toBe(false);
// ::ffff:127.0.0.1 is a padded ipv4 address and is a match for 127.0.0.1
expect(middlewares.checkIp(localhostV62, ['127.0.0.1'], new Map())).toBe(true);
});
describe('body field type validation', () => {
beforeEach(() => {
AppCachePut(fakeReq.body._ApplicationId, {
masterKeyIps: ['0.0.0.0/0'],
});
});
it('should reject non-string _SessionToken in body', async () => {
fakeReq.body._SessionToken = { toString: 'evil' };
await middlewares.handleParseHeaders(fakeReq, fakeRes);
expect(fakeRes.status).toHaveBeenCalledWith(403);
});
it('should reject non-string _ClientVersion in body', async () => {
fakeReq.body._ClientVersion = { toLowerCase: 'evil' };
await middlewares.handleParseHeaders(fakeReq, fakeRes);
expect(fakeRes.status).toHaveBeenCalledWith(403);
});
it('should reject non-string _InstallationId in body', async () => {
fakeReq.body._InstallationId = { toString: 'evil' };
await middlewares.handleParseHeaders(fakeReq, fakeRes);
expect(fakeRes.status).toHaveBeenCalledWith(403);
});
it('should reject non-string _ContentType in body', async () => {
fakeReq.body._ContentType = { toString: 'evil' };
await middlewares.handleParseHeaders(fakeReq, fakeRes);
expect(fakeRes.status).toHaveBeenCalledWith(403);
});
it('should reject non-string base64 in file-via-JSON upload', async () => {
fakeReq.body = Buffer.from(
JSON.stringify({
_ApplicationId: 'FakeAppId',
base64: { toString: 'evil' },
})
);
await middlewares.handleParseHeaders(fakeReq, fakeRes);
expect(fakeRes.status).toHaveBeenCalledWith(403);
});
it('should not crash the server process on non-string body fields', async () => {
// Verify that type confusion in body fields does not crash the Node.js process.
// Each request should be handled independently without affecting server stability.
const payloads = [
{ _SessionToken: { toString: 'evil' } },
{ _ClientVersion: { toLowerCase: 'evil' } },
{ _InstallationId: [1, 2, 3] },
{ _ContentType: { toString: 'evil' } },
];
for (const payload of payloads) {
const req = {
ip: '127.0.0.1',
originalUrl: 'http://example.com/parse/',
url: 'http://example.com/',
body: { _ApplicationId: 'FakeAppId', ...payload },
headers: {},
get: key => req.headers[key.toLowerCase()],
};
const res = jasmine.createSpyObj('res', ['end', 'status']);
await middlewares.handleParseHeaders(req, res);
expect(res.status).toHaveBeenCalledWith(403);
}
// Server process is still alive — a subsequent valid request works
const validReq = {
ip: '127.0.0.1',
originalUrl: 'http://example.com/parse/',
url: 'http://example.com/',
body: { _ApplicationId: 'FakeAppId' },
headers: {},
get: key => validReq.headers[key.toLowerCase()],
};
const validRes = jasmine.createSpyObj('validRes', ['end', 'status']);
let nextCalled = false;
await middlewares.handleParseHeaders(validReq, validRes, () => {
nextCalled = true;
});
expect(nextCalled).toBe(true);
expect(validRes.status).not.toHaveBeenCalled();
});
it('should still accept valid string body fields', done => {
fakeReq.body._SessionToken = 'r:validtoken';
fakeReq.body._ClientVersion = 'js1.0.0';
fakeReq.body._InstallationId = 'install123';
fakeReq.body._ContentType = 'application/json';
middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeReq.info.sessionToken).toEqual('r:validtoken');
expect(fakeReq.info.clientVersion).toEqual('js1.0.0');
expect(fakeReq.info.installationId).toEqual('install123');
expect(fakeReq.headers['content-type']).toEqual('application/json');
done();
});
});
});
it('should match address with cache', () => {
const ipv6 = '2001:0db8:85a3:0000:0000:8a2e:0370:7334';
const cache1 = new Map();
const spyBlockListCheck = spyOn(BlockList.prototype, 'check').and.callThrough();
expect(middlewares.checkIp(ipv6, ['::'], cache1)).toBe(true);
expect(cache1.get('2001:0db8:85a3:0000:0000:8a2e:0370:7334')).toBe(undefined);
expect(cache1.get('allowAllIpv6')).toBe(true);
expect(spyBlockListCheck).toHaveBeenCalledTimes(0);
const cache2 = new Map();
expect(middlewares.checkIp('::1', ['::1'], cache2)).toBe(true);
expect(cache2.get('::1')).toBe(true);
expect(spyBlockListCheck).toHaveBeenCalledTimes(1);
expect(middlewares.checkIp('::1', ['::1'], cache2)).toBe(true);
expect(spyBlockListCheck).toHaveBeenCalledTimes(1);
spyBlockListCheck.calls.reset();
const cache3 = new Map();
expect(middlewares.checkIp('127.0.0.1', ['127.0.0.1'], cache3)).toBe(true);
expect(cache3.get('127.0.0.1')).toBe(true);
expect(spyBlockListCheck).toHaveBeenCalledTimes(1);
expect(middlewares.checkIp('127.0.0.1', ['127.0.0.1'], cache3)).toBe(true);
expect(spyBlockListCheck).toHaveBeenCalledTimes(1);
spyBlockListCheck.calls.reset();
const cache4 = new Map();
const ranges = ['127.0.0.1', '192.168.0.0/24'];
// should not cache negative match
expect(middlewares.checkIp('123.123.123.123', ranges, cache4)).toBe(false);
expect(cache4.get('123.123.123.123')).toBe(undefined);
expect(spyBlockListCheck).toHaveBeenCalledTimes(1);
spyBlockListCheck.calls.reset();
// should not cache cidr
expect(middlewares.checkIp('192.168.0.101', ranges, cache4)).toBe(true);
expect(cache4.get('192.168.0.101')).toBe(undefined);
expect(spyBlockListCheck).toHaveBeenCalledTimes(1);
});
});