forked from pydio/cells
/
access-list.go
591 lines (527 loc) · 17.5 KB
/
access-list.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
/*
* Copyright (c) 2019-2021. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
package permissions
import (
"context"
"sort"
"strings"
"sync"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/log"
defaults "github.com/pydio/cells/common/micro"
"github.com/pydio/cells/common/proto/idm"
"github.com/pydio/cells/common/proto/tree"
"github.com/pydio/cells/x/configx"
json "github.com/pydio/cells/x/jsonx"
)
// PolicyResolver implements the check of an object against a set of ACL policies
type PolicyResolver func(ctx context.Context, request *idm.PolicyEngineRequest, explicitOnly bool) (*idm.PolicyEngineResponse, error)
// VirtualPathResolver must be able to load virtual nodes based on their UUID
type VirtualPathResolver func(context.Context, *tree.Node) (*tree.Node, bool)
const (
FrontWsScopeAll = "PYDIO_REPO_SCOPE_ALL"
FrontWsScopeShared = "PYDIO_REPO_SCOPE_SHARED"
)
var (
AclRead = &idm.ACLAction{Name: "read", Value: "1"}
AclWrite = &idm.ACLAction{Name: "write", Value: "1"}
AclDeny = &idm.ACLAction{Name: "deny", Value: "1"}
AclPolicy = &idm.ACLAction{Name: "policy"}
AclQuota = &idm.ACLAction{Name: "quota"}
AclLock = &idm.ACLAction{Name: "lock"}
AclChildLock = &idm.ACLAction{Name: "child_lock"}
AclContentLock = &idm.ACLAction{Name: "content_lock"}
AclFrontAction_ = &idm.ACLAction{Name: "action:*"}
AclFrontParam_ = &idm.ACLAction{Name: "parameter:*"}
AclWsrootActionName = "workspace-path"
AclRecycleRoot = &idm.ACLAction{Name: "recycle_root", Value: "1"}
ResolvePolicyRequest PolicyResolver
)
func init() {
// Use default resolver (loads policies in memory and cache them for 1mn)
ResolvePolicyRequest = LocalACLPoliciesResolver
}
// AccessList is a merged representation of all ACLs that a user has access to.
// ACLs are merged using a Bitmask form to ease flags detections and comparisons.
type AccessList struct {
Workspaces map[string]*idm.Workspace
acls []*idm.ACL
workspacesNodes map[string]map[string]Bitmask
OrderedRoles []*idm.Role
FrontPluginsValues []*idm.ACL
claimsScopes map[string]Bitmask
hasClaimsScopes bool
uuidACLsMux sync.RWMutex
uuidACLs map[string]Bitmask
pathsACLsMux sync.RWMutex
pathsACLs map[string]Bitmask
}
// NewAccessList creates a new AccessList.
func NewAccessList(orderedRoles []*idm.Role, Acls ...[]*idm.ACL) *AccessList {
acl := &AccessList{
Workspaces: make(map[string]*idm.Workspace),
OrderedRoles: orderedRoles,
}
for _, lists := range Acls {
acl.acls = append(acl.acls, lists...)
}
return acl
}
// Append appends an additional list of ACLs.
func (a *AccessList) Append(acls []*idm.ACL) {
a.acls = append(a.acls, acls...)
}
// AppendClaimsScopes appends some specific permissions passed through claims.
// Currently only strings like "node:uuid:perm" are supported
func (a *AccessList) AppendClaimsScopes(ss []string) {
a.hasClaimsScopes = true
a.parseClaimScopes(ss)
}
// HasPolicyBasedAcls checks if there are policy based acls.
func (a *AccessList) HasPolicyBasedAcls() bool {
for _, acl := range a.acls {
if acl.Action.Name == AclPolicy.Name {
return true
}
}
return false
}
// Flatten performs actual flatten.
func (a *AccessList) Flatten(ctx context.Context) {
nodes, workspaces := a.flattenNodes(ctx, a.acls)
a.uuidACLsMux.Lock()
a.uuidACLs = nodes
a.uuidACLsMux.Unlock()
a.workspacesNodes = workspaces
}
// GetWorkspacesNodes gets detected workspace root nodes that are then
// used to populate the Workspace keys.
func (a *AccessList) GetWorkspacesNodes() map[string]map[string]Bitmask {
return a.workspacesNodes
}
// GetNodeBitmask finds a bitmask by node Id
func (a *AccessList) GetNodeBitmask(nodeId string) (Bitmask, bool) {
a.uuidACLsMux.RLock()
defer a.uuidACLsMux.RUnlock()
if b, o := a.uuidACLs[nodeId]; o {
return b, o
}
return Bitmask{}, false
}
// SetNodeBitmask sets a bitmask for nodeId.
func (a *AccessList) SetNodeBitmask(nodeId string, b Bitmask) {
a.uuidACLsMux.Lock()
if a.uuidACLs == nil {
a.uuidACLs = map[string]Bitmask{}
}
a.uuidACLs[nodeId] = b
a.uuidACLsMux.Unlock()
}
// ReplicateBitmask copies a bitmask value from one position to another
func (a *AccessList) ReplicateBitmask(fromUuid, toUuid string) bool {
// Protect this method from concurrency
a.uuidACLsMux.Lock()
defer a.uuidACLsMux.Unlock()
if b, o := a.uuidACLs[fromUuid]; o {
a.uuidACLs[toUuid] = b
return true
}
return false
}
// GetAccessibleWorkspaces retrieves a map of accessible workspaces.
func (a *AccessList) GetAccessibleWorkspaces(ctx context.Context) map[string]string {
accessListWsNodes := a.GetWorkspacesNodes()
results := make(map[string]string)
for wsId, wsNodes := range accessListWsNodes {
rights := &right{}
for nodeId := range wsNodes {
if a.CanRead(ctx, &tree.Node{Uuid: nodeId}) {
rights.Read = true
}
if a.CanWrite(ctx, &tree.Node{Uuid: nodeId}) {
rights.Write = true
}
}
if rights.isAccessible() {
results[wsId] = rights.toString()
}
}
return results
}
// CanRead checks if a node has READ access.
func (a *AccessList) CanRead(ctx context.Context, nodes ...*tree.Node) bool {
if a.claimsScopesDeny(ctx, nodes[0], FlagRead) {
return false
}
deny, mask := a.parentMaskOrDeny(ctx, false, nodes...)
return !deny && mask.HasFlag(ctx, FlagRead, nodes...)
}
// CanWrite checks if a node has WRITE access.
func (a *AccessList) CanWrite(ctx context.Context, nodes ...*tree.Node) bool {
if a.claimsScopesDeny(ctx, nodes[0], FlagWrite) {
return false
}
deny, mask := a.parentMaskOrDeny(ctx, false, nodes...)
return !deny && mask.HasFlag(ctx, FlagWrite, nodes...)
}
func (a *AccessList) HasExplicitDeny(ctx context.Context, flag BitmaskFlag, nodes ...*tree.Node) bool {
_, mask := a.parentMaskOrDeny(ctx, false, nodes...)
// Only test first node - do not test parents
if len(nodes) > 1 {
nodes = nodes[:1]
}
return mask.HasPolicyExplicitDeny(ctx, flag, nodes...)
}
// CanReadWithResolver checks if a node has READ access, using VirtualPathResolver if necessary
func (a *AccessList) CanReadWithResolver(ctx context.Context, resolver VirtualPathResolver, nodes ...*tree.Node) bool {
a.replicateMasksResolved(ctx, resolver)
if a.claimsScopesDeny(ctx, nodes[0], FlagRead) {
return false
}
deny, mask := a.parentMaskOrDeny(ctx, false, nodes...)
return !deny && mask.HasFlag(ctx, FlagRead, nodes...)
}
// CanWriteWithResolver checks if a node has WRITE access, using VirtualPathResolver if necessary.
func (a *AccessList) CanWriteWithResolver(ctx context.Context, resolver VirtualPathResolver, nodes ...*tree.Node) bool {
a.replicateMasksResolved(ctx, resolver)
if a.claimsScopesDeny(ctx, nodes[0], FlagWrite) {
return false
}
deny, mask := a.parentMaskOrDeny(ctx, false, nodes...)
return !deny && mask.HasFlag(ctx, FlagWrite, nodes...)
}
// CanReadPath checks if a node has READ access based on its Path
func (a *AccessList) CanReadPath(ctx context.Context, resolver VirtualPathResolver, nodes ...*tree.Node) bool {
if a.pathsACLs == nil {
if e := a.LoadNodePathsAcls(ctx, resolver); e != nil {
log.Logger(ctx).Error("Could not load NodePathsAcls", zap.Error(e))
return false
}
}
deny, mask := a.parentMaskOrDeny(ctx, true, nodes...)
return !deny && mask.HasFlag(ctx, FlagRead, nodes...)
}
// CanWritePath checks if a node has WRITE access based on its path.
func (a *AccessList) CanWritePath(ctx context.Context, resolver VirtualPathResolver, nodes ...*tree.Node) bool {
if a.pathsACLs == nil {
if e := a.LoadNodePathsAcls(ctx, resolver); e != nil {
log.Logger(ctx).Error("Could not load NodePathsAcls", zap.Error(e))
return false
}
}
deny, mask := a.parentMaskOrDeny(ctx, true, nodes...)
return !deny && mask.HasFlag(ctx, FlagWrite, nodes...)
}
// IsLocked checks if a node bitmask has a FlagLock value.
func (a *AccessList) IsLocked(ctx context.Context, nodes ...*tree.Node) bool {
// First we check for parents
mask, _ := a.firstMaskForParents(ctx, nodes...)
if mask.HasFlag(ctx, FlagLock, nodes[0]) {
return true
}
if mask := a.firstMaskForChildren(ctx, nodes[0]); mask.HasFlag(ctx, FlagLock, nodes[0]) {
return true
}
return false
}
// BelongsToWorkspaces finds corresponding workspace parents for this node.
func (a *AccessList) BelongsToWorkspaces(ctx context.Context, nodes ...*tree.Node) (workspaces []*idm.Workspace, workspacesRoots map[string]string) {
wsNodes := a.GetWorkspacesNodes()
foundWorkspaces := make(map[string]bool)
workspacesRoots = make(map[string]string)
for _, node := range nodes {
uuid := node.Uuid
for wsId, wsRoots := range wsNodes {
if _, has := a.Workspaces[wsId]; !has {
continue
}
for rootId := range wsRoots {
if rootId == uuid {
foundWorkspaces[wsId] = true
workspacesRoots[wsId] = rootId
}
}
}
}
for workspaceId := range foundWorkspaces {
workspaces = append(workspaces, a.Workspaces[workspaceId])
}
return workspaces, workspacesRoots
}
// LoadNodePathsAcls retrieve each nodes by UUID, to which an ACL is attached
func (a *AccessList) LoadNodePathsAcls(ctx context.Context, resolver VirtualPathResolver) error {
a.uuidACLsMux.RLock()
size := len(a.uuidACLs)
a.uuidACLsMux.RUnlock()
a.pathsACLs = make(map[string]Bitmask, size)
cli := tree.NewNodeProviderStreamerClient(common.ServiceGrpcNamespace_+common.ServiceTree, defaults.NewClient())
st, e := cli.ReadNodeStream(ctx)
if e != nil {
return e
}
defer st.Close()
// Retrieving path foreach ids
a.uuidACLsMux.RLock()
a.pathsACLsMux.Lock()
for nodeID, b := range a.uuidACLs {
if n, ok := resolver(ctx, &tree.Node{Uuid: nodeID}); ok {
log.Logger(ctx).Debug("Acl.LoadNodePathsAcls : Loading resolved node", n.Zap())
a.pathsACLs[strings.TrimSuffix(n.Path, "/")] = b
continue
}
err := st.Send(&tree.ReadNodeRequest{Node: &tree.Node{Uuid: nodeID}})
if err != nil {
return err
}
resp, err := st.Recv()
if err != nil || resp.Node == nil {
continue
}
a.pathsACLs[strings.TrimSuffix(resp.Node.Path, "/")] = b
}
a.uuidACLsMux.RUnlock()
a.pathsACLsMux.Unlock()
return nil
}
func (a *AccessList) replicateMasksResolved(ctx context.Context, resolver VirtualPathResolver) {
a.uuidACLsMux.Lock()
for id, bm := range a.uuidACLs {
if res, o := resolver(ctx, &tree.Node{Uuid: id}); o {
a.uuidACLs[res.Uuid] = bm
}
}
a.uuidACLsMux.Unlock()
}
// FlattenedFrontValues generates a configx.Values with frontend actions/parameters configs
func (a *AccessList) FlattenedFrontValues() configx.Values {
output := configx.New()
for _, role := range a.OrderedRoles {
for _, acl := range a.FrontPluginsValues {
if acl.RoleID != role.Uuid {
continue
}
name := acl.Action.Name
value := acl.Action.Value
scope := acl.WorkspaceID
var iVal interface{}
if e := json.Unmarshal([]byte(value), &iVal); e != nil {
// May not be marshalled, use original string instead
iVal = value
}
parts := strings.Split(name, ":")
t := parts[0]
p := parts[1]
n := parts[2]
if t == "action" {
output.Val("actions", p, n, scope).Set(iVal)
} else {
output.Val("parameters", p, n, scope).Set(iVal)
}
}
}
return output
}
// Zap simply returns a zapcore.Field object populated with this aggregated AccessList under a standard key
func (a *AccessList) Zap() zapcore.Field {
return zap.Any(common.KeyAccessList, a)
}
/***************
PRIVATE METHODS
****************/
// Flatten Permissions based on all the lists received :
// First go through each nodes and create Bitmask for each one, organized by roles
// Then flatten roles by keeping only last Bitmask found if node appears many times in many roles.
//
// At the same time, collect nodes that are flagged with a "WorkspaceID" in ACL to compute the list of
// accessible roots. Other permissions are used a simple folder permissions, they do not trigger a new workspace
// in the list.
func (a *AccessList) flattenNodes(ctx context.Context, aclList []*idm.ACL) (map[string]Bitmask, map[string]map[string]Bitmask) {
flattenedNodes := make(map[string]Bitmask)
flattenedWorkspaces := make(map[string]map[string]Bitmask)
detectedWorkspaces := make(map[string]map[string]string)
roles := make(map[string]map[string]Bitmask)
// Create Bitmasks for each node, for each role
for _, acl := range aclList {
if acl.NodeID == "" {
continue
}
var roleNodes map[string]Bitmask
if test, ok := roles[acl.RoleID]; ok {
roleNodes = test
} else {
roleNodes = make(map[string]Bitmask)
}
var nodeAcls Bitmask
if test, ok := roleNodes[acl.NodeID]; ok {
nodeAcls = test
} else {
nodeAcls = Bitmask{}
}
if flag, ok := NamesToFlags[acl.Action.Name]; ok {
if flag == FlagPolicy {
nodeAcls.AddPolicyFlag(acl.Action.Value)
} else if flag == FlagQuota {
nodeAcls.AddValueFlag(flag, acl.Action.Value)
} else {
nodeAcls.AddFlag(flag)
}
}
roleNodes[acl.NodeID] = nodeAcls
roles[acl.RoleID] = roleNodes
if acl.WorkspaceID != "" {
if _, ok := detectedWorkspaces[acl.WorkspaceID]; !ok {
detectedWorkspaces[acl.WorkspaceID] = make(map[string]string)
}
detectedWorkspaces[acl.WorkspaceID][acl.NodeID] = acl.NodeID
}
}
// Now flatten on roles : last role wins on each node
for _, role := range a.OrderedRoles {
if roleNodes, ok := roles[role.Uuid]; ok {
for nodeId, bitmask := range roleNodes {
flattenedNodes[nodeId] = bitmask
}
}
}
for workspaceId, workspaceRootNodes := range detectedWorkspaces {
wsRoots := make(map[string]Bitmask)
for nodeId := range workspaceRootNodes {
mask := flattenedNodes[nodeId]
if !mask.HasFlag(ctx, FlagDeny) {
wsRoots[nodeId] = mask
}
}
if len(wsRoots) > 0 {
flattenedWorkspaces[workspaceId] = wsRoots
}
}
return flattenedNodes, flattenedWorkspaces
}
// parentMaskOrDeny browses access list from current node to ROOT, going through each parent.
// If there is a deny anywhere up the path, it returns that deny,
// otherwise it sends the first Bitmask found (closest parent having a Bitmask set).
func (a *AccessList) parentMaskOrDeny(ctx context.Context, byPath bool, nodes ...*tree.Node) (bool, Bitmask) {
var firstParent Bitmask
var hasParentDeny bool
for _, node := range nodes {
var checkOn map[string]Bitmask
var checkKey string
var mux *sync.RWMutex
if byPath {
mux = &a.pathsACLsMux
checkOn = a.pathsACLs
checkKey = strings.Trim(node.Path, "/")
} else {
mux = &a.uuidACLsMux
checkOn = a.uuidACLs
checkKey = node.Uuid
}
mux.RLock()
if bitmask, ok := checkOn[checkKey]; ok {
if firstParent.BitmaskFlag == BitmaskFlag(0) {
firstParent = bitmask
}
if bitmask.HasFlag(ctx, FlagDeny, node) {
mux.RUnlock()
return true, Bitmask{BitmaskFlag: FlagDeny}
}
}
mux.RUnlock()
}
return hasParentDeny, firstParent
}
// firstMaskForParents just climbs up the tree and gets the first non empty mask found.
func (a *AccessList) firstMaskForParents(ctx context.Context, nodes ...*tree.Node) (Bitmask, *tree.Node) {
a.uuidACLsMux.RLock()
for _, node := range nodes {
if bitmask, ok := a.uuidACLs[node.Uuid]; ok {
return bitmask, node
}
}
a.uuidACLsMux.RUnlock()
return Bitmask{}, nil
}
// firstMaskForChildren look through all the access list pathes to get the first mask available for the node given in argument
func (a *AccessList) firstMaskForChildren(ctx context.Context, node *tree.Node) Bitmask {
a.pathsACLsMux.RLock()
keys := make([]string, 0, len(a.pathsACLs))
for k := range a.pathsACLs {
keys = append(keys, k)
}
sort.Strings(keys)
for _, p := range keys {
if strings.HasPrefix(p, strings.TrimRight(node.Path, "/")+"/") {
return a.pathsACLs[p]
}
}
a.pathsACLsMux.RUnlock()
return Bitmask{}
}
// parseClaimScopes parse scopes and store them internally
func (a *AccessList) parseClaimScopes(ss []string) {
if a.claimsScopes == nil {
a.claimsScopes = make(map[string]Bitmask)
}
for _, s := range ss {
// Look for scopes like "node:uuid:perm"
parts := strings.Split(s, ":")
if len(parts) != 3 || parts[0] != "node" {
continue
}
uuid := parts[1]
flag := Bitmask{}
if strings.Contains(parts[2], "r") {
flag.AddFlag(FlagRead)
}
if strings.Contains(parts[2], "w") {
flag.AddFlag(FlagWrite)
}
a.claimsScopes[uuid] = flag
}
}
// claimsScopesDeny checks if claimsScopes are set and verify node UUID against them
func (a *AccessList) claimsScopesDeny(ctx context.Context, node *tree.Node, perm BitmaskFlag) bool {
if a.hasClaimsScopes {
if flag, o := a.claimsScopes[node.Uuid]; !o || !flag.HasFlag(ctx, perm) {
return true
}
}
return false
}
// right is a tool struct to compute right strings
type right struct {
Read bool
Write bool
}
func (r *right) isAccessible() bool {
return r.Read || r.Write
}
func (r *right) toString() string {
var s []string
if r.Read {
s = append(s, "read")
}
if r.Write {
s = append(s, "write")
}
return strings.Join(s, ",")
}