-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
access_ee.go
726 lines (634 loc) · 19.3 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
// +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/y"
"github.com/dgraph-io/dgo/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 !worker.EnterpriseEnabled() {
return nil, errors.New("Enterprise features are disabled. You can enable them by " +
"supplying the appropriate license file to Dgraph Zero using a flag or 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)
}
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 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 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(Config.AccessJwtTtl).Unix(),
})
jwtString, err := token.SignedString(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
// Config.RefreshJwtTtl
func getRefreshJwt(userId string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"userid": userId,
"exp": time.Now().Add(Config.RefreshJwtTtl).Unix(),
})
jwtString, err := token.SignedString(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)
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(Config.HmacSecret) == 0 {
// the acl feature is not turned on
return
}
ticker := time.NewTicker(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)
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: has(dgraph.group.acl)) {
dgraph.xid
dgraph.group.acl
}
}
`
// ResetAcl clears the aclCachePtr and upserts the Groot account.
func ResetAcl() {
if len(Config.HmacSecret) == 0 {
// The acl feature is not turned on.
return
}
upsertGroot := func(ctx context.Context) error {
queryVars := map[string]string{
"$userid": x.GrootId,
"$password": "",
}
queryRequest := api.Request{
Query: queryUser,
Vars: queryVars,
}
queryResp, err := (&Server{}).doQuery(ctx, &queryRequest)
if err != nil {
return errors.Wrapf(err, "while querying user with id %s", x.GrootId)
}
startTs := queryResp.GetTxn().StartTs
rootUser, err := acl.UnmarshalUser(queryResp, "user")
if err != nil {
return errors.Wrapf(err, "while unmarshaling the root user")
}
if rootUser != nil {
glog.Infof("The groot account already exists, no need to insert again")
return nil
}
// Insert Groot.
createUserNQuads := acl.CreateUserNQuads(x.GrootId, "password")
mu := &api.Mutation{
StartTs: startTs,
CommitNow: true,
Set: createUserNQuads,
}
if _, err := (&Server{}).doMutate(context.Background(), mu, false); err != nil {
return err
}
glog.Infof("Successfully upserted the groot account")
return nil
}
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)
} else {
return
}
}
}
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])
}
// authorizeAlter parses the Schema in the operation and authorizes the operation
// using the aclCachePtr
func authorizeAlter(ctx context.Context, op *api.Operation) error {
if len(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
if len(op.DropAttr) > 0 {
preds = []string{op.DropAttr}
} else if op.DropOp == api.Operation_ATTR && len(op.DropValue) > 0 {
preds = []string{op.DropValue}
} else {
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 {
userId = userData[0]
groupIds = userData[1:]
if userId == x.GrootId {
return nil
}
} else if err == errNoJwt {
// treat the user as an anonymous guest who has not joined any group yet
// such a user can still get access to predicates that have no ACL rule defined, per the
// fail open approach
userId = "anonymous"
} else {
return status.Error(codes.Unauthenticated, err.Error())
}
// if we get here, we know the user is not Groot.
if isDropAll(op) || op.DropOp == api.Operation_DATA {
return errors.Errorf(
"only Groot is allowed to drop all data, but the current user is %s", userId)
}
for _, pred := range preds {
err := aclCachePtr.authorizePredicate(groupIds, pred, acl.Modify)
if err != nil {
logAccess(&accessEntry{
userId: userId,
groups: groupIds,
preds: preds,
operation: acl.Modify,
allowed: false,
})
return status.Error(codes.PermissionDenied,
fmt.Sprintf("unauthorized to alter the predicate: %v", err))
}
}
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{}{}
}
var preds []string
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
func authorizeMutation(ctx context.Context, gmu *gql.Mutation) error {
if len(Config.HmacSecret) == 0 {
// the user has not turned on the acl feature
return nil
}
preds := parsePredsFromMutation(gmu.Set)
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 {
userId = userData[0]
groupIds = userData[1:]
if userId == x.GrootId {
// groot is allowed to mutate anything except the permission of the acl predicates
if isAclPredMutation(gmu.Set) {
return errors.Errorf("the permission of ACL predicates can not be changed")
}
return nil
}
} else if err == errNoJwt {
// treat the user as an anonymous guest who has not joined any group yet
// such a user can still get access to predicates that have no ACL rule defined
} else {
return status.Error(codes.Unauthenticated, err.Error())
}
for _, pred := range preds {
err := aclCachePtr.authorizePredicate(groupIds, pred, acl.Write)
if err != nil {
logAccess(&accessEntry{
userId: userId,
groups: groupIds,
preds: preds,
operation: acl.Write,
allowed: false,
})
return status.Error(codes.PermissionDenied,
fmt.Sprintf("unauthorized to mutate the predicate: %v", err))
}
}
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 _, childPred := range parsePredsFromQuery(gq.Children) {
predsMap[childPred] = struct{}{}
}
}
var preds []string
for pred := range predsMap {
preds = append(preds, pred)
}
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) {
glog.V(1).Infof(log.String())
}
//authorizeQuery authorizes the query using the aclCachePtr
func authorizeQuery(ctx context.Context, req *api.Request) error {
if len(Config.HmacSecret) == 0 {
// the user has not turned on the acl feature
return nil
}
parsedReq, err := gql.Parse(gql.Request{
Str: req.Query,
Variables: req.Vars,
})
if err != nil {
return err
}
preds := parsePredsFromQuery(parsedReq.Query)
var userId string
var groupIds []string
doAuthorizeQuery := func() error {
userData, err := extractUserAndGroups(ctx)
if err == nil {
userId = userData[0]
groupIds = userData[1:]
if userId == x.GrootId {
// groot is allowed to query anything
return nil
}
} else if err == errNoJwt {
// treat the user as an anonymous guest who has not joined any group yet
// such a user can still get access to predicates that have no ACL rule defined
} else {
return status.Error(codes.Unauthenticated, err.Error())
}
for _, pred := range preds {
err := aclCachePtr.authorizePredicate(groupIds, pred, acl.Read)
if err != nil {
logAccess(&accessEntry{
userId: userId,
groups: groupIds,
preds: preds,
operation: acl.Read,
allowed: false,
})
return status.Error(codes.PermissionDenied,
fmt.Sprintf("unauthorized to query the predicate: %v", err))
}
}
return nil
}
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())
}
return err
}