-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathParseGraphQLServer.spec.js
More file actions
12353 lines (11485 loc) · 414 KB
/
ParseGraphQLServer.spec.js
File metadata and controls
12353 lines (11485 loc) · 414 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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const http = require('http');
const express = require('express');
const req = require('../lib/request');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const FormData = require('form-data');
require('./helper');
const { updateCLP } = require('./support/dev');
const Utils = require('../lib/Utils');
const pluralize = require('pluralize');
const createUploadLink = (...args) => import('apollo-upload-client/createUploadLink.mjs').then(({ default: fn }) => fn(...args));
const { mergeSchemas } = require('@graphql-tools/schema');
const {
ApolloClient,
InMemoryCache,
ApolloLink,
createHttpLink,
} = require('@apollo/client/core');
const gql = require('graphql-tag');
const { toGlobalId } = require('graphql-relay');
const {
GraphQLObjectType,
GraphQLString,
GraphQLNonNull,
GraphQLEnumType,
GraphQLInputObjectType,
GraphQLSchema,
GraphQLList,
} = require('graphql');
const { ParseServer } = require('../');
const { ParseGraphQLServer, getCSRFRequestHeaders } = require('../lib/GraphQL/ParseGraphQLServer');
const { ReadPreference, Collection } = require('mongodb');
let uuidv4;
function handleError(e) {
if (e && e.networkError && e.networkError.result && e.networkError.result.errors) {
fail(e.networkError.result.errors);
} else {
fail(e);
}
}
describe('ParseGraphQLServer', () => {
let parseServer;
let parseGraphQLServer;
let loggerErrorSpy;
beforeAll(async () => {
({ v4: uuidv4 } = await import('uuid'));
});
beforeEach(async () => {
parseServer = await global.reconfigureServer({
maintenanceKey: 'test2',
maxUploadSize: '1kb',
});
parseGraphQLServer = new ParseGraphQLServer(parseServer, {
graphQLPath: '/graphql',
playgroundPath: '/playground',
});
const logger = require('../lib/logger').default;
loggerErrorSpy = spyOn(logger, 'error').and.callThrough();
});
describe('constructor', () => {
it('should require a parseServer instance', () => {
expect(() => new ParseGraphQLServer()).toThrow('You must provide a parseServer instance!');
});
it('should require config.graphQLPath', () => {
expect(() => new ParseGraphQLServer(parseServer)).toThrow(
'You must provide a config.graphQLPath!'
);
expect(() => new ParseGraphQLServer(parseServer, {})).toThrow(
'You must provide a config.graphQLPath!'
);
});
it('should only require parseServer and config.graphQLPath args', () => {
let parseGraphQLServer;
expect(() => {
parseGraphQLServer = new ParseGraphQLServer(parseServer, {
graphQLPath: 'graphql',
});
}).not.toThrow();
expect(parseGraphQLServer.parseGraphQLSchema).toBeDefined();
expect(parseGraphQLServer.parseGraphQLSchema.databaseController).toEqual(
parseServer.config.databaseController
);
});
it('should initialize parseGraphQLSchema with a log controller', async () => {
const loggerAdapter = {
log: () => { },
error: () => { },
};
const parseServer = await global.reconfigureServer({
loggerAdapter,
});
const parseGraphQLServer = new ParseGraphQLServer(parseServer, {
graphQLPath: 'graphql',
});
expect(parseGraphQLServer.parseGraphQLSchema.log.adapter).toBe(loggerAdapter);
});
});
describe('_getServer', () => {
it('should only return new server on schema changes', async () => {
parseGraphQLServer.server = undefined;
const server1 = await parseGraphQLServer._getServer();
const server2 = await parseGraphQLServer._getServer();
expect(server1).toBe(server2);
// Trigger a schema change
const obj = new Parse.Object('SomeClass');
await obj.save();
const server3 = await parseGraphQLServer._getServer();
const server4 = await parseGraphQLServer._getServer();
expect(server3).not.toBe(server2);
expect(server3).toBe(server4);
});
it('should return same server reference when called 100 times in parallel', async () => {
parseGraphQLServer.server = undefined;
// Call _getServer 100 times in parallel
const promises = Array.from({ length: 100 }, () => parseGraphQLServer._getServer());
const servers = await Promise.all(promises);
// All resolved servers should be the same reference
const firstServer = servers[0];
servers.forEach((server, index) => {
expect(server).toBe(firstServer);
});
});
it('should include application-id header aliases in GraphQL CSRF request headers', () => {
const headers = getCSRFRequestHeaders({
'X-Parse-Application-Id': ['X-App-Id', 'X-Client-App'],
});
expect(headers).toEqual(['X-Parse-Application-Id', 'X-App-Id', 'X-Client-App']);
});
});
describe('_getGraphQLOptions', () => {
const req = {
info: new Object(),
config: new Object(),
auth: new Object(),
get: () => { },
};
const res = {
set: () => { },
};
it_id('0696675e-060f-414f-bc77-9d57f31807f5')(it)('should return schema and context with req\'s info, config and auth', async () => {
const options = await parseGraphQLServer._getGraphQLOptions();
expect(options.schema).toEqual(parseGraphQLServer.parseGraphQLSchema.graphQLSchema);
const contextResponse = await options.context({ req, res });
expect(contextResponse.info).toEqual(req.info);
expect(contextResponse.config).toEqual(req.config);
expect(contextResponse.auth).toEqual(req.auth);
});
it('should load GraphQL schema in every call', async () => {
const originalLoad = parseGraphQLServer.parseGraphQLSchema.load;
let counter = 0;
parseGraphQLServer.parseGraphQLSchema.load = () => ++counter;
expect((await parseGraphQLServer._getGraphQLOptions(req)).schema).toEqual(1);
expect((await parseGraphQLServer._getGraphQLOptions(req)).schema).toEqual(2);
expect((await parseGraphQLServer._getGraphQLOptions(req)).schema).toEqual(3);
parseGraphQLServer.parseGraphQLSchema.load = originalLoad;
});
});
describe('_transformMaxUploadSizeToBytes', () => {
it('should transform to bytes', () => {
expect(parseGraphQLServer._transformMaxUploadSizeToBytes('20mb')).toBe(20971520);
expect(parseGraphQLServer._transformMaxUploadSizeToBytes('333Gb')).toBe(357556027392);
expect(parseGraphQLServer._transformMaxUploadSizeToBytes('123456KB')).toBe(126418944);
});
});
describe('applyGraphQL', () => {
it('should require an Express.js app instance', () => {
expect(() => parseGraphQLServer.applyGraphQL()).toThrow(
'You must provide an Express.js app instance!'
);
expect(() => parseGraphQLServer.applyGraphQL({})).toThrow(
'You must provide an Express.js app instance!'
);
expect(() => parseGraphQLServer.applyGraphQL(new express())).not.toThrow();
});
it('should apply middlewares at config.graphQLPath', () => {
let useCount = 0;
expect(() =>
new ParseGraphQLServer(parseServer, {
graphQLPath: 'somepath',
}).applyGraphQL({
use: path => {
useCount++;
expect(path).toEqual('somepath');
},
})
).not.toThrow();
expect(useCount).toBeGreaterThan(0);
});
it('registers header alias normalization before parse header handling', async () => {
const parseServerWithAliases = await global.reconfigureServer({
maintenanceKey: 'test2',
maxUploadSize: '1kb',
headerAliases: {
'X-Parse-Application-Id': ['X-App-Id'],
},
});
const graphQLServerWithAliases = new ParseGraphQLServer(parseServerWithAliases, {
graphQLPath: '/graphql',
playgroundPath: '/playground',
});
const middlewares = require('../lib/middlewares');
const useCalls = [];
const app = {
use: (...args) => {
useCalls.push(args);
},
};
graphQLServerWithAliases.applyGraphQL(app);
const parseHeadersIndex = useCalls.findIndex(
([path, middleware]) => path === '/graphql' && middleware === middlewares.handleParseHeaders
);
expect(parseHeadersIndex).toBeGreaterThan(0);
const [path, aliasMiddleware] = useCalls[parseHeadersIndex - 1];
expect(path).toBe('/graphql');
const req = {
originalUrl: '/graphql',
url: '/graphql',
protocol: 'http',
headers: {
host: 'localhost',
'x-app-id': parseServerWithAliases.config.appId,
},
get: key => req.headers[key.toLowerCase()],
};
await new Promise(resolve => aliasMiddleware(req, {}, resolve));
expect(req.headers['x-parse-application-id']).toBe(parseServerWithAliases.config.appId);
});
});
describe('applyPlayground', () => {
it('should require an Express.js app instance', () => {
expect(() => parseGraphQLServer.applyPlayground()).toThrow(
'You must provide an Express.js app instance!'
);
expect(() => parseGraphQLServer.applyPlayground({})).toThrow(
'You must provide an Express.js app instance!'
);
expect(() => parseGraphQLServer.applyPlayground(new express())).not.toThrow();
});
it('should require initialization with config.playgroundPath', () => {
expect(() =>
new ParseGraphQLServer(parseServer, {
graphQLPath: 'graphql',
}).applyPlayground(new express())
).toThrow('You must provide a config.playgroundPath to applyPlayground!');
});
it('should apply middlewares at config.playgroundPath', () => {
let useCount = 0;
expect(() =>
new ParseGraphQLServer(parseServer, {
graphQLPath: 'graphQL',
playgroundPath: 'somepath',
}).applyPlayground({
get: path => {
useCount++;
expect(path).toEqual('somepath');
},
})
).not.toThrow();
expect(useCount).toBeGreaterThan(0);
});
});
describe('setGraphQLConfig', () => {
let parseGraphQLServer;
beforeEach(() => {
parseGraphQLServer = new ParseGraphQLServer(parseServer, {
graphQLPath: 'graphql',
});
});
it('should pass the graphQLConfig onto the parseGraphQLController', async () => {
let received;
parseGraphQLServer.parseGraphQLController = {
async updateGraphQLConfig(graphQLConfig) {
received = graphQLConfig;
return {};
},
};
const graphQLConfig = { enabledForClasses: [] };
await parseGraphQLServer.setGraphQLConfig(graphQLConfig);
expect(received).toBe(graphQLConfig);
});
it('should not absorb exceptions from parseGraphQLController', async () => {
parseGraphQLServer.parseGraphQLController = {
async updateGraphQLConfig() {
throw new Error('Network request failed');
},
};
await expectAsync(parseGraphQLServer.setGraphQLConfig({})).toBeRejectedWith(
new Error('Network request failed')
);
});
it('should return the response from parseGraphQLController', async () => {
parseGraphQLServer.parseGraphQLController = {
async updateGraphQLConfig() {
return { response: { result: true } };
},
};
await expectAsync(parseGraphQLServer.setGraphQLConfig({})).toBeResolvedTo({
response: { result: true },
});
});
});
describe('Auto API', () => {
let httpServer;
let parseLiveQueryServer;
const headers = {
'X-Parse-Application-Id': 'test',
'X-Parse-Javascript-Key': 'test',
};
let apolloClient;
let user1;
let user2;
let user3;
let user4;
let user5;
let role;
let object1;
let object2;
let object3;
let object4;
let objects = [];
async function prepareData() {
const acl = new Parse.ACL();
acl.setPublicReadAccess(true);
user1 = new Parse.User();
user1.setUsername('user1');
user1.setPassword('user1');
user1.setEmail('user1@user1.user1');
user1.setACL(acl);
await user1.signUp();
user2 = new Parse.User();
user2.setUsername('user2');
user2.setPassword('user2');
user2.setACL(acl);
await user2.signUp();
user3 = new Parse.User();
user3.setUsername('user3');
user3.setPassword('user3');
user3.setACL(acl);
await user3.signUp();
user4 = new Parse.User();
user4.setUsername('user4');
user4.setPassword('user4');
user4.setACL(acl);
await user4.signUp();
user5 = new Parse.User();
user5.setUsername('user5');
user5.setPassword('user5');
user5.setACL(acl);
await user5.signUp();
const roleACL = new Parse.ACL();
roleACL.setPublicReadAccess(true);
role = new Parse.Role();
role.setName('role');
role.setACL(roleACL);
role.getUsers().add(user1);
role.getUsers().add(user3);
role = await role.save();
const schemaController = await parseServer.config.databaseController.loadSchema();
try {
await schemaController.addClassIfNotExists(
'GraphQLClass',
{
someField: { type: 'String' },
pointerToUser: { type: 'Pointer', targetClass: '_User' },
},
{
find: {
'role:role': true,
[user1.id]: true,
[user2.id]: true,
},
create: {
'role:role': true,
[user1.id]: true,
[user2.id]: true,
},
get: {
'role:role': true,
[user1.id]: true,
[user2.id]: true,
},
update: {
'role:role': true,
[user1.id]: true,
[user2.id]: true,
},
addField: {
'role:role': true,
[user1.id]: true,
[user2.id]: true,
},
delete: {
'role:role': true,
[user1.id]: true,
[user2.id]: true,
},
readUserFields: ['pointerToUser'],
writeUserFields: ['pointerToUser'],
},
{}
);
} catch (err) {
if (!(err instanceof Parse.Error) || err.message !== 'Class GraphQLClass already exists.') {
throw err;
}
}
object1 = new Parse.Object('GraphQLClass');
object1.set('someField', 'someValue1');
object1.set('someOtherField', 'A');
const object1ACL = new Parse.ACL();
object1ACL.setPublicReadAccess(false);
object1ACL.setPublicWriteAccess(false);
object1ACL.setRoleReadAccess(role, true);
object1ACL.setRoleWriteAccess(role, true);
object1ACL.setReadAccess(user1.id, true);
object1ACL.setWriteAccess(user1.id, true);
object1ACL.setReadAccess(user2.id, true);
object1ACL.setWriteAccess(user2.id, true);
object1.setACL(object1ACL);
await object1.save(undefined, { useMasterKey: true });
object2 = new Parse.Object('GraphQLClass');
object2.set('someField', 'someValue2');
object2.set('someOtherField', 'A');
const object2ACL = new Parse.ACL();
object2ACL.setPublicReadAccess(false);
object2ACL.setPublicWriteAccess(false);
object2ACL.setReadAccess(user1.id, true);
object2ACL.setWriteAccess(user1.id, true);
object2ACL.setReadAccess(user2.id, true);
object2ACL.setWriteAccess(user2.id, true);
object2ACL.setReadAccess(user5.id, true);
object2ACL.setWriteAccess(user5.id, true);
object2.setACL(object2ACL);
await object2.save(undefined, { useMasterKey: true });
object3 = new Parse.Object('GraphQLClass');
object3.set('someField', 'someValue3');
object3.set('someOtherField', 'B');
object3.set('pointerToUser', user5);
await object3.save(undefined, { useMasterKey: true });
object4 = new Parse.Object('PublicClass');
object4.set('someField', 'someValue4');
await object4.save();
objects = [];
objects.push(object1, object2, object3, object4);
}
async function createGQLFromParseServer(_parseServer, parseGraphQLServerOptions) {
if (parseLiveQueryServer) {
await parseLiveQueryServer.server.close();
}
if (httpServer) {
await httpServer.close();
}
const expressApp = express();
httpServer = http.createServer(expressApp);
expressApp.use('/parse', _parseServer.app);
parseLiveQueryServer = await ParseServer.createLiveQueryServer(httpServer, {
port: 1338,
});
parseGraphQLServer = new ParseGraphQLServer(_parseServer, {
graphQLPath: '/graphql',
playgroundPath: '/playground',
...parseGraphQLServerOptions,
});
parseGraphQLServer.applyGraphQL(expressApp);
parseGraphQLServer.applyPlayground(expressApp);
await new Promise(resolve => httpServer.listen({ port: 13377 }, resolve));
}
beforeEach(async () => {
await createGQLFromParseServer(parseServer);
const httpLink = await createUploadLink({
uri: 'http://localhost:13377/graphql',
fetch,
headers,
});
apolloClient = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: 'no-cache',
},
},
});
spyOn(console, 'warn').and.callFake(() => { });
spyOn(console, 'error').and.callFake(() => { });
});
afterEach(async () => {
await parseLiveQueryServer.server.close();
await httpServer.close();
});
describe('GraphQL', () => {
it('should be healthy', async () => {
try {
const health = (
await apolloClient.query({
query: gql`
query Health {
health
}
`,
})
).data.health;
expect(health).toBeTruthy();
} catch (e) {
handleError(e);
}
});
it('should be cors enabled', async () => {
let checked = false;
const apolloClient = new ApolloClient({
link: new ApolloLink((operation, forward) => {
return forward(operation).map(response => {
const context = operation.getContext();
const {
response: { headers },
} = context;
expect(headers.get('access-control-allow-origin')).toEqual('*');
checked = true;
return response;
});
}).concat(
createHttpLink({
uri: 'http://localhost:13377/graphql',
fetch,
headers: {
...headers,
Origin: 'http://example.com',
},
})
),
cache: new InMemoryCache(),
});
const healthResponse = await apolloClient.query({
query: gql`
query Health {
health
}
`,
});
expect(healthResponse.data.health).toBeTruthy();
expect(checked).toBeTruthy();
});
it('should handle Parse headers', async () => {
const test = {
context: ({ req: { info, config, auth } }) => {
expect(req.info).toBeDefined();
expect(req.config).toBeDefined();
expect(req.auth).toBeDefined();
return {
info,
config,
auth,
};
},
};
const contextSpy = spyOn(test, 'context');
const originalGetGraphQLOptions = parseGraphQLServer._getGraphQLOptions;
parseGraphQLServer._getGraphQLOptions = async () => {
return {
schema: await parseGraphQLServer.parseGraphQLSchema.load(),
context: test.context,
};
};
const health = (
await apolloClient.query({
query: gql`
query Health {
health
}
`,
})
).data.health;
expect(health).toBeTruthy();
expect(contextSpy).toHaveBeenCalledTimes(1);
parseGraphQLServer._getGraphQLOptions = originalGetGraphQLOptions;
});
});
describe('Playground', () => {
it('should mount playground', async () => {
const res = await req({
method: 'GET',
url: 'http://localhost:13377/playground',
});
expect(res.status).toEqual(200);
});
});
describe('Schema', () => {
const resetGraphQLCache = async () => {
await Promise.all([
parseGraphQLServer.parseGraphQLController.cacheController.graphQL.clear(),
parseGraphQLServer.parseGraphQLSchema.schemaCache.clear(),
]);
};
describe('Context', () => {
it('should support dependency injection on graphql api', async () => {
const requestContextMiddleware = (req, res, next) => {
req.config.aCustomController = 'aCustomController';
next();
};
let called;
const parseServer = await reconfigureServer({ requestContextMiddleware });
await createGQLFromParseServer(parseServer);
Parse.Cloud.beforeSave('_User', request => {
expect(request.config.aCustomController).toEqual('aCustomController');
called = true;
});
await apolloClient.query({
query: gql`
mutation {
createUser(input: { fields: { username: "test", password: "test" } }) {
user {
objectId
}
}
}
`,
context: {
headers: {
'X-Parse-Master-Key': 'test',
},
}
})
expect(called).toBe(true);
})
})
describe('Introspection', () => {
it('should have public introspection disabled by default without master key', async () => {
try {
await apolloClient.query({
query: gql`
query Introspection {
__schema {
types {
name
}
}
}
`,
})
fail('should have thrown an error');
} catch (e) {
expect(e.message).toEqual('Response not successful: Received status code 403');
expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
}
});
it('should always work with master key in node environment production', async () => {
const originalNodeEnv = process.env.NODE_ENV;
try {
// Apollo Server have changing behavior based on the NODE_ENV variable
// so we need to set it to production to get the expected behavior
// and cover correctly the introspection cases
process.env.NODE_ENV = 'production';
await createGQLFromParseServer(parseServer);
const introspection = await apolloClient.query({
query: gql`
query Introspection {
__schema {
types {
name
}
}
}
`,
context: {
headers: {
'X-Parse-Master-Key': 'test',
},
},
});
expect(introspection.data).toBeDefined();
expect(introspection.errors).not.toBeDefined();
} finally {
process.env.NODE_ENV = originalNodeEnv;
}
});
it('should always work with master key in node environment development', async () => {
const originalNodeEnv = process.env.NODE_ENV;
try {
// Apollo Server have changing behavior based on the NODE_ENV variable
// so we need to set it to development to get the expected behavior
// and cover correctly the introspection cases
process.env.NODE_ENV = 'development';
await createGQLFromParseServer(parseServer);
const introspection = await apolloClient.query({
query: gql`
query Introspection {
__schema {
types {
name
}
}
}
`,
context: {
headers: {
'X-Parse-Master-Key': 'test',
},
},
});
expect(introspection.data).toBeDefined();
expect(introspection.errors).not.toBeDefined();
} finally {
process.env.NODE_ENV = originalNodeEnv;
}
});
it('should always work with maintenance key', async () => {
const introspection =
await apolloClient.query({
query: gql`
query Introspection {
__schema {
types {
name
}
}
}
`,
context: {
headers: {
'X-Parse-Maintenance-Key': 'test2',
},
}
},)
expect(introspection.data).toBeDefined();
expect(introspection.errors).not.toBeDefined();
});
it('should have public introspection enabled if enabled', async () => {
const parseServer = await reconfigureServer();
await createGQLFromParseServer(parseServer, { graphQLPublicIntrospection: true });
const introspection =
await apolloClient.query({
query: gql`
query Introspection {
__schema {
types {
name
}
}
}
`,
})
expect(introspection.data).toBeDefined();
});
it('should block __type introspection without master key', async () => {
try {
await apolloClient.query({
query: gql`
query TypeIntrospection {
__type(name: "User") {
name
kind
}
}
`,
});
fail('should have thrown an error');
} catch (e) {
expect(e.message).toEqual('Response not successful: Received status code 403');
expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
}
});
it('should block aliased __type introspection without master key', async () => {
try {
await apolloClient.query({
query: gql`
query AliasedTypeIntrospection {
myAlias: __type(name: "User") {
name
kind
}
}
`,
});
fail('should have thrown an error');
} catch (e) {
expect(e.message).toEqual('Response not successful: Received status code 403');
expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
}
});
it('should block __type introspection in fragments without master key', async () => {
try {
await apolloClient.query({
query: gql`
fragment TypeIntrospectionFields on Query {
typeInfo: __type(name: "User") {
name
kind
}
}
query FragmentTypeIntrospection {
...TypeIntrospectionFields
}
`,
});
fail('should have thrown an error');
} catch (e) {
expect(e.message).toEqual('Response not successful: Received status code 403');
expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
}
});
it('should block __type introspection through nested fragment spreads without master key', async () => {
try {
await apolloClient.query({
query: gql`
fragment InnerFragment on Query {
__type(name: "User") {
name
fields {
name
}
}
}
fragment OuterFragment on Query {
...InnerFragment
}
query NestedFragmentIntrospection {
...OuterFragment
}
`,
});
fail('should have thrown an error');
} catch (e) {
expect(e.message).toEqual('Response not successful: Received status code 403');
expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
}
});
it('should block __type introspection hidden in fragment with valid field without master key', async () => {
try {
// First create a test object to query
const object = new Parse.Object('SomeClass');
await object.save();
await apolloClient.query({
query: gql`
fragment MixedFragment on Query {
someClasses {
edges {
node {
objectId
}
}
}
__type(name: "User") {
name
kind
}
}
query MixedQuery {
...MixedFragment
}
`,
});
fail('should have thrown an error');
} catch (e) {
expect(e.message).toEqual('Response not successful: Received status code 403');
expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
}
});
it('should block __type introspection inside inline fragment without master key', async () => {
try {
await apolloClient.query({
query: gql`
query InlineFragmentBypass {
... on Query {
__type(name: "User") {
name
kind
}
}
}
`,
});
fail('should have thrown an error');
} catch (e) {
expect(e.message).toEqual('Response not successful: Received status code 403');
expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
}
});
it('should block __type introspection inside nested inline fragments without master key', async () => {
try {
await apolloClient.query({
query: gql`
query NestedInlineFragmentBypass {
... on Query {
... {
__type(name: "User") {
name
kind
}
}
}
}
`,
});
fail('should have thrown an error');
} catch (e) {
expect(e.message).toEqual('Response not successful: Received status code 403');
expect(e.networkError.result.errors[0].message).toEqual('Introspection is not allowed');
}
});
it('should allow __type introspection with master key', async () => {
const introspection = await apolloClient.query({
query: gql`
query TypeIntrospection {
__type(name: "User") {
name
kind
}
}
`,
context: {
headers: {
'X-Parse-Master-Key': 'test',
},
},