This repository has been archived by the owner on Feb 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo.go
563 lines (484 loc) · 13.6 KB
/
repo.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
//--------------------------------------------------------------------------
// Copyright 2018 infinimesh
// www.infinimesh.io
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//--------------------------------------------------------------------------
package dgraph
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"strings"
"github.com/dgraph-io/dgo"
"github.com/dgraph-io/dgo/protos/api"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/slntopp/infinimesh/pkg/node"
"github.com/slntopp/infinimesh/pkg/node/nodepb"
)
//isPermissionSufficient is for checking permission on namespace
func isPermissionSufficient(required, actual string) bool {
switch required {
case "WRITE":
return actual == "WRITE"
case "READ":
return actual == "WRITE" || actual == "READ"
default:
return false
}
}
//DGraphRepo is a Data type for executing Dgraph Query
type DGraphRepo struct {
Dg *dgo.Dgraph
}
//NewDGraphRepo is a method to connect to Dgraph Database
func NewDGraphRepo(dg *dgo.Dgraph) node.Repo {
return &DGraphRepo{Dg: dg}
}
//checkType is a method to type the type of the object
func checkType(ctx context.Context, txn *dgo.Txn, uid, _type string) bool {
q := `query object($_uid: string, $type: string) {
object(func: uid($_uid)) @filter(eq(type, $type)) {
uid
}
}
`
resp, err := txn.QueryWithVars(ctx, q, map[string]string{
"$_uid": uid,
"$type": _type,
})
if err != nil {
return false
}
var result struct {
Object []map[string]interface{} `json:"object"`
}
err = json.Unmarshal(resp.Json, &result)
if err != nil {
return false
}
return len(result.Object) > 0
}
//NameExists is a method to check if the object name already exists
func NameExists(ctx context.Context, txn *dgo.Txn, name, namespace, parent string) bool { //nolint
var q string
if parent == "" {
q = `query object($name: string, $namespace: string, $parent: uid){
object(func: eq(name, $name)) @cascade {
uid
name
~owns @filter(eq(name, $namespace)) {
name
}
}
}
`
} else {
q = `query exists($name: string, $namespace: string, $parent: uid){
exists(func: eq(name, $name)) @cascade {
uid
name
~owns @filter(eq(name, $namespace)) {
name
}
~children @filter(uid($parent)) {
uid
name
}
}
}
`
}
resp, err := txn.QueryWithVars(ctx, q, map[string]string{
"$parent": parent,
"$name": name,
"$namespace": namespace,
})
if err != nil {
return false
}
var result struct {
Object []map[string]interface{} `json:"object"`
}
err = json.Unmarshal(resp.Json, &result)
if err != nil {
return false
}
return len(result.Object) > 0
}
//FingerprintExists is a method to execute Dgraph Query to check if the finger print is present in the DB
func FingerprintExists(ctx context.Context, txn *dgo.Txn, fingerprint []byte) bool {
q := `query devices($fingerprint: string){
devices(func: eq(fingerprint, $fingerprint)) @normalize {
~certificates {
uid : uid
}
}
}
`
vars := map[string]string{
"$fingerprint": base64.StdEncoding.EncodeToString(fingerprint),
}
resp, err := txn.QueryWithVars(ctx, q, vars)
if err != nil {
return false
}
var result struct {
Nodes []*Node `json:"devices"`
}
err = json.Unmarshal(resp.Json, &result)
if err != nil {
return false
}
return len(result.Nodes) > 0
}
//CheckExists is a method to check if the object already exists
func CheckExists(ctx context.Context, txn *dgo.Txn, uid string) bool { //nolint
q := `query object($_uid: string) {
object(func: uid($_uid)) {
uid
}
}
`
resp, err := txn.QueryWithVars(ctx, q, map[string]string{
"$_uid": uid,
})
if err != nil {
return false
}
var result struct {
Object []map[string]interface{} `json:"object"`
}
err = json.Unmarshal(resp.Json, &result)
if err != nil {
return false
}
return len(result.Object) > 0
}
//AuthorizeNamespace is a method to authorize a user to a namespace
func (s *DGraphRepo) AuthorizeNamespace(ctx context.Context, account, namespaceID string, action nodepb.Action) (err error) {
txn := s.Dg.NewTxn()
if ok := checkType(ctx, txn, account, "account"); !ok {
return errors.New("invalid account")
}
// TODO use internal method that runs within txn
ns, err := s.GetNamespaceID(ctx, namespaceID)
if err != nil {
return err
}
_, err = txn.Mutate(ctx, &api.Mutation{
Set: []*api.NQuad{
&api.NQuad{
Subject: account,
Predicate: "access.to.namespace",
ObjectId: ns.Id,
Facets: []*api.Facet{
&api.Facet{
Key: "permission",
Value: []byte(action.String()),
ValType: api.Facet_STRING,
},
},
},
},
CommitNow: true,
})
if err != nil {
return errors.New("Failed to mutate")
}
return nil
}
//IsAuthorizedNamespace is a method to execute Dgraph Query that returns if the access to the namespace for an account is true or false
func (s *DGraphRepo) IsAuthorizedNamespace(ctx context.Context, namespaceid, account string, action nodepb.Action) (decision bool, err error) {
acc, err := s.GetAccount(ctx, account)
if err != nil {
return false, err
}
if acc.IsRoot {
return true, nil
}
params := map[string]string{
"$namespaceid": namespaceid,
"$user_id": account,
}
txn := s.Dg.NewReadOnlyTxn()
const q = `query access($namespaceid: string, $user_id: string){
access(func: uid($user_id)) @normalize @cascade {
name
uid
access.to.namespace @filter(uid($namespaceid)) @facets(permission,inherit) {
uid
name
type
}
}
}
`
res, err := txn.QueryWithVars(ctx, q, params)
if err != nil {
return false, err
}
var access struct {
Access []Namespace `json:"access"`
}
err = json.Unmarshal(res.Json, &access)
if err != nil {
return false, err
}
actionValue := strings.Split(action.String(), "_")
if len(access.Access) > 0 {
if isPermissionSufficient(actionValue[0], access.Access[0].AccessToPermission) {
return true, nil
}
}
return false, nil
}
//Authenticate is a method to authenticate the user credentials
func (s *DGraphRepo) Authenticate(ctx context.Context, username, password string) (success bool, uid string, defaultNamespace string, err error) {
txn := s.Dg.NewReadOnlyTxn()
const q = `query authenticate($username: string, $password: string){
login(func: eq(username, $username)) @filter(eq(type, "credentials")) {
uid
checkpwd(password, $password)
~has.credentials {
uid
type
enabled
default.namespace{
uid
name
}
}
}
}
`
resp, err := txn.QueryWithVars(ctx, q, map[string]string{"$username": username, "$password": password})
if err != nil {
return false, "", "", err
}
var result struct {
Login []*UsernameCredential `json:"login"`
}
err = json.Unmarshal(resp.Json, &result)
if err != nil {
return false, "", "", err
}
if len(result.Login) > 0 {
login := result.Login[0]
if login.CheckPwd {
// Success
if len(login.Account) > 0 {
if !login.Account[0].Enabled {
return false, "", "", status.Error(codes.Unauthenticated, "Account is disabled")
}
if len(login.Account[0].DefaultNamespace) > 0 {
defaultNamespace = login.Account[0].DefaultNamespace[0].Name
}
return result.Login[0].CheckPwd, login.Account[0].UID, defaultNamespace, nil
}
}
}
return false, "", "", errors.New("Invalid credentials")
}
//SetPassword is a method to change the password of the user account
func (s *DGraphRepo) SetPassword(ctx context.Context, accountid, password string) error {
txn := s.Dg.NewTxn()
const q = `query accounts($accountid: string) {
accounts(func: uid($accountid)) @filter(eq(type, "account")) {
uid
has.credentials {
name
uid
}
}
}`
response, err := txn.QueryWithVars(ctx, q, map[string]string{"$accountid": accountid})
if err != nil {
return err
}
var result struct {
Account []*Account `json:"accounts"`
}
err = json.Unmarshal(response.Json, &result)
if err != nil {
return err
}
if len(result.Account) == 0 {
return errors.New("Account not found")
}
if len(result.Account[0].HasCredentials) == 0 {
return errors.New("The account doesnot have credentials. Please set credential node.")
}
_, err = txn.Mutate(ctx, &api.Mutation{
Set: []*api.NQuad{
{
Subject: result.Account[0].HasCredentials[0].UID,
Predicate: "password",
ObjectValue: &api.Value{Val: &api.Value_StrVal{StrVal: password}},
},
},
CommitNow: true,
})
return err
}
//Authorize is a method to give access to the user
func (s *DGraphRepo) Authorize(ctx context.Context, account, node, action string, inherit bool) (err error) {
txn := s.Dg.NewTxn()
if ok := checkType(ctx, txn, account, "account"); !ok {
return errors.New("invalid account")
}
var _type string
if ok := checkType(ctx, txn, node, "namespace"); !ok {
if ok := checkType(ctx, txn, node, "object"); !ok {
return errors.New("resource does not exist")
} else {
_type = "object"
}
} else {
_type = "namespace"
}
var nq []*api.NQuad
if _type == "namespace" {
nq = append(nq,
&api.NQuad{
Subject: account,
Predicate: "access.to.namespace",
ObjectId: node,
Facets: []*api.Facet{
&api.Facet{
Key: "permission",
Value: []byte(action),
ValType: api.Facet_STRING,
},
},
},
)
} else if _type == "object" {
nq = append(nq,
&api.NQuad{
Subject: account,
Predicate: "access.to",
ObjectId: node,
Facets: []*api.Facet{
&api.Facet{
Key: "permission",
Value: []byte(action),
ValType: api.Facet_STRING,
},
&api.Facet{
Key: "inherit",
Value: []byte("true"),
ValType: api.Facet_BOOL,
},
},
},
)
}
_, err = txn.Mutate(ctx, &api.Mutation{
Set: nq,
CommitNow: true,
})
if err != nil {
return errors.New("Failed to mutate")
}
return nil
}
//IsAuthorized is a method to check if the given account has the mentioned action for the node
func (s *DGraphRepo) IsAuthorized(ctx context.Context, node, accountid, action string) (decision bool, err error) {
if node == accountid {
return true, nil
}
params := map[string]string{
"$device_id": node,
"$user_id": accountid,
}
txn := s.Dg.NewReadOnlyTxn()
const qDirect = `query direct_access($device_id: string, $user_id: string){
direct(func: uid($user_id)) @normalize @cascade {
access.to @filter(uid($device_id)) @facets(permission,inherit) {
type: type
}
}
direct_via_one_object(func: uid($user_id)) @normalize @cascade {
access.to @facets(permission,inherit) {
contains @filter(uid($device_id)) {
uid
type: type
}
}
}
}`
res, err := txn.QueryWithVars(ctx, qDirect, params)
if err != nil {
return false, err
}
var permissions struct {
Direct []Object `json:"direct"`
DirectViaObject []Object `json:"direct_via_one_object"`
}
err = json.Unmarshal(res.Json, &permissions)
if err != nil {
return false, err
}
if len(permissions.Direct) > 0 {
if isPermissionSufficient(action, permissions.Direct[0].AccessToPermission) {
return true, nil
}
}
if len(permissions.DirectViaObject) > 0 {
if isPermissionSufficient(action, permissions.DirectViaObject[0].AccessToPermission) {
return true, nil
}
}
const qRecursiveWrite = `query recursive($user_id: string, $device_id: string){
shortest(from: $user_id, to: $device_id) {
access.to @facets(eq(inherit, true) AND eq(permission,"WRITE"))
access.to.namespace @facets(eq(permission,"WRITE"))
owns
children
}
}`
const qRecursiveRead = `query recursive($user_id: string, $device_id: string){
shortest(from: $user_id, to: $device_id) {
access.to @facets(eq(inherit, true) AND (eq(permission,"WRITE") OR eq(permission, "READ")))
access.to.namespace @facets((eq(permission,"WRITE") OR eq(permission, "READ")))
owns
children
}
}`
var qRecursive string
switch action {
case "READ":
qRecursive = qRecursiveRead
case "WRITE":
qRecursive = qRecursiveWrite
default:
return false, errors.New("Invalid action")
}
res, err = txn.QueryWithVars(ctx, qRecursive, params)
if err != nil {
return false, err
}
var rez struct {
Path []map[string]interface{} `json:"_path_"`
}
if err = json.Unmarshal(res.Json, &rez); err != nil {
return false, err
}
if len(rez.Path) > 0 {
return true, nil
}
return false, nil
}