-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
mutation.go
757 lines (679 loc) · 25.5 KB
/
mutation.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
/*
* 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"
"encoding/json"
"fmt"
"sort"
"strconv"
dgoapi "github.com/dgraph-io/dgo/v210/protos/api"
"github.com/dgraph-io/dgraph/gql"
"github.com/dgraph-io/dgraph/graphql/dgraph"
"github.com/dgraph-io/dgraph/graphql/schema"
"github.com/dgraph-io/dgraph/x"
"github.com/golang/glog"
"github.com/pkg/errors"
otrace "go.opencensus.io/trace"
)
const touchedUidsKey = "_total"
// Mutations come in like this with variables:
//
// mutation themutation($post: PostInput!) {
// addPost(input: $post) { ... some query ...}
// }
// - with variable payload
// { "post":
// { "title": "My Post",
// "author": { authorID: 0x123 },
// ...
// }
// }
//
//
// Or, like this with the payload in the mutation arguments
//
// mutation themutation {
// addPost(input: { title: ... }) { ... some query ...}
// }
//
//
// Either way we build up a Dgraph json mutation to add the object
//
// For now, all mutations are only 1 level deep (cause of how we build the
// input objects) and only create a single node (again cause of inputs)
// A MutationResolver can resolve a single mutation.
type MutationResolver interface {
Resolve(ctx context.Context, mutation schema.Mutation) (*Resolved, bool)
}
// A MutationRewriter can transform a GraphQL mutation into a Dgraph mutation and
// can build a Dgraph gql.GraphQuery to follow a GraphQL mutation.
//
// Mutations come in like:
//
// mutation addAuthor($auth: AuthorInput!) {
// addAuthor(input: $auth) {
// author {
// id
// name
// }
// }
// }
//
// Where `addAuthor(input: $auth)` implies a mutation that must get run - written
// to a Dgraph mutation by Rewrite. The GraphQL following `addAuthor(...)`implies
// a query to run and return the newly created author, so the
// mutation query rewriting is dependent on the context set up by the result of
// the mutation.
type MutationRewriter interface {
// RewriteQueries generates and rewrites GraphQL mutation m into DQL queries which
// check if any referenced node by XID or ID exist or not.
// Instead of filtering on dgraph.type like @filter(type(Parrot)), we query `dgraph.type` and
// filter it on GraphQL side. @filter(type(Parrot)) is costly in terms of memory and cpu.
// Example existence queries:
// 1. Parrot1(func: uid(0x127)) {
// uid
// dgraph.type
// }
// 2. Computer2(func: eq(Computer.name, "computer1")) {
// uid
// dgraph.type
// }
// These query will be created in case of Add or Update Mutation which references node
// 0x127 or Computer of name "computer1"
RewriteQueries(ctx context.Context, m schema.Mutation) ([]*gql.GraphQuery, []string, error)
// Rewrite rewrites GraphQL mutation m into a Dgraph mutation - that could
// be as simple as a single DelNquads, or could be a Dgraph upsert mutation
// with a query and multiple mutations guarded by conditions.
Rewrite(ctx context.Context, m schema.Mutation, idExistence map[string]string) ([]*UpsertMutation, error)
// FromMutationResult takes a GraphQL mutation and the results of a Dgraph
// mutation and constructs a Dgraph query. It's used to find the return
// value from a GraphQL mutation - i.e. we've run the mutation indicated by m
// now we need to query Dgraph to satisfy all the result fields in m.
FromMutationResult(
ctx context.Context,
m schema.Mutation,
assigned map[string]string,
result map[string]interface{}) ([]*gql.GraphQuery, error)
// MutatedRootUIDs returns a list of Root UIDs that were mutated as part of the mutation.
MutatedRootUIDs(
mutation schema.Mutation,
assigned map[string]string,
result map[string]interface{}) []string
}
// A DgraphExecutor can execute a query/mutation and returns the request response and any errors.
type DgraphExecutor interface {
// Execute performs the actual query/mutation and returns a Dgraph response. If an error
// occurs, that indicates that the execution failed in some way significant enough
// way as to not continue processing this query/mutation or others in the same request.
Execute(ctx context.Context, req *dgoapi.Request, field schema.Field) (*dgoapi.Response, error)
CommitOrAbort(ctx context.Context, tc *dgoapi.TxnContext) (*dgoapi.TxnContext, error)
}
// An UpsertMutation is the query and mutations needed for a Dgraph upsert.
// The node types is a blank node name -> Type mapping of nodes that could
// be created by the upsert.
type UpsertMutation struct {
Query []*gql.GraphQuery
Mutations []*dgoapi.Mutation
NewNodes map[string]schema.Type
}
// DgraphExecutorFunc is an adapter that allows us to compose dgraph execution and
// build a QueryExecuter from a function. Based on the http.HandlerFunc pattern.
type DgraphExecutorFunc func(ctx context.Context, req *dgoapi.Request) (*dgoapi.Response, error)
// Execute calls qe(ctx, query)
func (ex DgraphExecutorFunc) Execute(
ctx context.Context,
req *dgoapi.Request) (*dgoapi.Response, error) {
return ex(ctx, req)
}
// MutationResolverFunc is an adapter that allows to build a MutationResolver from
// a function. Based on the http.HandlerFunc pattern.
type MutationResolverFunc func(ctx context.Context, m schema.Mutation) (*Resolved, bool)
// Resolve calls mr(ctx, mutation)
func (mr MutationResolverFunc) Resolve(ctx context.Context, m schema.Mutation) (*Resolved, bool) {
return mr(ctx, m)
}
// NewDgraphResolver creates a new mutation resolver. The resolver runs the pipeline:
// 1) rewrite the mutation using mr (return error if failed)
// 2) execute the mutation with me (return error if failed)
// 3) write a query for the mutation with mr (return error if failed)
// 4) execute the query with qe (return error if failed)
func NewDgraphResolver(mr MutationRewriter, ex DgraphExecutor) MutationResolver {
return &dgraphResolver{
mutationRewriter: mr,
executor: ex,
}
}
// mutationResolver can resolve a single GraphQL mutation field
type dgraphResolver struct {
mutationRewriter MutationRewriter
executor DgraphExecutor
}
func (mr *dgraphResolver) Resolve(ctx context.Context, m schema.Mutation) (*Resolved, bool) {
span := otrace.FromContext(ctx)
stop := x.SpanTimer(span, "resolveMutation")
defer stop()
if span != nil {
span.Annotatef(nil, "mutation alias: [%s] type: [%s]", m.Alias(), m.MutationType())
}
resolverTrace := &schema.ResolverTrace{
Path: []interface{}{m.ResponseName()},
ParentType: "Mutation",
FieldName: m.ResponseName(),
ReturnType: m.Type().String(),
}
timer := newtimer(ctx, &resolverTrace.OffsetDuration)
timer.Start()
defer timer.Stop()
resolved, success := mr.rewriteAndExecute(ctx, m)
resolverTrace.Dgraph = resolved.Extensions.Tracing.Execution.Resolvers[0].Dgraph
resolved.Extensions.Tracing.Execution.Resolvers[0] = resolverTrace
return resolved, success
}
func getNumUids(m schema.Mutation, a map[string]string, r map[string]interface{}) int {
switch m.MutationType() {
case schema.AddMutation:
return len(a)
default:
mutated := extractMutated(r, m.Name())
return len(mutated)
}
}
func (mr *dgraphResolver) rewriteAndExecute(
ctx context.Context,
mutation schema.Mutation) (*Resolved, bool) {
var mutResp, qryResp *dgoapi.Response
req := &dgoapi.Request{}
commit := false
defer func() {
if !commit && mutResp != nil && mutResp.Txn != nil {
mutResp.Txn.Aborted = true
_, err := mr.executor.CommitOrAbort(ctx, mutResp.Txn)
if err != nil {
glog.Errorf("Error occurred while aborting transaction: %s", err)
}
}
}()
dgraphPreMutationQueryDuration := &schema.LabeledOffsetDuration{Label: "preMutationQuery"}
dgraphMutationDuration := &schema.LabeledOffsetDuration{Label: "mutation"}
dgraphPostMutationQueryDuration := &schema.LabeledOffsetDuration{Label: "query"}
ext := &schema.Extensions{
Tracing: &schema.Trace{
Execution: &schema.ExecutionTrace{
Resolvers: []*schema.ResolverTrace{
{
Dgraph: []*schema.LabeledOffsetDuration{
dgraphPreMutationQueryDuration,
dgraphMutationDuration,
dgraphPostMutationQueryDuration,
},
},
},
},
},
}
emptyResult := func(err error) *Resolved {
return &Resolved{
// all the standard mutations are nullable objects, so Data should pretty-much be
// {"mutAlias":null} everytime.
Data: mutation.NullResponse(),
Field: mutation,
// there is no completion down the pipeline, so error's path should be prepended with
// mutation's alias before returning the response.
Err: schema.PrependPath(err, mutation.ResponseName()),
Extensions: ext,
}
}
// upserts stores rewritten []*UpsertMutation by Rewrite function. These mutations
// are then executed and the results processed and returned.
var upserts []*UpsertMutation
var err error
// queries stores rewritten []*gql.GraphQuery by RewriteQueries function. These queries
// are then executed and the results are processed
var queries []*gql.GraphQuery
var filterTypes []string
queries, filterTypes, err = mr.mutationRewriter.RewriteQueries(ctx, mutation)
if err != nil {
return emptyResult(schema.GQLWrapf(err, "couldn't rewrite mutation %s", mutation.Name())),
resolverFailed
}
// Execute queries and parse its result into a map
qry := dgraph.AsString(queries)
req.Query = qry
// The query will be empty in case there is no reference XID / UID in the mutation.
// Don't execute the query in those cases.
// The query will also be empty in case this is not an Add or an Update Mutation.
if req.Query != "" {
// Executing and processing existence queries
queryTimer := newtimer(ctx, &dgraphPreMutationQueryDuration.OffsetDuration)
queryTimer.Start()
mutResp, err = mr.executor.Execute(ctx, req, nil)
queryTimer.Stop()
if err != nil {
gqlErr := schema.GQLWrapLocationf(
err, mutation.Location(), "mutation %s failed", mutation.Name())
return emptyResult(gqlErr), resolverFailed
}
ext.TouchedUids += mutResp.GetMetrics().GetNumUids()[touchedUidsKey]
}
// Parse the result of query.
// mutResp.Json will contain response to the query.
// The response is parsed to existenceQueriesResult
// dgraph.type is a list that contains types and interfaces the type implements.
// Example Response:
// {
// Project_1 :
// [
// {
// "uid" : "0x123",
// "dgraph.type" : ["Project", "Work"]
// }
// ],
// Column_2 :
// [
// {
// "uid": "0x234",
// "dgraph.type" : ["Column"]
// }
// ]
// }
type res struct {
Uid string `json:"uid"`
Types []string `json:"dgraph.type"`
}
queryResultMap := make(map[string][]res)
if mutResp != nil {
err = json.Unmarshal(mutResp.Json, &queryResultMap)
}
if err != nil {
gqlErr := schema.GQLWrapLocationf(
err, mutation.Location(), "mutation %s failed", mutation.Name())
return emptyResult(gqlErr), resolverFailed
}
x.AssertTrue(len(filterTypes) == len(queries))
// qNameToType map contains the mapping from the query name to type/interface the query response
// has to be filtered upon.
qNameToType := make(map[string]string)
for i, typ := range filterTypes {
qNameToType[queries[i].Attr] = typ
}
// The above response is parsed into map[string]string as follows:
// {
// "Project_1" : "0x123",
// "Column_2" : "0x234"
// }
// As only Add and Update mutations generate queries using RewriteQueries,
// qNameToUID map will be non-empty only in case of Add or Update Mutation.
qNameToUID := make(map[string]string)
for key, result := range queryResultMap {
count := 0
typ := qNameToType[key]
for _, res := range result {
if x.HasString(res.Types, typ) {
qNameToUID[key] = res.Uid
count++
}
}
if count > 1 {
// Found multiple UIDs for query. This should ideally not happen.
// This indicates that there are multiple nodes with same XIDs / UIDs. Throw an error.
err = errors.New(fmt.Sprintf("Found multiple nodes with ID: %s", qNameToUID[key]))
gqlErr := schema.GQLWrapLocationf(
err, mutation.Location(), "mutation %s failed", mutation.Name())
return emptyResult(gqlErr), resolverFailed
}
}
// Create upserts, delete mutations, update mutations, add mutations.
upserts, err = mr.mutationRewriter.Rewrite(ctx, mutation, qNameToUID)
if err != nil {
return emptyResult(schema.GQLWrapf(err, "couldn't rewrite mutation %s", mutation.Name())),
resolverFailed
}
if len(upserts) == 0 {
return &Resolved{
Data: completeMutationResult(mutation, nil, 0),
Field: mutation,
Err: nil,
Extensions: ext,
}, resolverSucceeded
}
// For delete mutation, if query field is requested, there will be two upserts, the second one
// isn't needed for mutation, it only has the query to fetch the query field.
// We need to execute this query before the mutation to find out the query field.
var queryErrs error
if mutation.MutationType() == schema.DeleteMutation {
if qryField := mutation.QueryField(); qryField != nil {
dgQuery := upserts[1].Query
upserts = upserts[0:1] // we don't need the second upsert anymore
queryTimer := newtimer(ctx, &dgraphPostMutationQueryDuration.OffsetDuration)
queryTimer.Start()
qryResp, err = mr.executor.Execute(ctx, &dgoapi.Request{Query: dgraph.AsString(dgQuery),
ReadOnly: true}, qryField)
queryTimer.Stop()
if err != nil && !x.IsGqlErrorList(err) {
return emptyResult(schema.GQLWrapf(err, "couldn't execute query for mutation %s",
mutation.Name())), resolverFailed
} else {
queryErrs = err
}
ext.TouchedUids += qryResp.GetMetrics().GetNumUids()[touchedUidsKey]
}
}
result := make(map[string]interface{})
newNodes := make(map[string]schema.Type)
mutationTimer := newtimer(ctx, &dgraphMutationDuration.OffsetDuration)
mutationTimer.Start()
for _, upsert := range upserts {
req.Query = dgraph.AsString(upsert.Query)
req.Mutations = upsert.Mutations
mutResp, err = mr.executor.Execute(ctx, req, nil)
if err != nil {
gqlErr := schema.GQLWrapLocationf(
err, mutation.Location(), "mutation %s failed", mutation.Name())
return emptyResult(gqlErr), resolverFailed
}
ext.TouchedUids += mutResp.GetMetrics().GetNumUids()[touchedUidsKey]
if req.Query != "" && len(mutResp.GetJson()) != 0 {
if err := json.Unmarshal(mutResp.GetJson(), &result); err != nil {
return emptyResult(
schema.GQLWrapf(err, "Couldn't unmarshal response from Dgraph mutation")),
resolverFailed
}
}
// for update mutation, if @id field is present in set then we check that
// in filter only one node is selected. if there are multiple nodes selected,
// then it's not possible to update all of them with same value of @id fields.
// In that case we return error
if mutation.MutationType() == schema.UpdateMutation {
inp := mutation.ArgValue(schema.InputArgName).(map[string]interface{})
setArg := inp["set"]
objSet, okSetArg := setArg.(map[string]interface{})
if len(objSet) == 0 && okSetArg {
return emptyResult(
schema.GQLWrapf(errors.Errorf("not able to find set args"+
" in update mutation"),
"mutation %s failed", mutation.Name())),
resolverFailed
}
mutatedType := mutation.MutatedType()
var xidsPresent bool
if len(objSet) != 0 {
for _, xid := range mutatedType.XIDFields() {
if xidVal, ok := objSet[xid.Name()]; ok && xidVal != nil {
xidsPresent = true
}
}
}
// if @id field is present in set and there are multiple nodes returned from
// upsert query then we return error
if xidsPresent && len(result[mutation.Name()].([]interface{})) > 1 {
if queryAuthSelector(mutatedType) == nil {
return emptyResult(
schema.GQLWrapf(errors.Errorf("only one node is allowed in"+
" the filter while updating fields with @id directive"),
"mutation %s failed", mutation.Name())),
resolverFailed
}
return emptyResult(
schema.GQLWrapf(errors.Errorf("GraphQL debug: only one node is"+
" allowed in the filter while updating fields with @id directive"),
"mutation %s failed", mutation.Name())),
resolverFailed
}
}
copyTypeMap(upsert.NewNodes, newNodes)
}
mutationTimer.Stop()
authErr := authorizeNewNodes(ctx, mutation, mutResp.Uids, newNodes, mr.executor, mutResp.Txn)
if authErr != nil {
return emptyResult(schema.GQLWrapf(authErr, "mutation failed")), resolverFailed
}
var dgQuery []*gql.GraphQuery
dgQuery, err = mr.mutationRewriter.FromMutationResult(ctx, mutation, mutResp.GetUids(), result)
queryErrs = schema.AppendGQLErrs(queryErrs, schema.GQLWrapf(err,
"couldn't rewrite query for mutation %s", mutation.Name()))
if err != nil {
return emptyResult(queryErrs), resolverFailed
}
txnCtx, err := mr.executor.CommitOrAbort(ctx, mutResp.Txn)
if err != nil {
return emptyResult(
schema.GQLWrapf(err, "mutation failed, couldn't commit transaction")),
resolverFailed
}
commit = true
// once committed, send async updates to configured webhooks, if any.
if mutation.HasLambdaOnMutate() {
rootUIDs := mr.mutationRewriter.MutatedRootUIDs(mutation, mutResp.GetUids(), result)
// NOTE: This is an async operation. We can't extract logs from webhooks.
go sendWebhookEvent(ctx, mutation, txnCtx.CommitTs, rootUIDs)
}
// For delete mutation, we would have already populated qryResp if query field was requested.
if mutation.MutationType() != schema.DeleteMutation {
queryTimer := newtimer(ctx, &dgraphPostMutationQueryDuration.OffsetDuration)
queryTimer.Start()
qryResp, err = mr.executor.Execute(ctx, &dgoapi.Request{Query: dgraph.AsString(dgQuery),
ReadOnly: true}, mutation.QueryField())
queryTimer.Stop()
if !x.IsGqlErrorList(err) {
err = schema.GQLWrapf(err, "couldn't execute query for mutation %s", mutation.Name())
}
queryErrs = schema.AppendGQLErrs(queryErrs, err)
ext.TouchedUids += qryResp.GetMetrics().GetNumUids()[touchedUidsKey]
}
numUids := getNumUids(mutation, mutResp.Uids, result)
return &Resolved{
Data: completeMutationResult(mutation, qryResp.GetJson(), numUids),
Field: mutation,
// the error path only contains the query field, so we prepend the mutation response name
Err: schema.PrependPath(queryErrs, mutation.ResponseName()),
Extensions: ext,
}, resolverSucceeded
}
// completeMutationResult takes in the result returned for the query field of mutation and builds
// the JSON required for data field in GraphQL response.
// The input qryResult can either be nil or of the form:
// {"qryFieldAlias":...}
// and the output will look like:
// {"addAuthor":{"qryFieldAlias":...,"numUids":2,"msg":"Deleted"}}
func completeMutationResult(mutation schema.Mutation, qryResult []byte, numUids int) []byte {
comma := ""
var buf bytes.Buffer
x.Check2(buf.WriteRune('{'))
mutation.CompleteAlias(&buf)
x.Check2(buf.WriteRune('{'))
// Our standard MutationPayloads consist of only the following fields:
// * queryField
// * numUids
// * msg (only for DeleteMutationPayload)
// And __typename can be present anywhere. So, build data accordingly.
// Note that all these fields are nullable, so no need to raise non-null errors.
for _, f := range mutation.SelectionSet() {
x.Check2(buf.WriteString(comma))
f.CompleteAlias(&buf)
switch f.Name() {
case schema.Typename:
x.Check2(buf.WriteString(`"` + f.TypeName(nil) + `"`))
case schema.Msg:
if numUids == 0 {
x.Check2(buf.WriteString(`"No nodes were deleted"`))
} else {
x.Check2(buf.WriteString(`"Deleted"`))
}
case schema.NumUid:
// Although theoretically it is possible that numUids can be out of the int32 range but
// we don't need to apply coercion rules here as per Int type because carrying out a
// mutation which mutates more than 2 billion uids doesn't seem a practical case.
// So, we are skipping coercion here.
x.Check2(buf.WriteString(strconv.Itoa(numUids)))
default: // this has to be queryField
if len(qryResult) == 0 {
// don't write null, instead write [] as query field is always a nullable list
x.Check2(buf.Write(schema.JsonEmptyList))
} else {
// need to write only the value returned for query field, so need to remove the JSON
// key till colon (:) and also the ending brace }.
// 4 = {"":
x.Check2(buf.Write(qryResult[4+len(f.ResponseName()) : len(qryResult)-1]))
}
}
comma = ","
}
x.Check2(buf.WriteString("}}"))
return buf.Bytes()
}
// authorizeNewNodes takes the new nodes (uids) actually created by a GraphQL mutation and
// the types that mutation rewriting expects those nodes to be (newNodeTypes) and checks if
// the JWT that came in with the request is authorized to create those nodes. We can't check
// this before the mutation, because the nodes aren't linked into the graph yet.
//
// We group the nodes into their types, generate the authorization add rules for that type
// and then check that the authorized nodes for each type is equal to the nodes created
// for that type by performing an authorization query to Dgraph as part of the ongoing
// transaction (txn). If the authorization query returns fewer nodes than we created, some
// of the new nodes failed the auth rules.
func authorizeNewNodes(
ctx context.Context,
m schema.Mutation,
uids map[string]string,
newNodeTypes map[string]schema.Type,
queryExecutor DgraphExecutor,
txn *dgoapi.TxnContext) error {
customClaims, err := m.GetAuthMeta().ExtractCustomClaims(ctx)
if err != nil {
return schema.GQLWrapf(err, "authorization failed")
}
authVariables := customClaims.AuthVariables
newRw := &authRewriter{
authVariables: authVariables,
varGen: NewVariableGenerator(),
selector: addAuthSelector,
hasAuthRules: true,
}
// Collect all the newly created nodes in type groups
newByType := make(map[string][]uint64)
namesToType := make(map[string]schema.Type)
for nodeName, nodeTyp := range newNodeTypes {
if uidStr, created := uids[nodeName]; created {
uid, err := strconv.ParseUint(uidStr, 0, 64)
if err != nil {
return schema.GQLWrapf(err, "authorization failed")
}
if nodeTyp.ListType() != nil {
nodeTyp = nodeTyp.ListType()
}
namesToType[nodeTyp.Name()] = nodeTyp
newByType[nodeTyp.Name()] = append(newByType[nodeTyp.Name()], uid)
}
}
// sort to get a consistent query rewriting
var createdTypes []string
for typeName := range newByType {
createdTypes = append(createdTypes, typeName)
}
sort.Strings(createdTypes)
// Write auth queries for each set of node types
var needsAuth []string
authQrys := make(map[string][]*gql.GraphQuery)
for _, typeName := range createdTypes {
typ := namesToType[typeName]
varName := newRw.varGen.Next(typ, "", "", false)
newRw.varName = varName
newRw.parentVarName = typ.Name() + "Root"
authQueries, authFilter := newRw.rewriteAuthQueries(typ)
rn := newRw.selector(typ)
rbac := rn.EvaluateStatic(newRw.authVariables)
if rbac == schema.Negative {
return x.GqlErrorf("authorization failed")
}
if rbac == schema.Positive {
continue
}
if len(authQueries) == 0 {
continue
}
// Generate query blocks like this for each node type
//
// Todo(func: uid(Todo1)) @filter(uid(Todo2) AND uid(Todo3)) { uid }
// Todo1 as var(func: uid(...new uids of this type...) )
// Todo2 as var(func: uid(Todo1)) @cascade { ...auth query 1... }
// Todo3 as var(func: uid(Todo1)) @cascade { ...auth query 2... }
typQuery := &gql.GraphQuery{
Attr: typ.Name(),
Func: &gql.Function{
Name: "uid",
Args: []gql.Arg{{Value: varName}}},
Filter: authFilter,
Children: []*gql.GraphQuery{{Attr: "uid"}}}
nodes := newByType[typeName]
sort.Slice(nodes, func(i, j int) bool { return nodes[i] < nodes[j] })
varQry := &gql.GraphQuery{
Var: varName,
Attr: "var",
Func: &gql.Function{
Name: "uid",
UID: nodes,
},
}
needsAuth = append(needsAuth, typeName)
authQrys[typeName] = append([]*gql.GraphQuery{typQuery, varQry}, authQueries...)
}
if len(needsAuth) == 0 {
// no auth to apply
return nil
}
// create the query in order so we get a stable query
sort.Strings(needsAuth)
var qs []*gql.GraphQuery
for _, typeName := range needsAuth {
qs = append(qs, authQrys[typeName]...)
}
resp, errs := queryExecutor.Execute(ctx,
&dgoapi.Request{
Query: dgraph.AsString(qs),
StartTs: txn.GetStartTs(),
}, nil)
if errs != nil || len(resp.Json) == 0 {
return x.GqlErrorf("authorization request failed")
}
authResult := make(map[string]interface{})
if err := json.Unmarshal(resp.Json, &authResult); err != nil {
return x.GqlErrorf("authorization checking failed")
}
for _, typeName := range needsAuth {
check, ok := authResult[typeName]
if !ok || check == nil {
// We needed auth on this type, but it wasn't even in the response. That
// means Dgraph found no matching nodes and returned nothing for this field.
// So all the nodes failed auth.
// FIXME: what do we actually want to return to users when auth failed?
// Is this too much?
return x.GqlErrorf("authorization failed")
}
foundUIDs, ok := check.([]interface{})
if !ok {
return x.GqlErrorf("authorization failed")
}
if len(newByType[typeName]) != len(foundUIDs) {
// Some of the created nodes passed auth and some failed.
return x.GqlErrorf("authorization failed")
}
}
// By now either there were no types that needed auth, or all nodes passed the
// auth checks. So the mutation as a whole passed authorization.
return nil
}