-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
acl_test.go
2285 lines (2005 loc) · 54.5 KB
/
acl_test.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. and Contributors
*
* 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 acl
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"testing"
"time"
"github.com/dgraph-io/dgo/v200"
"github.com/dgraph-io/dgo/v200/protos/api"
"github.com/dgraph-io/dgraph/testutil"
"github.com/dgraph-io/dgraph/x"
"github.com/golang/glog"
"github.com/stretchr/testify/require"
)
var (
userid = "alice"
userpassword = "simplepassword"
dgraphEndpoint = testutil.SockAddr
)
func createUser(t *testing.T, accessToken, username, password string) *testutil.GraphQLResponse {
addUser := `
mutation addUser($name: String!, $pass: String!) {
addUser(input: [{name: $name, password: $pass}]) {
user {
name
}
}
}`
params := testutil.GraphQLParams{
Query: addUser,
Variables: map[string]interface{}{
"name": username,
"pass": password,
},
}
resp := makeRequest(t, accessToken, params)
return resp
}
func getCurrentUser(t *testing.T, accessToken string) *testutil.GraphQLResponse {
query := `
query {
getCurrentUser {
name
}
}`
resp := makeRequest(t, accessToken, testutil.GraphQLParams{Query: query})
return resp
}
func checkUserCount(t *testing.T, resp []byte, expected int) {
type Response struct {
AddUser struct {
User []struct {
Name string
}
}
}
var r Response
err := json.Unmarshal(resp, &r)
require.NoError(t, err)
require.Equal(t, expected, len(r.AddUser.User))
}
func deleteUser(t *testing.T, accessToken, username string) {
// TODO - Verify that only one uid got deleted once numUids are returned as part of the payload.
delUser := `
mutation deleteUser($name: String!) {
deleteUser(filter: {name: {eq: $name}}) {
msg
}
}`
params := testutil.GraphQLParams{
Query: delUser,
Variables: map[string]interface{}{
"name": username,
},
}
resp := makeRequest(t, accessToken, params)
resp.RequireNoGraphQLErrors(t)
require.JSONEq(t, `{"deleteUser":{"msg":"Deleted"}}`, string(resp.Data))
}
func deleteGroup(t *testing.T, accessToken, name string) {
// TODO - Verify that only one uid got deleted once numUids are returned as part of the payload.
delGroup := `
mutation deleteUser($name: String!) {
deleteGroup(filter: {name: {eq: $name}}) {
msg
}
}`
params := testutil.GraphQLParams{
Query: delGroup,
Variables: map[string]interface{}{
"name": name,
},
}
resp := makeRequest(t, accessToken, params)
resp.RequireNoGraphQLErrors(t)
require.JSONEq(t, `{"deleteGroup":{"msg":"Deleted"}}`, string(resp.Data))
}
func TestInvalidGetUser(t *testing.T) {
currentUser := getCurrentUser(t, "invalid token")
require.Equal(t, `{"getCurrentUser":null}`, string(currentUser.Data))
require.Equal(t, x.GqlErrorList{{
Message: "couldn't rewrite query getCurrentUser because unable to parse jwt token: token" +
" contains an invalid number of segments",
}}, currentUser.Errors)
}
func TestPasswordReturn(t *testing.T) {
accessJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: "groot",
Passwd: "password",
})
require.NoError(t, err, "login failed")
query := `
query {
getCurrentUser {
name
password
}
}`
resp := makeRequest(t, accessJwt, testutil.GraphQLParams{Query: query})
require.Equal(t, resp.Errors, x.GqlErrorList{{
Message: `Cannot query field "password" on type "User".`,
Locations: []x.Location{{
Line: 5,
Column: 4,
}},
}})
}
func TestGetCurrentUser(t *testing.T) {
accessJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: "groot",
Passwd: "password",
})
require.NoError(t, err, "login failed")
currentUser := getCurrentUser(t, accessJwt)
currentUser.RequireNoGraphQLErrors(t)
require.Equal(t, string(currentUser.Data), `{"getCurrentUser":{"name":"groot"}}`)
// clean up the user to allow repeated running of this test
userid := "hamilton"
deleteUser(t, accessJwt, userid)
glog.Infof("cleaned up db user state")
resp := createUser(t, accessJwt, userid, userpassword)
resp.RequireNoGraphQLErrors(t)
checkUserCount(t, resp.Data, 1)
newJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: userid,
Passwd: userpassword,
})
require.NoError(t, err, "login failed")
currentUser = getCurrentUser(t, newJwt)
currentUser.RequireNoGraphQLErrors(t)
require.Equal(t, string(currentUser.Data), `{"getCurrentUser":{"name":"hamilton"}}`)
}
func TestCreateAndDeleteUsers(t *testing.T) {
accessJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: "groot",
Passwd: "password",
})
require.NoError(t, err, "login failed")
// clean up the user to allow repeated running of this test
deleteUser(t, accessJwt, userid)
glog.Infof("cleaned up db user state")
resp := createUser(t, accessJwt, userid, userpassword)
resp.RequireNoGraphQLErrors(t)
checkUserCount(t, resp.Data, 1)
// adding the user again should fail
resp = createUser(t, accessJwt, userid, userpassword)
require.Equal(t, x.GqlErrorList{{
Message: "couldn't rewrite query for mutation addUser because id alice already exists" +
" for type User",
}}, resp.Errors)
checkUserCount(t, resp.Data, 0)
// delete the user
deleteUser(t, accessJwt, userid)
resp = createUser(t, accessJwt, userid, userpassword)
resp.RequireNoGraphQLErrors(t)
// now we should be able to create the user again
checkUserCount(t, resp.Data, 1)
}
func resetUser(t *testing.T) {
accessJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: "groot",
Passwd: "password",
})
require.NoError(t, err, "login failed")
// clean up the user to allow repeated running of this test
deleteUser(t, accessJwt, userid)
glog.Infof("deleted user")
resp := createUser(t, accessJwt, userid, userpassword)
resp.RequireNoGraphQLErrors(t)
checkUserCount(t, resp.Data, 1)
glog.Infof("created user")
}
func TestReservedPredicates(t *testing.T) {
// This test uses the groot account to ensure that reserved predicates
// cannot be altered even if the permissions allow it.
dg1, err := testutil.DgraphClientWithGroot(testutil.SockAddr)
if err != nil {
t.Fatalf("Error while getting a dgraph client: %v", err)
}
alterReservedPredicates(t, dg1)
}
func TestAuthorization(t *testing.T) {
if testing.Short() {
t.Skip("skipping because -short=true")
}
glog.Infof("testing with port 9180")
dg1, err := testutil.DgraphClientWithGroot(testutil.SockAddr)
if err != nil {
t.Fatalf("Error while getting a dgraph client: %v", err)
}
testAuthorization(t, dg1)
glog.Infof("done")
glog.Infof("testing with port 9182")
dg2, err := testutil.DgraphClientWithGroot(":9182")
if err != nil {
t.Fatalf("Error while getting a dgraph client: %v", err)
}
testAuthorization(t, dg2)
glog.Infof("done")
}
func testAuthorization(t *testing.T, dg *dgo.Dgraph) {
createAccountAndData(t, dg)
ctx := context.Background()
if err := dg.Login(ctx, userid, userpassword); err != nil {
t.Fatalf("unable to login using the account %v", userid)
}
// initially the query should return empty result, mutate and alter
// operations should all fail when there are no rules defined on the predicates
queryPredicateWithUserAccount(t, dg, false)
mutatePredicateWithUserAccount(t, dg, true)
alterPredicateWithUserAccount(t, dg, true)
createGroupAndAcls(t, unusedGroup, false)
// wait for 6 seconds to ensure the new acl have reached all acl caches
glog.Infof("Sleeping for 6 seconds for acl caches to be refreshed")
time.Sleep(6 * time.Second)
// now all these operations except query should fail since
// there are rules defined on the unusedGroup
queryPredicateWithUserAccount(t, dg, false)
mutatePredicateWithUserAccount(t, dg, true)
alterPredicateWithUserAccount(t, dg, true)
// create the dev group and add the user to it
createGroupAndAcls(t, devGroup, true)
// wait for 6 seconds to ensure the new acl have reached all acl caches
glog.Infof("Sleeping for 6 seconds for acl caches to be refreshed")
time.Sleep(6 * time.Second)
// now the operations should succeed again through the devGroup
queryPredicateWithUserAccount(t, dg, false)
// sleep long enough (10s per the docker-compose.yml)
// for the accessJwt to expire in order to test auto login through refresh jwt
glog.Infof("Sleeping for 4 seconds for accessJwt to expire")
time.Sleep(4 * time.Second)
mutatePredicateWithUserAccount(t, dg, false)
glog.Infof("Sleeping for 4 seconds for accessJwt to expire")
time.Sleep(4 * time.Second)
alterPredicateWithUserAccount(t, dg, false)
}
var predicateToRead = "predicate_to_read"
var queryAttr = "name"
var predicateToWrite = "predicate_to_write"
var predicateToAlter = "predicate_to_alter"
var devGroup = "dev"
var unusedGroup = "unusedGroup"
var query = fmt.Sprintf(`
{
q(func: eq(%s, "SF")) {
%s
}
}`, predicateToRead, queryAttr)
var schemaQuery = "schema {}"
func alterReservedPredicates(t *testing.T, dg *dgo.Dgraph) {
ctx := context.Background()
// Test that alter requests are allowed if the new update is the same as
// the initial update for a reserved predicate.
err := dg.Alter(ctx, &api.Operation{
Schema: "dgraph.xid: string @index(exact) @upsert .",
})
require.NoError(t, err)
err = dg.Alter(ctx, &api.Operation{
Schema: "dgraph.xid: int .",
})
require.Error(t, err)
require.Contains(t, err.Error(),
"predicate dgraph.xid is reserved and is not allowed to be modified")
err = dg.Alter(ctx, &api.Operation{
DropAttr: "dgraph.xid",
})
require.Error(t, err)
require.Contains(t, err.Error(),
"predicate dgraph.xid is reserved and is not allowed to be dropped")
// Test that reserved predicates act as case-insensitive.
err = dg.Alter(ctx, &api.Operation{
Schema: "dgraph.XID: int .",
})
require.Error(t, err)
require.Contains(t, err.Error(),
"predicate dgraph.XID is reserved and is not allowed to be modified")
}
func queryPredicateWithUserAccount(t *testing.T, dg *dgo.Dgraph, shouldFail bool) {
ctx := context.Background()
txn := dg.NewTxn()
_, err := txn.Query(ctx, query)
if shouldFail {
require.Error(t, err, "the query should have failed")
} else {
require.NoError(t, err, "the query should have succeeded")
}
}
func querySchemaWithUserAccount(t *testing.T, dg *dgo.Dgraph, shouldFail bool) {
ctx := context.Background()
txn := dg.NewTxn()
_, err := txn.Query(ctx, schemaQuery)
if shouldFail {
require.Error(t, err, "the query should have failed")
} else {
require.NoError(t, err, "the query should have succeeded")
}
}
func mutatePredicateWithUserAccount(t *testing.T, dg *dgo.Dgraph, shouldFail bool) {
ctx := context.Background()
txn := dg.NewTxn()
_, err := txn.Mutate(ctx, &api.Mutation{
CommitNow: true,
SetNquads: []byte(fmt.Sprintf(`_:a <%s> "string" .`, predicateToWrite)),
})
if shouldFail {
require.Error(t, err, "the mutation should have failed")
} else {
require.NoError(t, err, "the mutation should have succeeded")
}
}
func alterPredicateWithUserAccount(t *testing.T, dg *dgo.Dgraph, shouldFail bool) {
ctx := context.Background()
err := dg.Alter(ctx, &api.Operation{
Schema: fmt.Sprintf(`%s: int .`, predicateToAlter),
})
if shouldFail {
require.Error(t, err, "the alter should have failed")
} else {
require.NoError(t, err, "the alter should have succeeded")
}
}
func createAccountAndData(t *testing.T, dg *dgo.Dgraph) {
// use the groot account to clean the database
ctx := context.Background()
if err := dg.Login(ctx, x.GrootId, "password"); err != nil {
t.Fatalf("unable to login using the groot account:%v", err)
}
op := api.Operation{
DropAll: true,
}
if err := dg.Alter(ctx, &op); err != nil {
t.Fatalf("Unable to cleanup db:%v", err)
}
require.NoError(t, dg.Alter(ctx, &api.Operation{
Schema: fmt.Sprintf(`%s: string @index(exact) .`, predicateToRead),
}))
// wait for 6 seconds to ensure the new acl have reached all acl caches
glog.Infof("Sleeping for 6 seconds for acl caches to be refreshed")
time.Sleep(6 * time.Second)
// create some data, e.g. user with name alice
resetUser(t)
txn := dg.NewTxn()
_, err := txn.Mutate(ctx, &api.Mutation{
SetNquads: []byte(fmt.Sprintf("_:a <%s> \"SF\" .", predicateToRead)),
})
require.NoError(t, err)
require.NoError(t, txn.Commit(ctx))
}
func createGroup(t *testing.T, accessToken, name string) []byte {
addGroup := `
mutation addGroup($name: String!) {
addGroup(input: [{name: $name}]) {
group {
name
}
}
}`
params := testutil.GraphQLParams{
Query: addGroup,
Variables: map[string]interface{}{
"name": name,
},
}
resp := makeRequest(t, accessToken, params)
resp.RequireNoGraphQLErrors(t)
return resp.Data
}
func createGroupWithRules(t *testing.T, accessJwt, name string, rules []rule) *group {
queryParams := testutil.GraphQLParams{
Query: `
mutation addGroup($name: String!, $rules: [RuleRef]){
addGroup(input: [
{
name: $name
rules: $rules
}
]) {
group {
name
rules {
predicate
permission
}
}
}
}`,
Variables: map[string]interface{}{
"name": name,
"rules": rules,
},
}
resp := makeRequest(t, accessJwt, queryParams)
resp.RequireNoGraphQLErrors(t)
var addGroupResp struct {
AddGroup struct {
Group []group
}
}
err := json.Unmarshal(resp.Data, &addGroupResp)
require.NoError(t, err)
require.Len(t, addGroupResp.AddGroup.Group, 1)
return &addGroupResp.AddGroup.Group[0]
}
func updateGroup(t *testing.T, accessJwt, name string, setRules []rule,
removeRules []string) *group {
queryParams := testutil.GraphQLParams{
Query: `
mutation updateGroup($name: String!, $set: SetGroupPatch, $remove: RemoveGroupPatch){
updateGroup(input: {
filter: {
name: {
eq: $name
}
}
set: $set
remove: $remove
}) {
group {
name
rules {
predicate
permission
}
}
}
}`,
Variables: map[string]interface{}{
"name": name,
"set": nil,
"remove": nil,
},
}
if len(setRules) != 0 {
queryParams.Variables["set"] = map[string]interface{}{
"rules": setRules,
}
}
if len(removeRules) != 0 {
queryParams.Variables["remove"] = map[string]interface{}{
"rules": removeRules,
}
}
resp := makeRequest(t, accessJwt, queryParams)
resp.RequireNoGraphQLErrors(t)
var result struct {
UpdateGroup struct {
Group []group
}
}
err := json.Unmarshal(resp.Data, &result)
require.NoError(t, err)
require.Len(t, result.UpdateGroup.Group, 1)
return &result.UpdateGroup.Group[0]
}
func checkGroupCount(t *testing.T, resp []byte, expected int) {
type Response struct {
AddGroup struct {
Group []struct {
Name string
}
}
}
var r Response
err := json.Unmarshal(resp, &r)
require.NoError(t, err)
require.Equal(t, expected, len(r.AddGroup.Group))
}
func addToGroup(t *testing.T, accessToken, userName, group string) {
addUserToGroup := `mutation updateUser($name: String!, $group: String!) {
updateUser(input: {
filter: {
name: {
eq: $name
}
},
set: {
groups: [
{ name: $group }
]
}
}) {
user {
name
groups {
name
}
}
}
}`
params := testutil.GraphQLParams{
Query: addUserToGroup,
Variables: map[string]interface{}{
"name": userName,
"group": group,
},
}
resp := makeRequest(t, accessToken, params)
resp.RequireNoGraphQLErrors(t)
var result struct {
UpdateUser struct {
User []struct {
Name string
Groups []struct {
Name string
}
}
Name string
}
}
err := json.Unmarshal(resp.Data, &result)
require.NoError(t, err)
// There should be a user in response.
require.Len(t, result.UpdateUser.User, 1)
// User's name must be <userName>
require.Equal(t, userName, result.UpdateUser.User[0].Name)
var foundGroup bool
for _, usr := range result.UpdateUser.User {
for _, grp := range usr.Groups {
if grp.Name == group {
foundGroup = true
break
}
}
}
require.True(t, foundGroup)
}
type rule struct {
Predicate string `json:"predicate"`
Permission int32 `json:"permission"`
}
type group struct {
Name string `json:"name"`
Rules []rule `json:"rules"`
}
func makeRequest(t *testing.T, accessToken string, params testutil.GraphQLParams) *testutil.
GraphQLResponse {
return testutil.MakeGQLRequestWithAccessJwt(t, ¶ms, accessToken)
}
func addRulesToGroup(t *testing.T, accessToken, group string, rules []rule) {
addRuleToGroup := `mutation updateGroup($name: String!, $rules: [RuleRef!]!) {
updateGroup(input: {
filter: {
name: {
eq: $name
}
},
set: {
rules: $rules
}
}) {
group {
name
rules {
predicate
permission
}
}
}
}`
params := testutil.GraphQLParams{
Query: addRuleToGroup,
Variables: map[string]interface{}{
"name": group,
"rules": rules,
},
}
resp := makeRequest(t, accessToken, params)
resp.RequireNoGraphQLErrors(t)
rulesb, err := json.Marshal(rules)
require.NoError(t, err)
expectedOutput := fmt.Sprintf(`{
"updateGroup": {
"group": [
{
"name": "%s",
"rules": %s
}
]
}
}`, group, rulesb)
testutil.CompareJSON(t, expectedOutput, string(resp.Data))
}
func createGroupAndAcls(t *testing.T, group string, addUserToGroup bool) {
accessJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: "groot",
Passwd: "password",
})
require.NoError(t, err, "login failed")
// create a new group
resp := createGroup(t, accessJwt, group)
checkGroupCount(t, resp, 1)
// add the user to the group
if addUserToGroup {
addToGroup(t, accessJwt, userid, group)
}
rules := []rule{
{
predicateToRead, Read.Code,
},
{
queryAttr, Read.Code,
},
{
predicateToWrite, Write.Code,
},
{
predicateToAlter, Modify.Code,
},
}
// add READ permission on the predicateToRead to the group
// also add read permission to the attribute queryAttr, which is used inside the query block
// add WRITE permission on the predicateToWrite
// add MODIFY permission on the predicateToAlter
addRulesToGroup(t, accessJwt, group, rules)
}
func TestPredicatePermission(t *testing.T) {
if testing.Short() {
t.Skip("skipping because -short=true")
}
glog.Infof("testing with port 9180")
dg, err := testutil.DgraphClientWithGroot(testutil.SockAddr)
if err != nil {
t.Fatalf("Error while getting a dgraph client: %v", err)
}
createAccountAndData(t, dg)
ctx := context.Background()
err = dg.Login(ctx, userid, userpassword)
require.NoError(t, err, "Logging in with the current password should have succeeded")
// Schema query is allowed to all logged in users.
querySchemaWithUserAccount(t, dg, false)
// The query should return emptry response, alter and mutation
// should be blocked when no rule is defined.
queryPredicateWithUserAccount(t, dg, false)
mutatePredicateWithUserAccount(t, dg, true)
alterPredicateWithUserAccount(t, dg, true)
createGroupAndAcls(t, unusedGroup, false)
// Wait for 6 seconds to ensure the new acl have reached all acl caches.
glog.Infof("Sleeping for 6 seconds for acl caches to be refreshed")
time.Sleep(6 * time.Second)
// The operations except query should fail when there is a rule defined, but the
// current user is not allowed.
queryPredicateWithUserAccount(t, dg, false)
mutatePredicateWithUserAccount(t, dg, true)
alterPredicateWithUserAccount(t, dg, true)
// Schema queries should still succeed since they are not tied to specific predicates.
querySchemaWithUserAccount(t, dg, false)
}
func TestAccessWithoutLoggingIn(t *testing.T) {
dg, err := testutil.DgraphClientWithGroot(testutil.SockAddr)
require.NoError(t, err)
createAccountAndData(t, dg)
dg, err = testutil.DgraphClient(testutil.SockAddr)
require.NoError(t, err)
// Without logging in, the anonymous user should be evaluated as if the user does not
// belong to any group, and access should not be granted if there is no ACL rule defined
// for a predicate.
queryPredicateWithUserAccount(t, dg, true)
mutatePredicateWithUserAccount(t, dg, true)
alterPredicateWithUserAccount(t, dg, true)
// Schema queries should fail if the user has not logged in.
querySchemaWithUserAccount(t, dg, true)
}
func TestUnauthorizedDeletion(t *testing.T) {
ctx, _ := context.WithTimeout(context.Background(), 100*time.Second)
unAuthPred := "unauthorizedPredicate"
dg, err := testutil.DgraphClientWithGroot(testutil.SockAddr)
require.NoError(t, err)
op := api.Operation{
DropAll: true,
}
require.NoError(t, dg.Alter(ctx, &op))
op = api.Operation{
Schema: fmt.Sprintf("%s: string @index(exact) .", unAuthPred),
}
require.NoError(t, dg.Alter(ctx, &op))
resetUser(t)
accessJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: "groot",
Passwd: "password",
})
require.NoError(t, err, "login failed")
createGroup(t, accessJwt, devGroup)
addToGroup(t, accessJwt, userid, devGroup)
txn := dg.NewTxn()
mutation := &api.Mutation{
SetNquads: []byte(fmt.Sprintf("_:a <%s> \"testdata\" .", unAuthPred)),
CommitNow: true,
}
resp, err := txn.Mutate(ctx, mutation)
require.NoError(t, err)
nodeUID, ok := resp.Uids["a"]
require.True(t, ok)
addRulesToGroup(t, accessJwt, devGroup, []rule{{unAuthPred, 0}})
userClient, err := testutil.DgraphClient(testutil.SockAddr)
require.NoError(t, err)
time.Sleep(6 * time.Second)
err = userClient.Login(ctx, userid, userpassword)
require.NoError(t, err)
txn = userClient.NewTxn()
mutString := fmt.Sprintf("<%s> <%s> * .", nodeUID, unAuthPred)
mutation = &api.Mutation{
DelNquads: []byte(mutString),
CommitNow: true,
}
_, err = txn.Mutate(ctx, mutation)
require.Error(t, err)
require.Contains(t, err.Error(), "PermissionDenied")
}
func TestGuardianAccess(t *testing.T) {
ctx, _ := context.WithTimeout(context.Background(), 100*time.Second)
dg, err := testutil.DgraphClientWithGroot(testutil.SockAddr)
require.NoError(t, err)
testutil.DropAll(t, dg)
op := api.Operation{Schema: "unauthpred: string @index(exact) ."}
require.NoError(t, dg.Alter(ctx, &op))
addNewUserToGroup(t, "guardian", "guardianpass", "guardians")
mutation := &api.Mutation{
SetNquads: []byte("_:a <unauthpred> \"testdata\" ."),
CommitNow: true,
}
resp, err := dg.NewTxn().Mutate(ctx, mutation)
require.NoError(t, err)
nodeUID, ok := resp.Uids["a"]
require.True(t, ok)
time.Sleep(6 * time.Second)
gClient, err := testutil.DgraphClient(testutil.SockAddr)
require.NoError(t, err, "Error while creating client")
gClient.Login(ctx, "guardian", "guardianpass")
mutString := fmt.Sprintf("<%s> <unauthpred> \"testdata\" .", nodeUID)
mutation = &api.Mutation{SetNquads: []byte(mutString), CommitNow: true}
_, err = gClient.NewTxn().Mutate(ctx, mutation)
require.NoError(t, err, "Error while mutating unauthorized predicate")
query := `
{
me(func: eq(unauthpred, "testdata")) {
uid
}
}`
resp, err = gClient.NewTxn().Query(ctx, query)
require.NoError(t, err, "Error while querying unauthorized predicate")
require.Contains(t, string(resp.GetJson()), "uid")
op = api.Operation{Schema: "unauthpred: int ."}
require.NoError(t, gClient.Alter(ctx, &op), "Error while altering unauthorized predicate")
gqlResp := removeUserFromGroup(t, "guardian", "guardians")
gqlResp.RequireNoGraphQLErrors(t)
expectedOutput := `{"updateUser":{"user":[{"name":"guardian","groups":[]}]}}`
require.JSONEq(t, expectedOutput, string(gqlResp.Data))
_, err = gClient.NewTxn().Query(ctx, query)
require.Error(t, err, "Query succeeded. It should have failed.")
}
func addNewUserToGroup(t *testing.T, userName, password, groupName string) {
accessJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: "groot",
Passwd: "password",
})
require.NoError(t, err, "login failed")
resp := createUser(t, accessJwt, userName, password)
resp.RequireNoGraphQLErrors(t)
checkUserCount(t, resp.Data, 1)
addToGroup(t, accessJwt, userName, groupName)
}
func removeUserFromGroup(t *testing.T, userName, groupName string) *testutil.GraphQLResponse {
removeUserGroups := `mutation updateUser($name: String!, $groupName: String!) {
updateUser(input: {
filter: {
name: {
eq: $name
}
},
remove: {
groups: [{ name: $groupName }]
}
}) {
user {
name
groups {
name
}
}
}
}`
params := testutil.GraphQLParams{
Query: removeUserGroups,
Variables: map[string]interface{}{
"name": userName,
"groupName": groupName,
},
}
accessJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: "groot",
Passwd: "password",
})
require.NoError(t, err, "login failed")
resp := makeRequest(t, accessJwt, params)
return resp
}
func TestQueryRemoveUnauthorizedPred(t *testing.T) {
ctx, _ := context.WithTimeout(context.Background(), 100*time.Second)
dg, err := testutil.DgraphClientWithGroot(testutil.SockAddr)
require.NoError(t, err)
testutil.DropAll(t, dg)
op := api.Operation{Schema: `
name : string @index(exact) .
nickname : string @index(exact) .
age : int .
`}
require.NoError(t, dg.Alter(ctx, &op))
resetUser(t)
accessJwt, _, err := testutil.HttpLogin(&testutil.LoginParams{
Endpoint: adminEndpoint,
UserID: "groot",
Passwd: "password",
})
require.NoError(t, err, "login failed")
createGroup(t, accessJwt, devGroup)
addToGroup(t, accessJwt, userid, devGroup)
txn := dg.NewTxn()
mutation := &api.Mutation{
SetNquads: []byte(`
_:a <name> "RandomGuy" .
_:a <age> "23" .
_:a <nickname> "RG" .
_:b <name> "RandomGuy2" .
_:b <age> "25" .
_:b <nickname> "RG2" .
`),