-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
wrappers_test.go
1077 lines (999 loc) · 30.3 KB
/
wrappers_test.go
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
/*
* Copyright 2019 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package schema
import (
"encoding/json"
"io/ioutil"
"strings"
"testing"
"github.com/dgraph-io/dgraph/graphql/authorization"
"github.com/google/go-cmp/cmp"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"github.com/vektah/gqlparser/v2/ast"
"gopkg.in/yaml.v2"
)
func TestDgraphMapping_WithoutDirectives(t *testing.T) {
schemaStr := `
type Author {
id: ID!
name: String! @search(by: [hash, trigram])
dob: DateTime @search
reputation: Float @search
posts: [Post!] @hasInverse(field: author)
}
type Post {
postID: ID!
postType: PostType @search
author: Author! @hasInverse(field: posts)
}
enum PostType {
Fact
Question
Opinion
}
interface Employee {
ename: String!
}
interface Character {
id: ID!
name: String! @search(by: [exact])
appearsIn: [Episode!] @search
}
type Human implements Character & Employee {
starships: [Starship]
totalCredits: Float
}
type Droid implements Character {
primaryFunction: String
}
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
type Starship {
id: ID!
name: String! @search(by: [term])
length: Float
}`
schHandler, errs := NewHandler(schemaStr)
require.NoError(t, errs)
sch, err := FromString(schHandler.GQLSchema())
require.NoError(t, err)
s, ok := sch.(*schema)
require.True(t, ok, "expected to be able to convert sch to internal schema type")
author := map[string]string{
"name": "Author.name",
"dob": "Author.dob",
"reputation": "Author.reputation",
"posts": "Author.posts",
}
post := map[string]string{
"postType": "Post.postType",
"author": "Post.author",
}
character := map[string]string{
"name": "Character.name",
"appearsIn": "Character.appearsIn",
}
human := map[string]string{
"ename": "Employee.ename",
"name": "Character.name",
"appearsIn": "Character.appearsIn",
"starships": "Human.starships",
"totalCredits": "Human.totalCredits",
}
droid := map[string]string{
"name": "Character.name",
"appearsIn": "Character.appearsIn",
"primaryFunction": "Droid.primaryFunction",
}
starship := map[string]string{
"name": "Starship.name",
"length": "Starship.length",
}
expected := map[string]map[string]string{
"Author": author,
"UpdateAuthorPayload": author,
"DeleteAuthorPayload": author,
"Post": post,
"UpdatePostPayload": post,
"DeletePostPayload": post,
"Employee": map[string]string{
"ename": "Employee.ename",
},
"Character": character,
"UpdateCharacterPayload": character,
"DeleteCharacterPayload": character,
"Human": human,
"UpdateHumanPayload": human,
"DeleteHumanPayload": human,
"Droid": droid,
"UpdateDroidPayload": droid,
"DeleteDroidPayload": droid,
"Starship": starship,
"UpdateStarshipPayload": starship,
"DeleteStarshipPayload": starship,
}
if diff := cmp.Diff(expected, s.dgraphPredicate); diff != "" {
t.Errorf("dgraph predicate map mismatch (-want +got):\n%s", diff)
}
}
func TestDgraphMapping_WithDirectives(t *testing.T) {
schemaStr := `
type Author @dgraph(type: "dgraph.author") {
id: ID!
name: String! @search(by: [hash, trigram])
dob: DateTime @search
reputation: Float @search
posts: [Post!] @hasInverse(field: author)
}
type Post @dgraph(type: "dgraph.Post") {
postID: ID!
postType: PostType @search @dgraph(pred: "dgraph.post_type")
author: Author! @hasInverse(field: posts) @dgraph(pred: "dgraph.post_author")
}
enum PostType {
Fact
Question
Opinion
}
interface Employee @dgraph(type: "dgraph.employee.en") {
ename: String!
}
interface Character @dgraph(type: "performance.character") {
id: ID!
name: String! @search(by: [exact])
appearsIn: [Episode!] @search @dgraph(pred: "appears_in")
}
type Human implements Character & Employee {
starships: [Starship]
totalCredits: Float @dgraph(pred: "credits")
}
type Droid implements Character @dgraph(type: "roboDroid") {
primaryFunction: String
}
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
type Starship @dgraph(type: "star.ship") {
id: ID!
name: String! @search(by: [term]) @dgraph(pred: "star.ship.name")
length: Float
}`
schHandler, errs := NewHandler(schemaStr)
require.NoError(t, errs)
sch, err := FromString(schHandler.GQLSchema())
require.NoError(t, err)
s, ok := sch.(*schema)
require.True(t, ok, "expected to be able to convert sch to internal schema type")
author := map[string]string{
"name": "dgraph.author.name",
"dob": "dgraph.author.dob",
"reputation": "dgraph.author.reputation",
"posts": "dgraph.author.posts",
}
post := map[string]string{
"postType": "dgraph.post_type",
"author": "dgraph.post_author",
}
character := map[string]string{
"name": "performance.character.name",
"appearsIn": "appears_in",
}
human := map[string]string{
"ename": "dgraph.employee.en.ename",
"name": "performance.character.name",
"appearsIn": "appears_in",
"starships": "Human.starships",
"totalCredits": "credits",
}
droid := map[string]string{
"name": "performance.character.name",
"appearsIn": "appears_in",
"primaryFunction": "roboDroid.primaryFunction",
}
starship := map[string]string{
"name": "star.ship.name",
"length": "star.ship.length",
}
expected := map[string]map[string]string{
"Author": author,
"UpdateAuthorPayload": author,
"DeleteAuthorPayload": author,
"Post": post,
"UpdatePostPayload": post,
"DeletePostPayload": post,
"Employee": map[string]string{
"ename": "dgraph.employee.en.ename",
},
"Character": character,
"UpdateCharacterPayload": character,
"DeleteCharacterPayload": character,
"Human": human,
"UpdateHumanPayload": human,
"DeleteHumanPayload": human,
"Droid": droid,
"UpdateDroidPayload": droid,
"DeleteDroidPayload": droid,
"Starship": starship,
"UpdateStarshipPayload": starship,
"DeleteStarshipPayload": starship,
}
if diff := cmp.Diff(expected, s.dgraphPredicate); diff != "" {
t.Errorf("dgraph predicate map mismatch (-want +got):\n%s", diff)
}
}
func TestCheckNonNulls(t *testing.T) {
gqlSchema, err := FromString(`
type T {
req: String!
notReq: String
alsoReq: String!
}`)
require.NoError(t, err)
tcases := map[string]struct {
obj map[string]interface{}
exc string
err error
}{
"all present": {
obj: map[string]interface{}{"req": "here", "notReq": "here", "alsoReq": "here"},
err: nil,
},
"only non-null": {
obj: map[string]interface{}{"req": "here", "alsoReq": "here"},
err: nil,
},
"missing non-null": {
obj: map[string]interface{}{"req": "here", "notReq": "here"},
err: errors.Errorf("type T requires a value for field alsoReq, but no value present"),
},
"missing all non-null": {
obj: map[string]interface{}{"notReq": "here"},
err: errors.Errorf("type T requires a value for field req, but no value present"),
},
"with exclusion": {
obj: map[string]interface{}{"req": "here", "notReq": "here"},
exc: "alsoReq",
err: nil,
},
}
typ := &astType{
typ: &ast.Type{NamedType: "T"},
inSchema: (gqlSchema.(*schema)),
}
for name, test := range tcases {
t.Run(name, func(t *testing.T) {
err := typ.EnsureNonNulls(test.obj, test.exc)
if test.err == nil {
require.NoError(t, err)
} else {
require.EqualError(t, err, test.err.Error())
}
})
}
}
func TestSubstituteVarsInBody(t *testing.T) {
tcases := []struct {
name string
variables map[string]interface{}
template interface{}
expected interface{}
expectedErr error
}{
{
"handle nil template correctly",
map[string]interface{}{"id": "0x3", "postID": "0x9"},
nil,
nil,
nil,
},
{
"handle empty object template correctly",
map[string]interface{}{"id": "0x3", "postID": "0x9"},
map[string]interface{}{},
map[string]interface{}{},
nil,
},
{
"substitutes variables correctly",
map[string]interface{}{"id": "0x3", "postID": "0x9"},
map[string]interface{}{"author": "$id", "post": map[string]interface{}{"id": "$postID"}},
map[string]interface{}{"author": "0x3", "post": map[string]interface{}{"id": "0x9"}},
nil,
},
{
"substitutes nil variables correctly",
map[string]interface{}{"id": nil},
map[string]interface{}{"author": "$id"},
map[string]interface{}{"author": nil},
nil,
},
{
"substitutes variables with an array in template correctly",
map[string]interface{}{"id": "0x3", "admin": false, "postID": "0x9",
"text": "Random comment", "age": 28},
map[string]interface{}{"author": "$id", "admin": "$admin",
"post": map[string]interface{}{"id": "$postID",
"comments": []interface{}{"$text", "$age"}}, "age": "$age"},
map[string]interface{}{"author": "0x3", "admin": false,
"post": map[string]interface{}{"id": "0x9",
"comments": []interface{}{"Random comment", 28}}, "age": 28},
nil,
},
{
"substitutes variables with an array of object in template correctly",
map[string]interface{}{"id": "0x3", "admin": false, "postID": "0x9",
"text": "Random comment", "age": 28},
map[string]interface{}{"author": "$id", "admin": "$admin",
"post": map[string]interface{}{"id": "$postID",
"comments": []interface{}{map[string]interface{}{"text": "$text"}}}, "age": "$age"},
map[string]interface{}{"author": "0x3", "admin": false,
"post": map[string]interface{}{"id": "0x9",
"comments": []interface{}{map[string]interface{}{"text": "Random comment"}}}, "age": 28},
nil,
},
{
"substitutes array variables correctly",
map[string]interface{}{"ids": []int{1, 2, 3}, "names": []string{"M1", "M2"},
"check": []interface{}{1, 3.14, "test"}},
map[string]interface{}{"ids": "$ids", "names": "$names", "check": "$check"},
map[string]interface{}{"ids": []int{1, 2, 3}, "names": []string{"M1", "M2"},
"check": []interface{}{1, 3.14, "test"}},
nil,
},
{
"substitutes object variables correctly",
map[string]interface{}{"author": map[string]interface{}{"id": 1, "name": "George"}},
map[string]interface{}{"author": "$author"},
map[string]interface{}{"author": map[string]interface{}{"id": 1, "name": "George"}},
nil,
},
{
"substitutes array of object variables correctly",
map[string]interface{}{"authors": []interface{}{map[string]interface{}{"id": 1,
"name": "George"}, map[string]interface{}{"id": 2, "name": "Jerry"}}},
map[string]interface{}{"authors": "$authors"},
map[string]interface{}{"authors": []interface{}{map[string]interface{}{"id": 1,
"name": "George"}, map[string]interface{}{"id": 2, "name": "Jerry"}}},
nil,
},
{
"substitutes direct body variable correctly",
map[string]interface{}{"authors": []interface{}{map[string]interface{}{"id": 1,
"name": "George"}, map[string]interface{}{"id": 2, "name": "Jerry"}}},
"$authors",
[]interface{}{map[string]interface{}{"id": 1, "name": "George"},
map[string]interface{}{"id": 2, "name": "Jerry"}},
nil,
},
{
"skip variable that is not present and shouldn't return error ",
map[string]interface{}{"postID": "0x9"},
map[string]interface{}{"author": "$id", "post": map[string]interface{}{"id": "$postID"}},
map[string]interface{}{"author": "$id", "post": map[string]interface{}{"id": "0x9"}},
nil,
},
}
for _, test := range tcases {
t.Run(test.name, func(t *testing.T) {
var templatePtr *interface{}
if test.template == nil {
templatePtr = nil
} else {
templatePtr = &test.template
}
err := SubstituteVarsInBody(templatePtr, test.variables)
if test.expectedErr == nil {
require.NoError(t, err)
require.Equal(t, test.expected, test.template)
} else {
require.EqualError(t, err, test.expectedErr.Error())
}
})
}
}
func TestParseBodyTemplate(t *testing.T) {
tcases := []struct {
name string
template string
expected interface{}
requiredFields map[string]bool
expectedErr error
}{
{
"parses empty body template correctly",
``,
nil,
nil,
nil,
},
{
"parses whitespace body template correctly",
` `,
nil,
nil,
nil,
},
{
"parses empty object body template correctly",
`{}`,
map[string]interface{}{},
map[string]bool{},
nil,
},
{
"parses body template correctly",
`{ author: $id, post: { id: $postID }}`,
map[string]interface{}{"author": "$id", "post": map[string]interface{}{"id": "$postID"}},
map[string]bool{"id": true, "postID": true},
nil,
},
{
"parses body template with an array correctly",
`{ author: $id, admin: $admin, post: { id: $postID, comments: [$text] },
age: $age}`,
map[string]interface{}{"author": "$id", "admin": "$admin",
"post": map[string]interface{}{"id": "$postID",
"comments": []interface{}{"$text"}}, "age": "$age"},
map[string]bool{"id": true, "admin": true, "postID": true, "text": true, "age": true},
nil,
},
{
"parses body template with an array of object correctly",
`{ author: $id, admin: $admin, post: { id: $postID, comments: [{ text: $text }] },
age: $age}`,
map[string]interface{}{"author": "$id", "admin": "$admin",
"post": map[string]interface{}{"id": "$postID",
"comments": []interface{}{map[string]interface{}{"text": "$text"}}}, "age": "$age"},
map[string]bool{"id": true, "admin": true, "postID": true, "text": true, "age": true},
nil,
},
{
"parses body template with direct variable correctly",
`$authors`,
"$authors",
map[string]bool{"authors": true},
nil,
},
{
"json unmarshal error",
`{ author: $id, post: { id $postID }}`,
nil,
nil,
errors.New("couldn't unmarshal HTTP body: {\"author\":\"$id\",\"post\":{\"id\"\"$postID\"}}" +
" as JSON"),
},
{
"unmatched brackets error",
`{{ author: $id, post: { id: $postID }}`,
nil,
nil,
errors.New("found unmatched curly braces while parsing body template"),
},
{
"invalid character error",
`(author: $id, post: { id: $postID }}`,
nil,
nil,
errors.New("invalid character: ( while parsing body template"),
},
}
for _, test := range tcases {
t.Run(test.name, func(t *testing.T) {
b, requiredFields, err := parseBodyTemplate(test.template)
if test.expectedErr == nil {
require.NoError(t, err)
require.Equal(t, test.requiredFields, requiredFields)
if b == nil {
require.Nil(t, test.expected)
} else {
require.Equal(t, test.expected, *b)
}
} else {
require.EqualError(t, err, test.expectedErr.Error())
}
})
}
}
func TestSubstituteVarsInURL(t *testing.T) {
tcases := []struct {
name string
variables map[string]interface{}
url string
expected string
expectedErr error
}{
{
"Return url as is when no params",
nil,
"http://myapi.com/favMovies/1?num=10",
"http://myapi.com/favMovies/1?num=10",
nil,
},
{
"Substitute query params with space properly",
map[string]interface{}{"id": "0x9", "name": "Michael Compton",
"num": 10},
"http://myapi.com/favMovies/$id?name=$name&num=$num",
"http://myapi.com/favMovies/0x9?name=Michael+Compton&num=10",
nil,
},
{
"Substitute query params for variables with array value",
map[string]interface{}{"ids": []int{1, 2}, "names": []string{"M1", "M2"},
"check": []interface{}{1, 3.14, "test"}},
"http://myapi.com/favMovies?id=$ids&name=$names&check=$check",
"http://myapi.com/favMovies?check=1&check=3.14&check=test&id=1&id=2&name=M1&name=M2",
nil,
},
{
"Substitute query params for variables with object value",
map[string]interface{}{"data": map[string]interface{}{"id": 1, "name": "George"}},
"http://myapi.com/favMovies?author=$data",
"http://myapi.com/favMovies?author%5Bid%5D=1&author%5Bname%5D=George",
nil,
},
{
"Substitute query params for variables with array of object value",
map[string]interface{}{"data": []interface{}{map[string]interface{}{"id": 1,
"name": "George"}, map[string]interface{}{"id": 2, "name": "Jerry"}}},
"http://myapi.com/favMovies?author=$data",
"http://myapi.com/favMovies?author%5Bid%5D=1&author%5Bid%5D=2&author%5Bname%5D=George" +
"&author%5Bname%5D=Jerry",
nil,
},
{
"Substitute query params for a variable value that is null as empty",
map[string]interface{}{"id": "0x9", "name": nil, "num": 10},
"http://myapi.com/favMovies/$id?name=$name&num=$num",
"http://myapi.com/favMovies/0x9?name=&num=10",
nil,
},
{
"Remove query params corresponding to variables that are empty.",
map[string]interface{}{"id": "0x9", "num": 10},
"http://myapi.com/favMovies/$id?name=$name&num=$num",
"http://myapi.com/favMovies/0x9?num=10",
nil,
},
{
"Substitute multiple path params properly",
map[string]interface{}{"id": "0x9", "num": 10},
"http://myapi.com/favMovies/$id/$num",
"http://myapi.com/favMovies/0x9/10",
nil,
},
{
"Substitute path params for variables with array value",
map[string]interface{}{"ids": []int{1, 2}, "names": []string{"M1", "M2"},
"check": []interface{}{1, 3.14, "test"}},
"http://myapi.com/favMovies/$ids/$names/$check",
"http://myapi.com/favMovies/1%2C2/M1%2CM2/1%2C3.14%2Ctest",
nil,
},
{
"Substitute path params for variables with object value",
map[string]interface{}{"author": map[string]interface{}{"id": 1, "name": "George"}},
"http://myapi.com/favMovies/$author",
"http://myapi.com/favMovies/id%2C1%2Cname%2CGeorge",
nil,
},
{
"Substitute path params for variables with array of object value",
map[string]interface{}{"authors": []interface{}{map[string]interface{}{"id": 1,
"name": "George/"}, map[string]interface{}{"id": 2, "name": "Jerry"}}},
"http://myapi.com/favMovies/$authors",
"http://myapi.com/favMovies/id%2C1%2Cname%2CGeorge%2F%2Cid%2C2%2Cname%2CJerry",
nil,
},
}
for _, test := range tcases {
t.Run(test.name, func(t *testing.T) {
b, err := SubstituteVarsInURL(test.url, test.variables)
if test.expectedErr == nil {
require.NoError(t, err)
require.Equal(t, test.expected, string(b))
} else {
require.EqualError(t, err, test.expectedErr.Error())
}
})
}
}
func TestParseRequiredArgsFromGQLRequest(t *testing.T) {
tcases := []struct {
name string
req string
body string
requiredArgs map[string]bool
}{
{
"parse required args for single request",
"query($id: ID!, $age: String!) { userNames(id: $id, age: $age) }",
"",
map[string]bool{"id": true, "age": true},
},
{
"parse required nested args for single request",
"query($id: ID!, $age: String!) { userNames(id: $id, car: {age: $age}) }",
"",
map[string]bool{"id": true, "age": true},
},
}
for _, test := range tcases {
t.Run(test.name, func(t *testing.T) {
args, err := parseRequiredArgsFromGQLRequest(test.req)
require.NoError(t, err)
require.Equal(t, test.requiredArgs, args)
})
}
}
// Tests showing that the correct query and variables are sent to the remote server.
type CustomHTTPConfigCase struct {
Name string
Type string
// the query and variables given as input by the user.
GQLQuery string
GQLVariables string
// our schema against which the above query and variables are resolved.
GQLSchema string
// for resolving fields variables are populated from the result of resolving a Dgraph query
// so RemoteVariables won't have anything.
InputVariables string
// remote query and variables which are built as part of the HTTP config and checked.
RemoteQuery string
RemoteVariables string
// remote schema against which the RemoteQuery and RemoteVariables are validated.
RemoteSchema string
}
func TestGraphQLQueryInCustomHTTPConfig(t *testing.T) {
b, err := ioutil.ReadFile("custom_http_config_test.yaml")
require.NoError(t, err, "Unable to read test file")
var tests []CustomHTTPConfigCase
err = yaml.Unmarshal(b, &tests)
require.NoError(t, err, "Unable to unmarshal tests to yaml.")
for _, tcase := range tests {
t.Run(tcase.Name, func(t *testing.T) {
schHandler, errs := NewHandler(tcase.GQLSchema)
require.NoError(t, errs)
sch, err := FromString(schHandler.GQLSchema())
require.NoError(t, err)
var vars map[string]interface{}
if tcase.GQLVariables != "" {
err = json.Unmarshal([]byte(tcase.GQLVariables), &vars)
require.NoError(t, err)
}
op, err := sch.Operation(
&Request{
Query: tcase.GQLQuery,
Variables: vars,
})
require.NoError(t, err)
require.NotNil(t, op)
var field Field
if tcase.Type == "query" {
queries := op.Queries()
require.Len(t, queries, 1)
field = queries[0]
} else if tcase.Type == "mutation" {
mutations := op.Mutations()
require.Len(t, mutations, 1)
field = mutations[0]
} else if tcase.Type == "field" {
queries := op.Queries()
require.Len(t, queries, 1)
q := queries[0]
require.Len(t, q.SelectionSet(), 1)
// We are allow checking the custom http config on the first field of the query.
field = q.SelectionSet()[0]
}
c, err := field.CustomHTTPConfig()
require.NoError(t, err)
remoteSchemaHandler, errs := NewHandler(tcase.RemoteSchema)
require.NoError(t, errs)
remoteSchema, err := FromString(remoteSchemaHandler.GQLSchema())
require.NoError(t, err)
// Validate the generated query against the remote schema.
tmpl, ok := (*c.Template).(map[string]interface{})
require.True(t, ok)
require.Equal(t, tcase.RemoteQuery, c.RemoteGqlQuery)
v, _ := tmpl["variables"].(map[string]interface{})
var rv map[string]interface{}
if tcase.RemoteVariables != "" {
require.NoError(t, json.Unmarshal([]byte(tcase.RemoteVariables), &rv))
}
require.Equal(t, rv, v)
if tcase.InputVariables != "" {
require.NoError(t, json.Unmarshal([]byte(tcase.InputVariables), &v))
}
op, err = remoteSchema.Operation(
&Request{
Query: c.RemoteGqlQuery,
Variables: v,
})
require.NoError(t, err)
require.NotNil(t, op)
})
}
}
func TestAllowedHeadersList(t *testing.T) {
tcases := []struct {
name string
schemaStr string
expected string
}{
{
"auth header present in allowed headers list",
`
type X @auth(
query: {rule: """
query {
queryX(filter: { userRole: { eq: "ADMIN" } }) {
__typename
}
}"""
}
) {
username: String! @id
userRole: String @search(by: [hash])
}
# Dgraph.Authorization {"VerificationKey":"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsppQMzPRyYP9KcIAg4CG\nUV3NGCIRdi2PqkFAWzlyo0mpZlHf5Hxzqb7KMaXBt8Yh+1fbi9jcBbB4CYgbvgV0\n7pAZY/HE4ET9LqnjeF2sjmYiGVxLARv8MHXpNLcw7NGcL0FgSX7+B2PB2WjBPnJY\ndvaJ5tsT+AuZbySaJNS1Ha77lW6gy/dmBDybZ1UU+ixRjDWEqPmtD71g2Fpk8fgr\nReNm2h/ZQsJ19onFaGPQN6L6uJR+hfYN0xmOdTC21rXRMUJT8Pw9Xsi6wSt+tI4T\nKxDfMTxKksfjv93dnnof5zJtIcMFQlSKLOrgDC0WP07gVTR2b85tFod80ykevvgu\nAQIDAQAB\n-----END PUBLIC KEY-----","Header":"X-Test-Dgraph","Namespace":"https://dgraph.io/jwt/claims","Algo":"RS256"}
`,
"X-Test-Dgraph",
},
}
for _, test := range tcases {
t.Run(test.name, func(t *testing.T) {
schHandler, errs := NewHandler(test.schemaStr)
require.NoError(t, errs)
_, err := FromString(schHandler.GQLSchema())
require.NoError(t, err)
require.True(t, strings.Contains(hc.allowed, test.expected))
})
}
}
func TestCustomLogicHeaders(t *testing.T) {
tcases := []struct {
name string
schemaStr string
err error
}{
{
"check for introspection header to always use value from secrets",
`
type User @remote {
description: String
}
type Query {
user(name: String!): User
@custom(
http: {
url: "http://api:8888/graphql"
method: "POST"
introspectionHeaders: ["Authorization:Api-Token"]
graphql: "query($name: String!) { getUser(name: $name) }"
}
)
}
`,
errors.New("input:13: Type Query; Field user; introspectionHeaders in @custom directive should use secrets to store the header value. " + "To do that specify `Api-Token` in this format '#Dgraph.Secret name value' at the bottom of your schema file." + "\n"),
},
{
"check for secret and forward headers overlapping",
`
type User @remote {
description: String
}
type Query {
user(name: String!): User
@custom(
http: {
url: "http://api:8888/graphql"
method: "POST"
forwardHeaders: ["API-Token", "Authorization"]
secretHeaders: ["Authorization"]
graphql: "query($name: String!) { getUser(name: $name) }"
}
)
}
`,
errors.New("input:14: Type Query; Field user; secretHeaders and forwardHeaders in @custom directive cannot have overlapping headers, found: `Authorization`." + "\n"),
},
{
"check for header structure",
`
type User @remote {
description: String
}
type Query {
user(name: String!): User
@custom(
http: {
url: "http://api:8888/graphql"
method: "POST"
forwardHeaders: ["API-Token", "Content-Type"]
secretHeaders: ["Authorization:Auth:random"]
graphql: "query($name: String!) { getUser(name: $name) }"
}
)
}
`,
errors.New("input:14: Type Query; Field user; secretHeaders in @custom directive should be of the form 'remote_headername:local_headername' or just 'headername', found: `Authorization:Auth:random`." + "\n"),
},
}
for _, test := range tcases {
t.Run(test.name, func(t *testing.T) {
_, err := NewHandler(test.schemaStr)
require.EqualError(t, err, test.err.Error())
})
}
}
func TestParseSecrets(t *testing.T) {
tcases := []struct {
name string
schemaStr string
expectedSecrets map[string]string
expectedAuthHeader string
err error
}{
{"should be able to parse secrets",
`
type User {
id: ID!
name: String!
}
# Dgraph.Secret GITHUB_API_TOKEN "some-super-secret-token"
# Dgraph.Secret STRIPE_API_KEY "stripe-api-key-value"
`,
map[string]string{"GITHUB_API_TOKEN": "some-super-secret-token",
"STRIPE_API_KEY": "stripe-api-key-value"},
"",
nil,
},
{"should be able to parse secret where schema also has other comments.",
`
# Dgraph.Secret GITHUB_API_TOKEN "some-super-secret-token"
type User {
id: ID!
name: String!
}
# Dgraph.Secret STRIPE_API_KEY "stripe-api-key-value"
# random comment
`,
map[string]string{"GITHUB_API_TOKEN": "some-super-secret-token",
"STRIPE_API_KEY": "stripe-api-key-value"},
"",
nil,
},
{
"should throw an error if the secret is not in the correct format",
`
type User {
id: ID!
name: String!
}
# Dgraph.Secret RANDOM_TOKEN
`,
nil,
"",
errors.New("incorrect format for specifying Dgraph secret found for " +
"comment: `# Dgraph.Secret RANDOM_TOKEN`, it should " +
"be `# Dgraph.Secret key value`"),
},
{
"Dgraph.Authorization old format",
`
type User {
id: ID!
name: String!
}
# Dgraph.Secret "GITHUB_API_TOKEN" "some-super-secret-token"
# Dgraph.Authorization X-Test-Dgraph https://dgraph.io/jwt/claims HS256 "key"
# Dgraph.Secret STRIPE_API_KEY "stripe-api-key-value"
`,
map[string]string{"GITHUB_API_TOKEN": "some-super-secret-token",
"STRIPE_API_KEY": "stripe-api-key-value"},
"X-Test-Dgraph",
nil,
},
{
"Dgraph.Authorization old format error",
`
type User {
id: ID!
name: String!
}
# Dgraph.Secret "GITHUB_API_TOKEN" "some-super-secret-token"
# Dgraph.Authorization X-Test-Dgraph https://dgraph.io/jwt/claims "key"
# Dgraph.Secret STRIPE_API_KEY "stripe-api-key-value"
`,
nil,