-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathaccess_ee.go
1430 lines (1266 loc) · 39.4 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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// +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"
"strconv"
"strings"
"time"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/ristretto/z"
"github.com/dgraph-io/dgraph/query"
"github.com/pkg/errors"
bpb "github.com/dgraph-io/badger/v3/pb"
"github.com/dgraph-io/dgo/v210/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/status"
)
type predsAndvars struct {
preds []string
vars map[string]string
}
// Login handles login requests from clients.
func (s *Server) Login(ctx context.Context,
request *api.LoginRequest) (*api.Response, error) {
if !shouldAllowAcls(request.GetNamespace()) {
return nil, errors.New("operation is not allowed in cloud mode")
}
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 ipAddr, err := hasAdminAuth(ctx, "Login"); err != nil {
return nil, err
} else {
addr = ipAddr.String()
span.Annotate([]otrace.Attribute{
otrace.StringAttribute("client_ip", addr),
}, "client ip for login")
}
user, err := s.authenticateLogin(ctx, request)
if err != nil {
glog.Errorf("Authentication from address %s failed: %v", addr, err)
return nil, x.ErrorInvalidLogin
}
glog.Infof("%s logged in successfully", user.UserID)
resp := &api.Response{}
accessJwt, err := getAccessJwt(user.UserID, user.Groups, user.Namespace)
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, user.Namespace)
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.userId
ctx = x.AttachNamespace(ctx, userData.namespace)
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: invalid credentials")
}
user.Namespace = userData.namespace
glog.Infof("Authenticated user %s through refresh token", userId)
return user, nil
}
// In case of login, we can't extract namespace from JWT because we have not yet given JWT
// to the user, so the login request should contain the namespace, which is then set to ctx.
ctx = x.AttachNamespace(ctx, request.Namespace)
// 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: invalid credentials")
}
if !user.PasswordMatch {
return nil, x.ErrorInvalidLogin
}
user.Namespace = request.Namespace
return user, nil
}
type userData struct {
namespace uint64
userId string
groupIds []string
}
// 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) (*userData, error) {
claims, err := x.ParseJWT(jwtStr)
if err != nil {
return nil, err
}
// 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)
}
namespace, ok := claims["namespace"].(float64)
if !ok {
return nil, errors.Errorf("namespace in claims is not valid:%v", namespace)
}
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 &userData{namespace: uint64(namespace), userId: userId, groupIds: 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, namespace
// and expiration TTL specified by worker.Config.AccessJwtTtl
func getAccessJwt(userId string, groups []acl.Group, namespace uint64) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"userid": userId,
"groups": acl.GetGroupIDs(groups),
"namespace": namespace,
// set the jwt exp according to the ttl
"exp": time.Now().Add(worker.Config.AccessJwtTtl).Unix(),
})
jwtString, err := token.SignedString([]byte(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, namespace and expiration ttl
// specified by worker.Config.RefreshJwtTtl
func getRefreshJwt(userId string, namespace uint64) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"userid": userId,
"namespace": namespace,
"exp": time.Now().Add(worker.Config.RefreshJwtTtl).Unix(),
})
jwtString, err := token.SignedString([]byte(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,
}
req := &Request{
req: &api.Request{
Query: queryUser,
Vars: queryVars,
},
doAuth: NoAuthorize,
}
queryResp, err := (&Server{}).doQuery(ctx, req)
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
}
func refreshAclCache(ctx context.Context, ns, refreshTs uint64) error {
glog.V(2).Infof("Refreshing ACLs")
req := &Request{
req: &api.Request{
Query: queryAcls,
ReadOnly: true,
StartTs: refreshTs,
},
doAuth: NoAuthorize,
}
ctx = x.AttachNamespace(ctx, ns)
queryResp, err := (&Server{}).doQuery(ctx, req)
if err != nil {
return errors.Errorf("unable to retrieve acls: %v", err)
}
groups, err := acl.UnmarshalGroups(queryResp.GetJson(), "allAcls")
if err != nil {
return err
}
worker.AclCachePtr.Update(ns, groups)
glog.V(2).Infof("Updated the ACL cache for namespace: %#x", ns)
return nil
}
func RefreshACLs(ctx context.Context) {
for ns := range schema.State().Namespaces() {
if err := refreshAclCache(ctx, ns, 0); err != nil {
glog.Errorf("Error while retrieving acls for namespace %#x: %v", ns, err)
}
}
worker.AclCachePtr.Set()
}
// SubscribeForAclUpdates subscribes for ACL predicates and updates the acl cache.
func SubscribeForAclUpdates(closer *z.Closer) {
defer func() {
glog.Infoln("RefreshAcls closed")
closer.Done()
}()
if len(worker.Config.HmacSecret) == 0 {
// the acl feature is not turned on
return
}
var maxRefreshTs uint64
retrieveAcls := func(ns uint64, refreshTs uint64) error {
if refreshTs <= maxRefreshTs {
return nil
}
maxRefreshTs = refreshTs
ctx := x.AttachNamespace(closer.Ctx(), ns)
if !worker.AclCachePtr.Loaded() {
updaters := z.NewCloser(1)
RefreshACLs(updaters.Ctx())
}
return refreshAclCache(ctx, ns, refreshTs)
}
closer.AddRunning(1)
go worker.SubscribeForUpdates(aclPrefixes, x.IgnoreBytes, func(kvs *bpb.KVList) {
if kvs == nil || len(kvs.Kv) == 0 {
return
}
kv := x.KvWithMaxVersion(kvs, aclPrefixes)
pk, err := x.Parse(kv.GetKey())
if err != nil {
glog.Fatalf("Got a key from subscription which is not parsable: %s", err)
}
glog.V(3).Infof("Got ACL update via subscription for attr: %s", pk.Attr)
ns, _ := x.ParseNamespaceAttr(pk.Attr)
if err := retrieveAcls(ns, kv.GetVersion()); err != nil {
glog.Errorf("Error while retrieving acls: %v", err)
}
}, 1, closer)
<-closer.HasBeenClosed()
}
const queryAcls = `
{
allAcls(func: type(dgraph.type.Group)) {
dgraph.xid
dgraph.acl.rule {
dgraph.rule.predicate
dgraph.rule.permission
}
~dgraph.user.group{
dgraph.xid
}
}
}
`
var aclPrefixes = [][]byte{
x.PredicatePrefix(x.GalaxyAttr("dgraph.acl.permission")),
x.PredicatePrefix(x.GalaxyAttr("dgraph.acl.predicate")),
x.PredicatePrefix(x.GalaxyAttr("dgraph.acl.rule")),
x.PredicatePrefix(x.GalaxyAttr("dgraph.user.group")),
x.PredicatePrefix(x.GalaxyAttr("dgraph.type.Group")),
x.PredicatePrefix(x.GalaxyAttr("dgraph.xid")),
}
// upserts the Groot account.
func InitializeAcl(closer *z.Closer) {
defer func() {
glog.Infof("ResetAcl closed")
closer.Done()
}()
if len(worker.Config.HmacSecret) == 0 {
// The acl feature is not turned on.
return
}
upsertGuardianAndGroot(closer, x.GalaxyNamespace)
}
// Note: The handling of closer should be done by caller.
func upsertGuardianAndGroot(closer *z.Closer, ns uint64) {
if len(worker.Config.HmacSecret) == 0 {
// The acl feature is not turned on.
return
}
for closer.Ctx().Err() == nil {
ctx, cancel := context.WithTimeout(closer.Ctx(), time.Minute)
defer cancel()
ctx = x.AttachNamespace(ctx, ns)
if err := upsertGuardian(ctx); err != nil {
glog.Infof("Unable to upsert the guardian group. Error: %v", err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
for closer.Ctx().Err() == nil {
ctx, cancel := context.WithTimeout(closer.Ctx(), time.Minute)
defer cancel()
ctx = x.AttachNamespace(ctx, ns)
if err := upsertGroot(ctx, "password"); err != nil {
glog.Infof("Unable to upsert the groot account. Error: %v", err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
}
// upsertGuardian must be called after setting the namespace in the context.
func upsertGuardian(ctx context.Context) error {
query := fmt.Sprintf(`
{
guid as guardians(func: eq(dgraph.xid, "%s")){
uid
}
}
`, x.GuardiansId)
groupNQuads := acl.CreateGroupNQuads(x.GuardiansId)
req := &Request{
req: &api.Request{
CommitNow: true,
Query: query,
Mutations: []*api.Mutation{
{
Set: groupNQuads,
Cond: "@if(eq(len(guid), 0))",
},
},
},
doAuth: NoAuthorize,
}
resp, err := (&Server{}).doQuery(ctx, req)
// Structs to parse guardians group uid from query response
type groupNode struct {
Uid string `json:"uid"`
}
type groupQryResp struct {
GuardiansGroup []groupNode `json:"guardians"`
}
if err != nil {
return errors.Wrapf(err, "while upserting group with id %s", x.GuardiansId)
}
var groupResp groupQryResp
var guardiansUidStr string
if err := json.Unmarshal(resp.GetJson(), &groupResp); err != nil {
return errors.Wrap(err, "Couldn't unmarshal response from guardians group query")
}
if len(groupResp.GuardiansGroup) == 0 {
// no guardians group found
// Extract guardians group uid from mutation
newGroupUidMap := resp.GetUids()
guardiansUidStr = newGroupUidMap["newgroup"]
} else if len(groupResp.GuardiansGroup) == 1 {
// we found a guardians group
guardiansUidStr = groupResp.GuardiansGroup[0].Uid
} else {
return errors.Wrap(err, "Multiple guardians group found")
}
uid, err := strconv.ParseUint(guardiansUidStr, 0, 64)
if err != nil {
return errors.Wrapf(err, "Error while parsing Uid: %s of guardians Group", guardiansUidStr)
}
ns, err := x.ExtractNamespace(ctx)
if err != nil {
return errors.Wrapf(err, "While upserting group with id %s", x.GuardiansId)
}
x.GuardiansUid.Store(ns, uid)
glog.V(2).Infof("Successfully upserted the guardian of namespace: %d\n", ns)
return nil
}
// upsertGroot must be called after setting the namespace in the context.
func upsertGroot(ctx context.Context, passwd string) error {
// groot is the default user of guardians group.
query := fmt.Sprintf(`
{
grootid as grootUser(func: eq(dgraph.xid, "%s")){
uid
}
guid as var(func: eq(dgraph.xid, "%s"))
}
`, x.GrootId, x.GuardiansId)
userNQuads := acl.CreateUserNQuads(x.GrootId, passwd)
userNQuads = append(userNQuads, &api.NQuad{
Subject: "_:newuser",
Predicate: "dgraph.user.group",
ObjectId: "uid(guid)",
})
req := &Request{
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))",
},
},
},
doAuth: NoAuthorize,
}
resp, err := (&Server{}).doQuery(ctx, req)
if err != nil {
return errors.Wrapf(err, "while upserting user with id %s", x.GrootId)
}
// Structs to parse groot user uid from query response
type userNode struct {
Uid string `json:"uid"`
}
type userQryResp struct {
GrootUser []userNode `json:"grootUser"`
}
var grootUserUid string
var userResp userQryResp
if err := json.Unmarshal(resp.GetJson(), &userResp); err != nil {
return errors.Wrap(err, "Couldn't unmarshal response from groot user query")
}
if len(userResp.GrootUser) == 0 {
// no groot user found from query
// Extract uid of created groot user from mutation
newUserUidMap := resp.GetUids()
grootUserUid = newUserUidMap["newuser"]
} else if len(userResp.GrootUser) == 1 {
// we found a groot user
grootUserUid = userResp.GrootUser[0].Uid
} else {
return errors.Wrap(err, "Multiple groot users found")
}
uid, err := strconv.ParseUint(grootUserUid, 0, 64)
if err != nil {
return errors.Wrapf(err, "Error while parsing Uid: %s of groot user", grootUserUid)
}
ns, err := x.ExtractNamespace(ctx)
if err != nil {
return errors.Wrapf(err, "While upserting user with id %s", x.GrootId)
}
x.GrootUid.Store(ns, uid)
glog.V(2).Infof("Successfully upserted groot account for namespace %d\n", ns)
return nil
}
// extract the userId, groupIds from the accessJwt in the context
func extractUserAndGroups(ctx context.Context) (*userData, error) {
accessJwt, err := x.ExtractJwt(ctx)
if err != nil {
return nil, err
}
return validateToken(accessJwt)
}
type authPredResult struct {
allowed []string
blocked map[string]struct{}
}
func authorizePreds(ctx context.Context, userData *userData, preds []string,
aclOp *acl.Operation) *authPredResult {
if !worker.AclCachePtr.Loaded() {
RefreshACLs(ctx)
}
userId := userData.userId
groupIds := userData.groupIds
ns := userData.namespace
blockedPreds := make(map[string]struct{})
for _, pred := range preds {
nsPred := x.NamespaceAttr(ns, pred)
if err := worker.AclCachePtr.AuthorizePredicate(groupIds, nsPred, aclOp); err != nil {
logAccess(&accessEntry{
userId: userId,
groups: groupIds,
preds: preds,
operation: aclOp,
allowed: false,
})
blockedPreds[pred] = struct{}{}
}
}
worker.AclCachePtr.RLock()
// User can have multiple permission for same predicate, add predicate
allowedPreds := make([]string, len(worker.AclCachePtr.GetUserPredPerms(userId)))
// only if the acl.Op is covered in the set of permissions for the user
for predicate, perm := range worker.AclCachePtr.GetUserPredPerms(userId) {
if (perm & aclOp.Code) > 0 {
allowedPreds = append(allowedPreds, predicate)
}
}
worker.AclCachePtr.RUnlock()
return &authPredResult{allowed: allowedPreds, blocked: blockedPreds}
}
// authorizeAlter parses the Schema in the operation and authorizes the operation
// using the worker.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, x.ParseAttr(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.userId
groupIds = userData.groupIds
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)
}
result := authorizePreds(ctx, userData, preds, acl.Modify)
if len(result.blocked) > 0 {
var msg strings.Builder
for key := range result.blocked {
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 {
// _STAR_ALL is not a predicate in itself.
if nquad.Predicate != "_STAR_ALL" {
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 unmarshal 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 worker.AclCachePtr. It will return permission
// denied error if any one of the predicates in mutation(set or delete) is unauthorized.
// At this stage, namespace is not attached in the predicates.
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.userId
groupIds = userData.groupIds
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")
}
if !shouldAllowAcls(userData.namespace) {
for _, pred := range preds {
if x.IsAclPredicate(pred) {
return status.Errorf(codes.PermissionDenied,
"unauthorized to mutate acl predicates: %s\n", pred)
}
}
}
return nil
}
result := authorizePreds(ctx, userData, preds, acl.Write)
if len(result.blocked) > 0 {
var msg strings.Builder
for key := range result.blocked {
x.Check2(msg.WriteString(key))
x.Check2(msg.WriteString(" "))
}
return status.Errorf(codes.PermissionDenied,
"unauthorized to mutate following predicates: %s\n", msg.String())
}
gmu.AllowedPreds = result.allowed
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) predsAndvars {
predsMap := make(map[string]struct{})
varsMap := make(map[string]string)
for _, gq := range gqls {
if gq.Func != nil {
predsMap[gq.Func.Attr] = struct{}{}
}
if len(gq.Var) > 0 {
varsMap[gq.Var] = gq.Attr
}
if len(gq.Attr) > 0 && gq.Attr != "uid" && gq.Attr != "expand" && gq.Attr != "val" {
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{}{}
}
childPredandVars := parsePredsFromQuery(gq.Children)
for _, childPred := range childPredandVars.preds {
predsMap[childPred] = struct{}{}
}
for childVar := range childPredandVars.vars {
varsMap[childVar] = childPredandVars.vars[childVar]
}
}
preds := make([]string, 0, len(predsMap))
for pred := range predsMap {
if len(pred) > 0 {
if _, found := varsMap[pred]; !found {
preds = append(preds, pred)
}
}
}
pv := predsAndvars{preds: preds, vars: varsMap}
return pv
}
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())
}
}
// With shared instance enabled, we don't allow ACL operations from any of the non-galaxy namespace.
func shouldAllowAcls(ns uint64) bool {
return !x.Config.SharedInstance || ns == x.GalaxyNamespace
}
// authorizeQuery authorizes the query using the worker.AclCachePtr. It will silently drop all
// unauthorized predicates from query.
// At this stage, namespace is not attached in the predicates.
func authorizeQuery(ctx context.Context, parsedReq *gql.Result, graphql bool) error {
if len(worker.Config.HmacSecret) == 0 {
// the user has not turned on the acl feature
return nil
}
var userId string
var groupIds []string
var namespace uint64
predsAndvars := parsePredsFromQuery(parsedReq.Query)
preds := predsAndvars.preds
varsToPredMap := predsAndvars.vars
// Need this to efficiently identify blocked variables from the
// list of blocked predicates
predToVarsMap := make(map[string]string)
for k, v := range varsToPredMap {
predToVarsMap[v] = k
}
doAuthorizeQuery := func() (map[string]struct{}, []string, error) {
userData, err := extractUserAndGroups(ctx)
if err != nil {
return nil, nil, status.Error(codes.Unauthenticated, err.Error())
}
userId = userData.userId
groupIds = userData.groupIds
namespace = userData.namespace
if x.IsGuardian(groupIds) {
if shouldAllowAcls(userData.namespace) {
// Members of guardian groups are allowed to query anything.
return nil, nil, nil
}
blocked := make(map[string]struct{})
for _, pred := range preds {
if x.IsAclPredicate(pred) {
blocked[pred] = struct{}{}
}
}
return blocked, nil, nil
}
result := authorizePreds(ctx, userData, preds, acl.Read)