-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathquery_rewriter.go
1994 lines (1766 loc) · 63.5 KB
/
query_rewriter.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 resolve
import (
"bytes"
"context"
"fmt"
"sort"
"strconv"
"strings"
"github.com/dgraph-io/dgraph/gql"
"github.com/dgraph-io/dgraph/graphql/authorization"
"github.com/dgraph-io/dgraph/graphql/schema"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/x"
"github.com/pkg/errors"
)
type queryRewriter struct{}
type authRewriter struct {
authVariables map[string]interface{}
isWritingAuth bool
// `filterByUid` is used to when we have to rewrite top level query with uid function. The
// variable name is passed in `varName`. If true it will rewrite as following:
// queryType(uid(varName)) {
// Once such case is when we perform query in delete mutation.
filterByUid bool
selector func(t schema.Type) *schema.RuleNode
varGen *VariableGenerator
varName string
// `parentVarName` is used to link a query with it's previous level.
parentVarName string
// `hasAuthRules` indicates if any of fields in the complete query hierarchy has auth rules.
hasAuthRules bool
// `hasCascade` indicates if any of fields in the complete query hierarchy has cascade directive.
hasCascade bool
}
// The struct is used as a return type for buildCommonAuthQueries function.
type commonAuthQueryVars struct {
// Stores queries of the form
// var(func: uid(Ticket)) {
// User as Ticket.assignedTo
// }
parentQry *gql.GraphQuery
// Stores queries which aggregate filters and auth rules. Eg.
// // User6 as var(func: uid(User2), orderasc: ...) @filter((eq(User.username, "User1") AND (...Auth Filter))))
selectionQry *gql.GraphQuery
}
// NewQueryRewriter returns a new QueryRewriter.
func NewQueryRewriter() QueryRewriter {
return &queryRewriter{}
}
func hasAuthRules(field schema.Field, authRw *authRewriter) bool {
if field == nil {
return false
}
rn := authRw.selector(field.ConstructedFor())
if rn != nil {
return true
}
for _, childField := range field.SelectionSet() {
if authRules := hasAuthRules(childField, authRw); authRules {
return true
}
}
return false
}
func hasCascadeDirective(field schema.Field) bool {
if c := field.Cascade(); c != nil {
return true
}
for _, childField := range field.SelectionSet() {
if res := hasCascadeDirective(childField); res {
return true
}
}
return false
}
// Returns the auth selector to be used depending on the query type.
func getAuthSelector(queryType schema.QueryType) func(t schema.Type) *schema.RuleNode {
if queryType == schema.PasswordQuery {
return passwordAuthSelector
}
return queryAuthSelector
}
// Rewrite rewrites a GraphQL query into a Dgraph GraphQuery.
func (qr *queryRewriter) Rewrite(
ctx context.Context,
gqlQuery schema.Query) ([]*gql.GraphQuery, error) {
authVariables, _ := ctx.Value(authorization.AuthVariables).(map[string]interface{})
if authVariables == nil {
customClaims, err := authorization.ExtractCustomClaims(ctx)
if err != nil {
return nil, err
}
authVariables = customClaims.AuthVariables
}
authRw := &authRewriter{
authVariables: authVariables,
varGen: NewVariableGenerator(),
selector: getAuthSelector(gqlQuery.QueryType()),
parentVarName: gqlQuery.ConstructedFor().Name() + "Root",
}
authRw.hasAuthRules = hasAuthRules(gqlQuery, authRw)
authRw.hasCascade = hasCascadeDirective(gqlQuery)
switch gqlQuery.QueryType() {
case schema.GetQuery:
// TODO: The only error that can occur in query rewriting is if an ID argument
// can't be parsed as a uid: e.g. the query was something like:
//
// getT(id: "HI") { ... }
//
// But that's not a rewriting error! It should be caught by validation
// way up when the query first comes in. All other possible problems with
// the query are caught by validation.
// ATM, I'm not sure how to hook into the GraphQL validator to get that to happen
xid, uid, err := gqlQuery.IDArgValue()
if err != nil {
return nil, err
}
dgQuery := rewriteAsGet(gqlQuery, uid, xid, authRw)
return dgQuery, nil
case schema.FilterQuery:
return rewriteAsQuery(gqlQuery, authRw), nil
case schema.PasswordQuery:
return passwordQuery(gqlQuery, authRw)
case schema.AggregateQuery:
return aggregateQuery(gqlQuery, authRw), nil
case schema.EntitiesQuery:
return entitiesQuery(gqlQuery, authRw)
default:
return nil, errors.Errorf("unimplemented query type %s", gqlQuery.QueryType())
}
}
// entitiesQuery rewrites the Apollo `_entities` Query which is sent from the Apollo gateway to a DQL query.
// This query is sent to the Dgraph service to resolve types `extended` and defined by this service.
func entitiesQuery(field schema.Query, authRw *authRewriter) ([]*gql.GraphQuery, error) {
// Input Argument to the Query is a List of "__typename" and "keyField" pair.
// For this type Extension:-
// extend type Product @key(fields: "upc") {
// upc: String @external
// reviews: [Review]
// }
// Input to the Query will be
// "_representations": [
// {
// "__typename": "Product",
// "upc": "B00005N5PF"
// },
// ...
// ]
representations, ok := field.ArgValue("representations").([]interface{})
if !ok {
return nil, fmt.Errorf("Error parsing `representations` argument")
}
typeNames := make(map[string]bool)
keyFieldValueList := make([]interface{}, 0)
keyFieldIsID := false
keyFieldName := ""
var err error
for i, rep := range representations {
representation, ok := rep.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Error parsing in %dth item in the `_representations` argument", i)
}
typename, ok := representation["__typename"].(string)
if !ok {
return nil, fmt.Errorf("Unable to extract __typename from %dth item in the `_representations` argument", i)
}
// Store all the typeNames into an map to perfrom validation at last.
typeNames[typename] = true
keyFieldName, keyFieldIsID, err = field.KeyField(typename)
if err != nil {
return nil, err
}
keyFieldValue, ok := representation[keyFieldName]
if !ok {
return nil, fmt.Errorf("Unable to extract value for key field `%s` from %dth item in the `_representations` argument", keyFieldName, i)
}
keyFieldValueList = append(keyFieldValueList, keyFieldValue)
}
// Return error if there was no typename extracted from the `_representations` argument.
if len(typeNames) == 0 {
return nil, fmt.Errorf("Expect one typename in `_representations` argument, got none")
}
// Since we have restricted that all the typeNames for the inputs in the
// representation list should be same, we need to validate it and throw error
// if represenation of more than one type exists.
if len(typeNames) > 1 {
keys := make([]string, len(typeNames))
i := 0
for k := range typeNames {
keys[i] = k
i++
}
return nil, fmt.Errorf("Expected only one unique typename in `_representations` argument, got: %v", keys)
}
var typeName string
for k := range typeNames {
typeName = k
}
typeDefn := field.BuildType(typeName)
rbac := authRw.evaluateStaticRules(typeDefn)
dgQuery := &gql.GraphQuery{
Attr: field.Name(),
}
if rbac == schema.Negative {
dgQuery.Attr = dgQuery.Attr + "()"
return []*gql.GraphQuery{dgQuery}, nil
}
// Construct Filter at Root Func.
// if keyFieldsIsID = true and keyFieldValueList = {"0x1", "0x2"}
// then query will be formed as:-
// _entities(func: uid("0x1", "0x2") {
// ...
// }
// if keyFieldsIsID = false then query will be like:-
// _entities(func: eq(keyFieldName,"0x1", "0x2") {
// ...
// }
// If the key field is of ID type and is not an external field
// then we query it using the `uid` otherwise we treat it as string
// and query using `eq` function.
if keyFieldIsID && !typeDefn.Field(keyFieldName).IsExternal() {
addUIDFunc(dgQuery, convertIDs(keyFieldValueList))
} else {
addEqFunc(dgQuery, typeDefn.DgraphPredicate(keyFieldName), keyFieldValueList)
}
// AddTypeFilter in as the Filter to the Root the Query.
// Query will be like :-
// _entities(func: ...) @filter(type(typeName)) {
// ...
// }
addTypeFilter(dgQuery, typeDefn)
selectionAuth := addSelectionSetFrom(dgQuery, field, authRw)
addUID(dgQuery)
dgQueries := authRw.addAuthQueries(typeDefn, []*gql.GraphQuery{dgQuery}, rbac)
return append(dgQueries, selectionAuth...), nil
}
func aggregateQuery(query schema.Query, authRw *authRewriter) []*gql.GraphQuery {
// Get the type which the count query is written for
mainType := query.ConstructedFor()
dgQuery, rbac := addCommonRules(query, mainType, authRw)
if rbac == schema.Negative {
return dgQuery
}
// Add filter
filter, _ := query.ArgValue("filter").(map[string]interface{})
_ = addFilter(dgQuery[0], mainType, filter)
dgQuery = authRw.addAuthQueries(mainType, dgQuery, rbac)
// mainQuery is the query with Attr: query.Name()
// It is the first query in dgQuery list.
mainQuery := dgQuery[0]
// Changing mainQuery Attr name to var. This is used in the final aggregate<Type> query.
mainQuery.Attr = "var"
finalMainQuery := &gql.GraphQuery{
Attr: query.DgraphAlias() + "()",
}
// Add selection set to mainQuery and finalMainQuery.
isAggregateVarAdded := make(map[string]bool)
isCountVarAdded := false
for _, f := range query.SelectionSet() {
// fldName stores Name of the field f.
fldName := f.Name()
if fldName == "count" {
if !isCountVarAdded {
child := &gql.GraphQuery{
Var: "countVar",
Attr: "count(uid)",
}
mainQuery.Children = append(mainQuery.Children, child)
isCountVarAdded = true
}
finalQueryChild := &gql.GraphQuery{
Alias: f.DgraphAlias(),
Attr: "max(val(countVar))",
}
finalMainQuery.Children = append(finalMainQuery.Children, finalQueryChild)
continue
}
// Handle other aggregate functions than count
aggregateFunctions := []string{"Max", "Min", "Sum", "Avg"}
for _, function := range aggregateFunctions {
// A field can have at maximum one of the aggregation functions as suffix
if strings.HasSuffix(fldName, function) {
// constructedForDgraphPredicate stores the Dgraph predicate for which aggregate function has been queried.
constructedForDgraphPredicate := f.DgraphPredicateForAggregateField()
// constructedForField contains the field for which aggregate function has been queried.
// As all aggregate functions have length 3, removing last 3 characters from fldName.
constructedForField := fldName[:len(fldName)-3]
// isAggregateVarAdded ensures that a field is added to Var query at maximum once.
// If a field has already been added to the var query, don't add it again.
// Eg. Even if scoreMax and scoreMin are queried, the query will contain only one expression
// of the from, "scoreVar as Tweets.score"
if !isAggregateVarAdded[constructedForField] {
child := &gql.GraphQuery{
Var: constructedForField + "Var",
Attr: constructedForDgraphPredicate,
}
// The var field is added to mainQuery. This adds the following DQL query.
// var(func: type(Tweets)) {
// scoreVar as Tweets.score
// }
mainQuery.Children = append(mainQuery.Children, child)
isAggregateVarAdded[constructedForField] = true
}
finalQueryChild := &gql.GraphQuery{
Alias: f.DgraphAlias(),
Attr: strings.ToLower(function) + "(val(" + constructedForField + "Var))",
}
// This adds the following DQL query
// aggregateTweets() {
// TweetsAggregateResult.scoreMin : min(val(scoreVar))
// }
finalMainQuery.Children = append(finalMainQuery.Children, finalQueryChild)
break
}
}
}
return append([]*gql.GraphQuery{finalMainQuery}, dgQuery...)
}
func passwordQuery(m schema.Query, authRw *authRewriter) ([]*gql.GraphQuery, error) {
xid, uid, err := m.IDArgValue()
if err != nil {
return nil, err
}
dgQuery := rewriteAsGet(m, uid, xid, authRw)
// Handle empty dgQuery
if strings.HasSuffix(dgQuery[0].Attr, "()") {
return dgQuery, nil
}
// mainQuery is the query with check<Type>Password as Attr.
// It is the first in the list of dgQuery.
mainQuery := dgQuery[0]
queriedType := m.Type()
name := queriedType.PasswordField().Name()
predicate := queriedType.DgraphPredicate(name)
password := m.ArgValue(name).(string)
// This adds the checkPwd function
op := &gql.GraphQuery{
Attr: "checkPwd",
Func: mainQuery.Func,
Filter: mainQuery.Filter,
Children: []*gql.GraphQuery{{
Var: "pwd",
Attr: fmt.Sprintf(`checkpwd(%s, "%s")`, predicate,
password),
}},
}
ft := &gql.FilterTree{
Op: "and",
Child: []*gql.FilterTree{{
Func: &gql.Function{
Name: "eq",
Args: []gql.Arg{
{
Value: "val(pwd)",
},
{
Value: "1",
},
},
},
}},
}
if mainQuery.Filter != nil {
ft.Child = append(ft.Child, mainQuery.Filter)
}
mainQuery.Filter = ft
return append(dgQuery, op), nil
}
func intersection(a, b []uint64) []uint64 {
m := make(map[uint64]bool)
var c []uint64
for _, item := range a {
m[item] = true
}
for _, item := range b {
if _, ok := m[item]; ok {
c = append(c, item)
}
}
return c
}
// addUID adds UID for every node that we query. Otherwise we can't tell the
// difference in a query result between a node that's missing and a node that's
// missing a single value. E.g. if we are asking for an Author and only the
// 'text' of all their posts e.g. getAuthor(id: 0x123) { posts { text } }
// If the author has 10 posts but three of them have a title, but no text,
// then Dgraph would just return 7 posts. And we'd have no way of knowing if
// there's only 7 posts, or if there's more that are missing 'text'.
// But, for GraphQL, we want to know about those missing values.
func addUID(dgQuery *gql.GraphQuery) {
if len(dgQuery.Children) == 0 {
return
}
hasUid := false
for _, c := range dgQuery.Children {
if c.Attr == "uid" {
hasUid = true
}
addUID(c)
}
// If uid was already requested by the user then we don't need to add it again.
if hasUid {
return
}
uidChild := &gql.GraphQuery{
Attr: "uid",
Alias: "dgraph.uid",
}
dgQuery.Children = append(dgQuery.Children, uidChild)
}
func rewriteAsQueryByIds(
field schema.Field,
uids []uint64,
authRw *authRewriter) []*gql.GraphQuery {
if field == nil {
return nil
}
rbac := authRw.evaluateStaticRules(field.Type())
dgQuery := []*gql.GraphQuery{{
Attr: field.DgraphAlias(),
}}
if rbac == schema.Negative {
dgQuery[0].Attr = dgQuery[0].Attr + "()"
return dgQuery
}
dgQuery[0].Func = &gql.Function{
Name: "uid",
UID: uids,
}
if ids := idFilter(extractQueryFilter(field), field.Type().IDField()); ids != nil {
addUIDFunc(dgQuery[0], intersection(ids, uids))
}
addArgumentsToField(dgQuery[0], field)
// The function getQueryByIds is called for passwordQuery or fetching query result types
// after making a mutation. In both cases, we want the selectionSet to use the `query` auth
// rule. queryAuthSelector function is used as selector before calling addSelectionSetFrom function.
// The original selector function of authRw is stored in oldAuthSelector and used after returning
// from addSelectionSetFrom function.
oldAuthSelector := authRw.selector
authRw.selector = queryAuthSelector
selectionAuth := addSelectionSetFrom(dgQuery[0], field, authRw)
authRw.selector = oldAuthSelector
addUID(dgQuery[0])
addCascadeDirective(dgQuery[0], field)
dgQuery = authRw.addAuthQueries(field.Type(), dgQuery, rbac)
if len(selectionAuth) > 0 {
dgQuery = append(dgQuery, selectionAuth...)
}
return dgQuery
}
// addArgumentsToField adds various different arguments to a field, such as
// filter, order and pagination.
func addArgumentsToField(dgQuery *gql.GraphQuery, field schema.Field) {
filter, _ := field.ArgValue("filter").(map[string]interface{})
_ = addFilter(dgQuery, field.Type(), filter)
addOrder(dgQuery, field)
addPagination(dgQuery, field)
}
func addTopLevelTypeFilter(query *gql.GraphQuery, field schema.Field) {
addTypeFilter(query, field.Type())
}
func rewriteAsGet(
query schema.Query,
uid uint64,
xid *string,
auth *authRewriter) []*gql.GraphQuery {
var dgQuery []*gql.GraphQuery
rbac := auth.evaluateStaticRules(query.Type())
// If Get query is for Type and none of the authrules are satisfied, then it is
// caught here but in case of interface, we need to check validity on each
// implementing type as Rules for the interface are made empty.
if rbac == schema.Negative {
return []*gql.GraphQuery{{Attr: query.DgraphAlias() + "()"}}
}
// For interface, empty query should be returned if Auth rules are
// not satisfied even for a single implementing type
if query.Type().IsInterface() {
implementingTypesHasFailedRules := false
implementingTypes := query.Type().ImplementingTypes()
for _, typ := range implementingTypes {
if auth.evaluateStaticRules(typ) != schema.Negative {
implementingTypesHasFailedRules = true
}
}
if !implementingTypesHasFailedRules {
return []*gql.GraphQuery{{Attr: query.Name() + "()"}}
}
}
if xid == nil {
dgQuery = rewriteAsQueryByIds(query, []uint64{uid}, auth)
// Add the type filter to the top level get query. When the auth has been written into the
// query the top level get query may be present in query's children.
addTopLevelTypeFilter(dgQuery[0], query)
return dgQuery
}
xidArgName := query.XIDArg()
eqXidFunc := &gql.Function{
Name: "eq",
Args: []gql.Arg{
{Value: xidArgName},
{Value: maybeQuoteArg("eq", *xid)},
},
}
if uid > 0 {
dgQuery = []*gql.GraphQuery{{
Attr: query.DgraphAlias(),
Func: &gql.Function{
Name: "uid",
UID: []uint64{uid},
},
}}
dgQuery[0].Filter = &gql.FilterTree{
Func: eqXidFunc,
}
} else {
dgQuery = []*gql.GraphQuery{{
Attr: query.DgraphAlias(),
Func: eqXidFunc,
}}
}
// Apply query auth rules even for password query
oldAuthSelector := auth.selector
auth.selector = queryAuthSelector
selectionAuth := addSelectionSetFrom(dgQuery[0], query, auth)
auth.selector = oldAuthSelector
addUID(dgQuery[0])
addTypeFilter(dgQuery[0], query.Type())
addCascadeDirective(dgQuery[0], query)
dgQuery = auth.addAuthQueries(query.Type(), dgQuery, rbac)
if len(selectionAuth) > 0 {
dgQuery = append(dgQuery, selectionAuth...)
}
return dgQuery
}
// Adds common RBAC and UID, Type rules to DQL query.
// This function is used by rewriteAsQuery and aggregateQuery functions
func addCommonRules(
field schema.Field,
fieldType schema.Type,
authRw *authRewriter) ([]*gql.GraphQuery, schema.RuleResult) {
rbac := authRw.evaluateStaticRules(fieldType)
dgQuery := &gql.GraphQuery{
Attr: field.DgraphAlias(),
}
if rbac == schema.Negative {
dgQuery.Attr = dgQuery.Attr + "()"
return []*gql.GraphQuery{dgQuery}, rbac
}
if authRw != nil && (authRw.isWritingAuth || authRw.filterByUid) && (authRw.varName != "" || authRw.parentVarName != "") {
// When rewriting auth rules, they always start like
// Todo2 as var(func: uid(Todo1)) @cascade {
// Where Todo1 is the variable generated from the filter of the field
// we are adding auth to.
authRw.addVariableUIDFunc(dgQuery)
// This is executed when querying while performing delete mutation request since
// in case of delete mutation we already have variable `MutationQueryVar` at root level.
if authRw.filterByUid {
// Since the variable is only added at the top level we reset the `authRW` variables.
authRw.varName = ""
authRw.filterByUid = false
}
} else if ids := idFilter(extractQueryFilter(field), fieldType.IDField()); ids != nil {
addUIDFunc(dgQuery, ids)
} else {
addTypeFunc(dgQuery, fieldType.DgraphName())
}
return []*gql.GraphQuery{dgQuery}, rbac
}
func rewriteAsQuery(field schema.Field, authRw *authRewriter) []*gql.GraphQuery {
dgQuery, rbac := addCommonRules(field, field.Type(), authRw)
if rbac == schema.Negative {
return dgQuery
}
addArgumentsToField(dgQuery[0], field)
selectionAuth := addSelectionSetFrom(dgQuery[0], field, authRw)
// we don't need to query uid for auth queries, as they always have at least one field in their
// selection set.
if !authRw.writingAuth() {
addUID(dgQuery[0])
}
addCascadeDirective(dgQuery[0], field)
dgQuery = authRw.addAuthQueries(field.Type(), dgQuery, rbac)
if len(selectionAuth) > 0 {
return append(dgQuery, selectionAuth...)
}
return dgQuery
}
func (authRw *authRewriter) writingAuth() bool {
return authRw != nil && authRw.isWritingAuth
}
// addAuthQueries takes a field and the GraphQuery that has so far been constructed for
// the field and builds any auth queries that are need to restrict the result to only
// the nodes authorized to be queried, returning a new graphQuery that does the
// original query and the auth.
func (authRw *authRewriter) addAuthQueries(
typ schema.Type,
dgQuery []*gql.GraphQuery,
rbacEval schema.RuleResult) []*gql.GraphQuery {
// There's no need to recursively inject auth queries into other auth queries, so if
// we are already generating an auth query, there's nothing to add.
if authRw == nil || authRw.isWritingAuth {
return dgQuery
}
authRw.varName = authRw.varGen.Next(typ, "", "", authRw.isWritingAuth)
fldAuthQueries, filter := authRw.rewriteAuthQueries(typ)
// If We are adding AuthRules on an Interfaces's operation,
// we need to construct auth filters by verifying Auth rules on the
// implementing types.
if typ.IsInterface() {
// First we fetch the list of Implementing types here
implementingTypes := make([]schema.Type, 0)
implementingTypes = append(implementingTypes, typ.ImplementingTypes()...)
var qrys []*gql.GraphQuery
var filts []*gql.FilterTree
implementingTypesHasAuthRules := false
for _, object := range implementingTypes {
// It could be the case that None of implementing Types have Auth Rules, which clearly
// indicates that neither the interface, nor any of the implementing type has its own
// Auth rules.
// ImplementingTypeHasAuthRules is set to true even if one of the implemented type have
// Auth rules or Interface has its own auth rule, in the latter case, all the
// implemented types must have inherited those auth rules.
if object.AuthRules().Rules != nil {
implementingTypesHasAuthRules = true
}
// First Check if the Auth Rules of the given type are satisfied or not.
// It might be possible that auth rule inherited from some other interface
// is not being satisfied. In that case we have to Drop this type
rbac := authRw.evaluateStaticRules(object)
if rbac == schema.Negative {
continue
}
// Form Query Like Todo1 as var(func: type(Todo))
queryVar := object.Name() + "1"
varQry := &gql.GraphQuery{
Attr: "var",
Var: queryVar,
Func: &gql.Function{
Name: "type",
Args: []gql.Arg{{Value: object.Name()}},
},
}
qrys = append(qrys, varQry)
// Form Auth Queries for the given object
objAuthQueries, objfilter := (&authRewriter{
authVariables: authRw.authVariables,
varGen: authRw.varGen,
varName: queryVar,
selector: authRw.selector,
parentVarName: authRw.parentVarName,
hasAuthRules: authRw.hasAuthRules,
}).rewriteAuthQueries(object)
// 1. If there is no Auth Query for the Given type then it means that
// neither the inherited interface, nor this type has any Auth rules.
// In this case the query must return all the nodes of this type.
// then simply we need to Put uid(Todo1) with OR in the main query filter.
// 2. If rbac evaluates to `Positive` which means RBAC rule is satisfied.
// Either it is the only auth rule, or it is present with `OR`, which means
// query must return all the nodes of this type.
if len(objAuthQueries) == 0 || rbac == schema.Positive {
objfilter = &gql.FilterTree{
Func: &gql.Function{
Name: "uid",
Args: []gql.Arg{{Value: queryVar, IsValueVar: false, IsGraphQLVar: false}},
},
}
filts = append(filts, objfilter)
} else {
qrys = append(qrys, objAuthQueries...)
filts = append(filts, objfilter)
}
}
// For an interface having Auth rules in some of the implementing types, len(qrys) = 0
// indicates that None of the type satisfied the Auth rules, We must return Empty Query here.
if implementingTypesHasAuthRules == true && len(qrys) == 0 {
return []*gql.GraphQuery{{
Attr: dgQuery[0].Attr + "()",
}}
}
// Join all the queries in qrys using OR filter and
// append these queries into fldAuthQueries
fldAuthQueries = append(fldAuthQueries, qrys...)
objOrfilter := &gql.FilterTree{
Op: "or",
Child: filts,
}
// if filts is non empty, which means it was a query on interface
// having Either any of the types satisfying auth rules or having
// some type with no Auth rules, In this case, the query will be different
// and will look somewhat like this:
// PostRoot as var(func: uid(Post1)) @filter((uid(QuestionAuth2) OR uid(AnswerAuth4)))
if len(filts) > 0 {
filter = objOrfilter
}
// Adding the case of Query on interface in which None of the implementing type have
// Auth Query Rules, in that case, we also return simple query.
if typ.IsInterface() == true && implementingTypesHasAuthRules == false {
return dgQuery
}
}
if len(fldAuthQueries) == 0 && !authRw.hasAuthRules {
return dgQuery
}
if rbacEval != schema.Uncertain {
fldAuthQueries = nil
filter = nil
}
// build a query like
// Todo1 as var(func: ... ) @filter(...)
// that has the filter from the user query in it. This is then used as
// the starting point for other auth queries.
//
// We already have the query, so just copy it and modify the original
varQry := &gql.GraphQuery{
Var: authRw.varName,
Attr: "var",
Func: dgQuery[0].Func,
Filter: dgQuery[0].Filter,
}
// build the root auth query like
// TodoRoot as var(func: uid(Todo1), orderasc: ..., first: ..., offset: ...) @filter(... type auth queries ...)
// that has the order and pagination params from user query in it and filter set to auth
// queries built for this type. This is then used as the starting point for user query and
// auth queries for children.
rootQry := &gql.GraphQuery{
Var: authRw.parentVarName,
Attr: "var",
Func: &gql.Function{
Name: "uid",
Args: []gql.Arg{{Value: authRw.varName}},
},
Filter: filter,
Order: dgQuery[0].Order, // we need the order here for pagination to work correctly
Args: dgQuery[0].Args, // this gets pagination from user query to root query
}
// The user query doesn't need the filter and pagination parameters anymore,
// as they have been taken care of by the var and root queries generated above.
// But, tt still needs the order parameter, even though it is also applied in root query.
// So, not setting order to nil.
dgQuery[0].Filter = nil
dgQuery[0].Args = nil
// The user query starts from the root query generated above and so gets filtered
// input from auth processing, so now we build
// queryTodo(func: uid(TodoRoot), ...) { ... }
dgQuery[0].Func = &gql.Function{
Name: "uid",
Args: []gql.Arg{{Value: authRw.parentVarName}},
}
// The final query that includes the user's filter and auth processing is thus like
//
// queryTodo(func: uid(Todo1)) @filter(uid(Todo2) AND uid(Todo3)) { ... }
// Todo1 as var(func: ... ) @filter(...)
// Todo2 as var(func: uid(Todo1)) @cascade { ...auth query 1... }
// Todo3 as var(func: uid(Todo1)) @cascade { ...auth query 2... }
ret := append(dgQuery, rootQry, varQry)
ret = append(ret, fldAuthQueries...)
return ret
}
func (authRw *authRewriter) addVariableUIDFunc(q *gql.GraphQuery) {
varName := authRw.parentVarName
if authRw.varName != "" {
varName = authRw.varName
}
q.Func = &gql.Function{
Name: "uid",
Args: []gql.Arg{{Value: varName}},
}
}
func queryAuthSelector(t schema.Type) *schema.RuleNode {
auth := t.AuthRules()
if auth == nil || auth.Rules == nil {
return nil
}
return auth.Rules.Query
}
// passwordAuthSelector is used as auth selector for checkPassword queries
func passwordAuthSelector(t schema.Type) *schema.RuleNode {
auth := t.AuthRules()
if auth == nil || auth.Rules == nil {
return nil
}
return auth.Rules.Password
}
func (authRw *authRewriter) rewriteAuthQueries(typ schema.Type) ([]*gql.GraphQuery, *gql.FilterTree) {
if authRw == nil || authRw.isWritingAuth {
return nil, nil
}
return (&authRewriter{
authVariables: authRw.authVariables,
varGen: authRw.varGen,
isWritingAuth: true,
varName: authRw.varName,
selector: authRw.selector,
parentVarName: authRw.parentVarName,
hasAuthRules: authRw.hasAuthRules,
}).rewriteRuleNode(typ, authRw.selector(typ))
}
func (authRw *authRewriter) evaluateStaticRules(typ schema.Type) schema.RuleResult {
if authRw == nil || authRw.isWritingAuth {
return schema.Uncertain
}
rn := authRw.selector(typ)
return rn.EvaluateStatic(authRw.authVariables)
}
func (authRw *authRewriter) rewriteRuleNode(
typ schema.Type,
rn *schema.RuleNode) ([]*gql.GraphQuery, *gql.FilterTree) {
if typ == nil || rn == nil {
return nil, nil
}
nodeList := func(
typ schema.Type,
rns []*schema.RuleNode) ([]*gql.GraphQuery, []*gql.FilterTree) {
var qrys []*gql.GraphQuery
var filts []*gql.FilterTree
for _, orRn := range rns {
q, f := authRw.rewriteRuleNode(typ, orRn)
qrys = append(qrys, q...)
if f != nil {
filts = append(filts, f)
}
}
return qrys, filts
}
switch {
case len(rn.And) > 0:
qrys, filts := nodeList(typ, rn.And)
if len(filts) == 0 {
return qrys, nil
}
if len(filts) == 1 {
return qrys, filts[0]
}
return qrys, &gql.FilterTree{
Op: "and",
Child: filts,
}
case len(rn.Or) > 0:
qrys, filts := nodeList(typ, rn.Or)
if len(filts) == 0 {
return qrys, nil