-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
access_ee.go
982 lines (864 loc) · 26 KB
/
access_ee.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
// +build !oss
/*
* Copyright 2018 Dgraph Labs, Inc. All rights reserved.
*
* Licensed under the Dgraph Community License (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* https://github.com/dgraph-io/dgraph/blob/master/licenses/DCL.txt
*/
package edgraph
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"github.com/dgraph-io/badger/v2/y"
"github.com/dgraph-io/dgo/v2/protos/api"
"github.com/dgraph-io/dgraph/ee/acl"
"github.com/dgraph-io/dgraph/gql"
"github.com/dgraph-io/dgraph/schema"
"github.com/dgraph-io/dgraph/worker"
"github.com/dgraph-io/dgraph/x"
jwt "github.com/dgrijalva/jwt-go"
"github.com/golang/glog"
otrace "go.opencensus.io/trace"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
// Login handles login requests from clients.
func (s *Server) Login(ctx context.Context,
request *api.LoginRequest) (*api.Response, error) {
if err := x.HealthCheck(); err != nil {
return nil, err
}
if !worker.EnterpriseEnabled() {
return nil, errors.New("Enterprise features are disabled. You can enable them by " +
"supplying the appropriate license file to Dgraph Zero using the HTTP endpoint.")
}
ctx, span := otrace.StartSpan(ctx, "server.Login")
defer span.End()
// record the client ip for this login request
var addr string
if peerInfo, ok := peer.FromContext(ctx); ok {
addr = peerInfo.Addr.String()
glog.Infof("Login request from: %s", addr)
span.Annotate([]otrace.Attribute{
otrace.StringAttribute("client_ip", addr),
}, "client ip for login")
}
user, err := s.authenticateLogin(ctx, request)
if err != nil {
errMsg := fmt.Sprintf("Authentication from address %s failed: %v", addr, err)
glog.Errorf(errMsg)
return nil, errors.Errorf(errMsg)
}
glog.Infof("%s logged in successfully", user.UserID)
resp := &api.Response{}
accessJwt, err := getAccessJwt(user.UserID, user.Groups)
if err != nil {
errMsg := fmt.Sprintf("unable to get access jwt (userid=%s,addr=%s):%v",
user.UserID, addr, err)
glog.Errorf(errMsg)
return nil, errors.Errorf(errMsg)
}
refreshJwt, err := getRefreshJwt(user.UserID)
if err != nil {
errMsg := fmt.Sprintf("unable to get refresh jwt (userid=%s,addr=%s):%v",
user.UserID, addr, err)
glog.Errorf(errMsg)
return nil, errors.Errorf(errMsg)
}
loginJwt := api.Jwt{
AccessJwt: accessJwt,
RefreshJwt: refreshJwt,
}
jwtBytes, err := loginJwt.Marshal()
if err != nil {
errMsg := fmt.Sprintf("unable to marshal jwt (userid=%s,addr=%s):%v",
user.UserID, addr, err)
glog.Errorf(errMsg)
return nil, errors.Errorf(errMsg)
}
resp.Json = jwtBytes
return resp, nil
}
// authenticateLogin authenticates the login request using either the refresh token if present, or
// the <userId, password> pair. If authentication passes, it queries the user's uid and associated
// groups from DB and returns the user object
func (s *Server) authenticateLogin(ctx context.Context, request *api.LoginRequest) (*acl.User,
error) {
if err := validateLoginRequest(request); err != nil {
return nil, errors.Wrapf(err, "invalid login request")
}
var user *acl.User
if len(request.RefreshToken) > 0 {
userData, err := validateToken(request.RefreshToken)
if err != nil {
return nil, errors.Wrapf(err, "unable to authenticate the refresh token %v",
request.RefreshToken)
}
userId := userData[0]
user, err = authorizeUser(ctx, userId, "")
if err != nil {
return nil, errors.Wrapf(err, "while querying user with id %v", userId)
}
if user == nil {
return nil, errors.Errorf("unable to authenticate through refresh token: "+
"user not found for id %v", userId)
}
glog.Infof("Authenticated user %s through refresh token", userId)
return user, nil
}
// authorize the user using password
var err error
user, err = authorizeUser(ctx, request.Userid, request.Password)
if err != nil {
return nil, errors.Wrapf(err, "while querying user with id %v",
request.Userid)
}
if user == nil {
return nil, errors.Errorf("unable to authenticate through password: "+
"user not found for id %v", request.Userid)
}
if !user.PasswordMatch {
return nil, errors.Errorf("password mismatch for user: %v", request.Userid)
}
return user, nil
}
// validateToken verifies the signature and expiration of the jwt, and if validation passes,
// returns a slice of strings, where the first element is the extracted userId
// and the rest are groupIds encoded in the jwt.
func validateToken(jwtStr string) ([]string, error) {
token, err := jwt.Parse(jwtStr, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return worker.Config.HmacSecret, nil
})
if err != nil {
return nil, errors.Errorf("unable to parse jwt token:%v", err)
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return nil, errors.Errorf("claims in jwt token is not map claims")
}
// by default, the MapClaims.Valid will return true if the exp field is not set
// here we enforce the checking to make sure that the refresh token has not expired
now := time.Now().Unix()
if !claims.VerifyExpiresAt(now, true) {
return nil, errors.Errorf("Token is expired") // the same error msg that's used inside jwt-go
}
userId, ok := claims["userid"].(string)
if !ok {
return nil, errors.Errorf("userid in claims is not a string:%v", userId)
}
groups, ok := claims["groups"].([]interface{})
var groupIds []string
if ok {
groupIds = make([]string, 0, len(groups))
for _, group := range groups {
groupId, ok := group.(string)
if !ok {
// This shouldn't happen. So, no need to make the client try to refresh the tokens.
return nil, errors.Errorf("unable to convert group to string:%v", group)
}
groupIds = append(groupIds, groupId)
}
}
return append([]string{userId}, groupIds...), nil
}
// validateLoginRequest validates that the login request has either the refresh token or the
// <user id, password> pair
func validateLoginRequest(request *api.LoginRequest) error {
if request == nil {
return errors.Errorf("the request should not be nil")
}
// we will use the refresh token for authentication if it's set
if len(request.RefreshToken) > 0 {
return nil
}
// otherwise make sure both userid and password are set
if len(request.Userid) == 0 {
return errors.Errorf("the userid should not be empty")
}
if len(request.Password) == 0 {
return errors.Errorf("the password should not be empty")
}
return nil
}
// getAccessJwt constructs an access jwt with the given user id, groupIds,
// and expiration TTL specified by worker.Config.AccessJwtTtl
func getAccessJwt(userId string, groups []acl.Group) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"userid": userId,
"groups": acl.GetGroupIDs(groups),
// set the jwt exp according to the ttl
"exp": time.Now().Add(worker.Config.AccessJwtTtl).Unix(),
})
jwtString, err := token.SignedString(worker.Config.HmacSecret)
if err != nil {
return "", errors.Errorf("unable to encode jwt to string: %v", err)
}
return jwtString, nil
}
// getRefreshJwt constructs a refresh jwt with the given user id, and expiration ttl specified by
// worker.Config.RefreshJwtTtl
func getRefreshJwt(userId string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"userid": userId,
"exp": time.Now().Add(worker.Config.RefreshJwtTtl).Unix(),
})
jwtString, err := token.SignedString(worker.Config.HmacSecret)
if err != nil {
return "", errors.Errorf("unable to encode jwt to string: %v", err)
}
return jwtString, nil
}
const queryUser = `
query search($userid: string, $password: string){
user(func: eq(dgraph.xid, $userid)) {
uid
dgraph.xid
password_match: checkpwd(dgraph.password, $password)
dgraph.user.group {
uid
dgraph.xid
}
}
}`
// authorizeUser queries the user with the given user id, and returns the associated uid,
// acl groups, and whether the password stored in DB matches the supplied password
func authorizeUser(ctx context.Context, userid string, password string) (
*acl.User, error) {
queryVars := map[string]string{
"$userid": userid,
"$password": password,
}
queryRequest := api.Request{
Query: queryUser,
Vars: queryVars,
}
queryResp, err := (&Server{}).doQuery(ctx, &queryRequest, NoAuthorize)
if err != nil {
glog.Errorf("Error while query user with id %s: %v", userid, err)
return nil, err
}
user, err := acl.UnmarshalUser(queryResp, "user")
if err != nil {
return nil, err
}
return user, nil
}
// RefreshAcls queries for the ACL triples and refreshes the ACLs accordingly.
func RefreshAcls(closer *y.Closer) {
defer closer.Done()
if len(worker.Config.HmacSecret) == 0 {
// the acl feature is not turned on
return
}
ticker := time.NewTicker(worker.Config.AclRefreshInterval)
defer ticker.Stop()
// retrieve the full data set of ACLs from the corresponding alpha server, and update the
// aclCachePtr
retrieveAcls := func() error {
glog.V(3).Infof("Refreshing ACLs")
queryRequest := api.Request{
Query: queryAcls,
ReadOnly: true,
}
ctx := context.Background()
var err error
queryResp, err := (&Server{}).doQuery(ctx, &queryRequest, NoAuthorize)
if err != nil {
return errors.Errorf("unable to retrieve acls: %v", err)
}
groups, err := acl.UnmarshalGroups(queryResp.GetJson(), "allAcls")
if err != nil {
return err
}
aclCachePtr.update(groups)
glog.V(3).Infof("Updated the ACL cache")
return nil
}
for {
select {
case <-closer.HasBeenClosed():
return
case <-ticker.C:
if err := retrieveAcls(); err != nil {
glog.Errorf("Error while retrieving acls:%v", err)
}
}
}
}
const queryAcls = `
{
allAcls(func: type(Group)) {
dgraph.xid
dgraph.acl.rule {
dgraph.rule.predicate
dgraph.rule.permission
}
}
}
`
// ResetAcl clears the aclCachePtr and upserts the Groot account.
func ResetAcl() {
if len(worker.Config.HmacSecret) == 0 {
// The acl feature is not turned on.
return
}
// guardians is the group of users who have complete access over all predicates.
upsertGuardians := func(ctx context.Context) error {
query := fmt.Sprintf(`
{
guid as var(func: eq(dgraph.xid, "%s"))
}
`, x.GuardiansId)
groupNQuads := acl.CreateGroupNQuads(x.GuardiansId)
req := &api.Request{
CommitNow: true,
Query: query,
Mutations: []*api.Mutation{
{
Set: groupNQuads,
Cond: "@if(eq(len(guid), 0))",
},
},
}
if _, err := (&Server{}).doQuery(ctx, req, NoAuthorize); err != nil {
return errors.Wrapf(err, "while upserting group with id %s", x.GuardiansId)
}
glog.Infof("Successfully upserted the guardian group")
return nil
}
// groot is the default user of guardians group.
upsertGroot := func(ctx context.Context) error {
query := fmt.Sprintf(`
{
grootid as var(func: eq(dgraph.xid, "%s"))
guid as var(func: eq(dgraph.xid, "%s"))
}
`, x.GrootId, x.GuardiansId)
userNQuads := acl.CreateUserNQuads(x.GrootId, "password")
userNQuads = append(userNQuads, &api.NQuad{
Subject: "_:newuser",
Predicate: "dgraph.user.group",
ObjectId: "uid(guid)",
})
req := &api.Request{
CommitNow: true,
Query: query,
Mutations: []*api.Mutation{
{
Set: userNQuads,
// Assuming that if groot exists, it is in guardian group
Cond: "@if(eq(len(grootid), 0) and gt(len(guid), 0))",
},
},
}
if _, err := (&Server{}).doQuery(ctx, req, NoAuthorize); err != nil {
return errors.Wrapf(err, "while upserting user with id %s", x.GrootId)
}
glog.Infof("Successfully upserted groot account")
return nil
}
for {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
if err := upsertGuardians(ctx); err != nil {
glog.Infof("Unable to upsert the guardian group. Error: %v", err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
for {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
if err := upsertGroot(ctx); err != nil {
glog.Infof("Unable to upsert the groot account. Error: %v", err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
}
var errNoJwt = errors.New("no accessJwt available")
// extract the userId, groupIds from the accessJwt in the context
func extractUserAndGroups(ctx context.Context) ([]string, error) {
// extract the jwt and unmarshal the jwt to get the list of groups
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errNoJwt
}
accessJwt := md.Get("accessJwt")
if len(accessJwt) == 0 {
return nil, errNoJwt
}
return validateToken(accessJwt[0])
}
func authorizePreds(userId string, groupIds, preds []string,
aclOp *acl.Operation) map[string]struct{} {
blockedPreds := make(map[string]struct{})
for _, pred := range preds {
if err := aclCachePtr.authorizePredicate(groupIds, pred, aclOp); err != nil {
logAccess(&accessEntry{
userId: userId,
groups: groupIds,
preds: preds,
operation: aclOp,
allowed: false,
})
blockedPreds[pred] = struct{}{}
}
}
return blockedPreds
}
// authorizeAlter parses the Schema in the operation and authorizes the operation
// using the aclCachePtr. It will return error if any one of the predicates specified in alter
// are not authorized.
func authorizeAlter(ctx context.Context, op *api.Operation) error {
if len(worker.Config.HmacSecret) == 0 {
// the user has not turned on the acl feature
return nil
}
// extract the list of predicates from the operation object
var preds []string
switch {
case len(op.DropAttr) > 0:
preds = []string{op.DropAttr}
case op.DropOp == api.Operation_ATTR && len(op.DropValue) > 0:
preds = []string{op.DropValue}
default:
update, err := schema.Parse(op.Schema)
if err != nil {
return err
}
for _, u := range update.Preds {
preds = append(preds, u.Predicate)
}
}
var userId string
var groupIds []string
// doAuthorizeAlter checks if alter of all the predicates are allowed
// as a byproduct, it also sets the userId, groups variables
doAuthorizeAlter := func() error {
userData, err := extractUserAndGroups(ctx)
if err != nil {
// We don't follow fail open approach anymore.
return status.Error(codes.Unauthenticated, err.Error())
}
userId = userData[0]
groupIds = userData[1:]
if x.IsGuardian(groupIds) {
// Members of guardian group are allowed to alter anything.
return nil
}
// if we get here, we know the user is not a guardian.
if isDropAll(op) || op.DropOp == api.Operation_DATA {
return errors.Errorf(
"only guardians are allowed to drop all data, but the current user is %s", userId)
}
blockedPreds := authorizePreds(userId, groupIds, preds, acl.Modify)
if len(blockedPreds) > 0 {
var msg strings.Builder
for key := range blockedPreds {
x.Check2(msg.WriteString(key))
x.Check2(msg.WriteString(" "))
}
return status.Errorf(codes.PermissionDenied,
"unauthorized to alter following predicates: %s\n", msg.String())
}
return nil
}
err := doAuthorizeAlter()
span := otrace.FromContext(ctx)
if span != nil {
span.Annotatef(nil, (&accessEntry{
userId: userId,
groups: groupIds,
preds: preds,
operation: acl.Modify,
allowed: err == nil,
}).String())
}
return err
}
// parsePredsFromMutation returns a union set of all the predicate names in the input nquads
func parsePredsFromMutation(nquads []*api.NQuad) []string {
// use a map to dedup predicates
predsMap := make(map[string]struct{})
for _, nquad := range nquads {
predsMap[nquad.Predicate] = struct{}{}
}
preds := make([]string, 0, len(predsMap))
for pred := range predsMap {
preds = append(preds, pred)
}
return preds
}
func isAclPredMutation(nquads []*api.NQuad) bool {
for _, nquad := range nquads {
if nquad.Predicate == "dgraph.group.acl" && nquad.ObjectValue != nil {
// this mutation is trying to change the permission of some predicate
// check if the predicate list contains an ACL predicate
if _, ok := nquad.ObjectValue.Val.(*api.Value_BytesVal); ok {
aclBytes := nquad.ObjectValue.Val.(*api.Value_BytesVal)
var aclsToChange []acl.Acl
err := json.Unmarshal(aclBytes.BytesVal, &aclsToChange)
if err != nil {
glog.Errorf(fmt.Sprintf("Unable to unmalshal bytes under the dgraph.group.acl "+
"predicate: %v", err))
continue
}
for _, aclToChange := range aclsToChange {
if x.IsAclPredicate(aclToChange.Predicate) {
return true
}
}
}
}
}
return false
}
// authorizeMutation authorizes the mutation using the aclCachePtr. It will return permission
// denied error if any one of the predicates in mutation(set or delete) is unauthorized.
func authorizeMutation(ctx context.Context, gmu *gql.Mutation) error {
if len(worker.Config.HmacSecret) == 0 {
// the user has not turned on the acl feature
return nil
}
preds := parsePredsFromMutation(gmu.Set)
// Del predicates weren't included before.
// A bug probably since f115de2eb6a40d882a86c64da68bf5c2a33ef69a
preds = append(preds, parsePredsFromMutation(gmu.Del)...)
var userId string
var groupIds []string
// doAuthorizeMutation checks if modification of all the predicates are allowed
// as a byproduct, it also sets the userId and groups
doAuthorizeMutation := func() error {
userData, err := extractUserAndGroups(ctx)
if err != nil {
// We don't follow fail open approach anymore.
return status.Error(codes.Unauthenticated, err.Error())
}
userId = userData[0]
groupIds = userData[1:]
if x.IsGuardian(groupIds) {
// Members of guardians group are allowed to mutate anything
// (including delete) except the permission of the acl predicates.
switch {
case isAclPredMutation(gmu.Set):
return errors.Errorf("the permission of ACL predicates can not be changed")
case isAclPredMutation(gmu.Del):
return errors.Errorf("ACL predicates can't be deleted")
}
return nil
}
blockedPreds := authorizePreds(userId, groupIds, preds, acl.Write)
if len(blockedPreds) > 0 {
var msg strings.Builder
for key := range blockedPreds {
x.Check2(msg.WriteString(key))
x.Check2(msg.WriteString(" "))
}
return status.Errorf(codes.PermissionDenied,
"unauthorized to mutate following predicates: %s\n", msg.String())
}
return nil
}
err := doAuthorizeMutation()
span := otrace.FromContext(ctx)
if span != nil {
span.Annotatef(nil, (&accessEntry{
userId: userId,
groups: groupIds,
preds: preds,
operation: acl.Write,
allowed: err == nil,
}).String())
}
return err
}
func parsePredsFromQuery(gqls []*gql.GraphQuery) []string {
predsMap := make(map[string]struct{})
for _, gq := range gqls {
if gq.Func != nil {
predsMap[gq.Func.Attr] = struct{}{}
}
if len(gq.Attr) > 0 {
predsMap[gq.Attr] = struct{}{}
}
for _, ord := range gq.Order {
predsMap[ord.Attr] = struct{}{}
}
for _, gbAttr := range gq.GroupbyAttrs {
predsMap[gbAttr.Attr] = struct{}{}
}
for _, pred := range parsePredsFromFilter(gq.Filter) {
predsMap[pred] = struct{}{}
}
for _, childPred := range parsePredsFromQuery(gq.Children) {
predsMap[childPred] = struct{}{}
}
}
preds := make([]string, 0, len(predsMap))
for pred := range predsMap {
preds = append(preds, pred)
}
return preds
}
func parsePredsFromFilter(f *gql.FilterTree) []string {
var preds []string
if f == nil {
return preds
}
if f.Func != nil && len(f.Func.Attr) > 0 {
preds = append(preds, f.Func.Attr)
}
for _, ch := range f.Child {
preds = append(preds, parsePredsFromFilter(ch)...)
}
return preds
}
type accessEntry struct {
userId string
groups []string
preds []string
operation *acl.Operation
allowed bool
}
func (log *accessEntry) String() string {
return fmt.Sprintf("ACL-LOG Authorizing user %q with groups %q on predicates %q "+
"for %q, allowed:%v", log.userId, strings.Join(log.groups, ","),
strings.Join(log.preds, ","), log.operation.Name, log.allowed)
}
func logAccess(log *accessEntry) {
if glog.V(1) {
glog.Info(log.String())
}
}
//authorizeQuery authorizes the query using the aclCachePtr. It will silently drop all
// unauthorized predicates from query.
func authorizeQuery(ctx context.Context, parsedReq *gql.Result) error {
if len(worker.Config.HmacSecret) == 0 {
// the user has not turned on the acl feature
return nil
}
var userId string
var groupIds []string
preds := parsePredsFromQuery(parsedReq.Query)
doAuthorizeQuery := func() (map[string]struct{}, error) {
userData, err := extractUserAndGroups(ctx)
if err != nil {
return nil, status.Error(codes.Unauthenticated, err.Error())
}
userId = userData[0]
groupIds = userData[1:]
if x.IsGuardian(groupIds) {
// Members of guardian groups are allowed to query anything.
return nil, nil
}
return authorizePreds(userId, groupIds, preds, acl.Read), nil
}
blockedPreds, err := doAuthorizeQuery()
if span := otrace.FromContext(ctx); span != nil {
span.Annotatef(nil, (&accessEntry{
userId: userId,
groups: groupIds,
preds: preds,
operation: acl.Read,
allowed: err == nil,
}).String())
}
if err != nil {
return err
}
if len(blockedPreds) != 0 {
for _, gq := range parsedReq.Query {
addUserFilterToQuery(gq, userId, groupIds)
}
for _, pred := range x.AllACLPredicates() {
delete(blockedPreds, pred)
}
parsedReq.Query = removePredsFromQuery(parsedReq.Query, blockedPreds)
}
return nil
}
// authorizeGroot authorizes the operation for Groot users.
func authorizeGroot(ctx context.Context) error {
if len(worker.Config.HmacSecret) == 0 {
// the user has not turned on the acl feature
return nil
}
var userID string
// doAuthorizeState checks if the user is authorized to perform this API request
doAuthorizeGroot := func() error {
userData, err := extractUserAndGroups(ctx)
switch {
case err == errNoJwt:
return status.Error(codes.PermissionDenied, err.Error())
case err != nil:
return status.Error(codes.Unauthenticated, err.Error())
default:
userID = userData[0]
if userID == x.GrootId {
return nil
}
// Deny non groot users.
return status.Error(codes.PermissionDenied, fmt.Sprintf("User is '%v'. "+
"Only User '%v' is authorized.", userID, x.GrootId))
}
}
return doAuthorizeGroot()
}
// addUserFilterToQuery applies makes sure that a user can access only its own
// acl info by applying filter of userid and groupid to acl predicates
func addUserFilterToQuery(gq *gql.GraphQuery, userId string, groupIds []string) {
addNewFilter := func(newFilter, filter *gql.FilterTree) *gql.FilterTree {
if filter == nil {
return newFilter
}
parentFilter := &gql.FilterTree{
Op: "AND",
Child: []*gql.FilterTree{filter, newFilter},
}
return parentFilter
}
if gq.Func != nil && gq.Func.Name == "type" {
for _, arg := range gq.Func.Args {
// The case where value of some varialble v (say) is "Group" and a
// query comes like `eq(dgraph.type, val(v))`, will be ingored here.
if arg.Value == "User" {
newFilter := &gql.FilterTree{
Func: &gql.Function{
Attr: "dgraph.xid",
Name: "eq",
Args: []gql.Arg{
gql.Arg{Value: userId},
},
},
}
gq.Filter = addNewFilter(newFilter, gq.Filter)
} else if arg.Value == "Group" {
child := &gql.FilterTree{
Func: &gql.Function{
Attr: "dgraph.xid",
Name: "eq",
},
}
for _, gid := range groupIds {
child.Func.Args = append(child.Func.Args,
gql.Arg{Value: gid})
}
newFilter := &gql.FilterTree{
Op: "OR",
Child: []*gql.FilterTree{child},
}
gq.Filter = addNewFilter(newFilter, gq.Filter)
}
}
}
switch gq.Attr {
case "dgraph.user.group":
child := &gql.FilterTree{
Func: &gql.Function{
Attr: "dgraph.xid",
Name: "eq",
},
}
for _, gid := range groupIds {
child.Func.Args = append(child.Func.Args, gql.Arg{Value: gid})
}
newFilter := &gql.FilterTree{
Op: "OR",
Child: []*gql.FilterTree{child},
}
gq.Filter = addNewFilter(newFilter, gq.Filter)
case "~dgraph.user.group":
newFilter := &gql.FilterTree{
Func: &gql.Function{
Attr: "dgraph.xid",
Name: "eq",
Args: []gql.Arg{
gql.Arg{Value: userId},
},
},
}
gq.Filter = addNewFilter(newFilter, gq.Filter)
}
for _, ch := range gq.Children {
addUserFilterToQuery(ch, userId, groupIds)
}
}
// removePredsFromQuery removes all the predicates in blockedPreds
// from all the queries in gqs.
func removePredsFromQuery(gqs []*gql.GraphQuery,
blockedPreds map[string]struct{}) []*gql.GraphQuery {
filteredGQs := gqs[:0]
for _, gq := range gqs {
if gq.Func != nil && len(gq.Func.Attr) > 0 {
if _, ok := blockedPreds[gq.Func.Attr]; ok {
continue
}
}
if len(gq.Attr) > 0 {
if _, ok := blockedPreds[gq.Attr]; ok {
continue
}
}
order := gq.Order[:0]
for _, ord := range gq.Order {
if _, ok := blockedPreds[ord.Attr]; ok {
continue
}
order = append(order, ord)
}
gq.Order = order
gq.Filter = removeFilters(gq.Filter, blockedPreds)
gq.GroupbyAttrs = removeGroupBy(gq.GroupbyAttrs, blockedPreds)
gq.Children = removePredsFromQuery(gq.Children, blockedPreds)
filteredGQs = append(filteredGQs, gq)
}
return filteredGQs
}
func removeFilters(f *gql.FilterTree, blockedPreds map[string]struct{}) *gql.FilterTree {
if f == nil {
return nil
}
if f.Func != nil && len(f.Func.Attr) > 0 {
if _, ok := blockedPreds[f.Func.Attr]; ok {
return nil
}
}
filteredChildren := f.Child[:0]
for _, ch := range f.Child {
child := removeFilters(ch, blockedPreds)
if child != nil {
filteredChildren = append(filteredChildren, child)
}
}
if len(filteredChildren) != len(f.Child) && (f.Op == "AND" || f.Op == "NOT") {
return nil
}
f.Child = filteredChildren
return f
}
func removeGroupBy(gbAttrs []gql.GroupByAttr,
blockedPreds map[string]struct{}) []gql.GroupByAttr {
filteredGbAttrs := gbAttrs[:0]
for _, gbAttr := range gbAttrs {
if _, ok := blockedPreds[gbAttr.Attr]; ok {
continue
}
filteredGbAttrs = append(filteredGbAttrs, gbAttr)
}
return filteredGbAttrs
}