forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
policies.go
200 lines (180 loc) · 5.93 KB
/
policies.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
/*
* Copyright (c) 2019. 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"
"fmt"
"path"
"strings"
"time"
"github.com/pydio/cells/idm/policy/converter"
"github.com/ory/ladon"
"github.com/ory/ladon/manager/memory"
"github.com/patrickmn/go-cache"
"github.com/pydio/cells/common"
defaults "github.com/pydio/cells/common/micro"
"github.com/micro/go-micro/metadata"
"github.com/pydio/cells/common/auth/claim"
"github.com/pydio/cells/common/proto/idm"
"github.com/pydio/cells/common/proto/tree"
"github.com/pydio/cells/common/service/context"
)
const (
PolicyNodeMetaName = "NodeMetaName"
PolicyNodeMetaPath = "NodeMetaPath"
PolicyNodeMetaType = "NodeMetaType"
PolicyNodeMetaExtension = "NodeMetaExtension"
PolicyNodeMetaSize = "NodeMetaSize"
PolicyNodeMetaMTime = "NodeMetaMTime"
PolicyNodeMeta_ = "NodeMeta:"
)
// PolicyRequestSubjectsFromUser builds an array of string subjects from the passed User.
func PolicyRequestSubjectsFromUser(user *idm.User) []string {
subjects := []string{
fmt.Sprintf("user:%s", user.Login),
}
if prof, ok := user.Attributes["profile"]; ok {
subjects = append(subjects, fmt.Sprintf("profile:%s", prof))
} else {
subjects = append(subjects, "profile:standard")
}
for _, r := range user.Roles {
subjects = append(subjects, fmt.Sprintf("role:%s", r.Uuid))
}
return subjects
}
// PolicyRequestSubjectsFromClaims builds an array of string subjects from the passed Claims.
func PolicyRequestSubjectsFromClaims(claims claim.Claims) []string {
subjects := []string{
fmt.Sprintf("user:%s", claims.Name),
}
if claims.Profile != "" {
subjects = append(subjects, fmt.Sprintf("profile:%s", claims.Profile))
} else {
subjects = append(subjects, "profile:standard")
}
for _, r := range strings.Split(claims.Roles, ",") {
subjects = append(subjects, fmt.Sprintf("role:%s", r))
}
return subjects
}
// PolicyContextFromMetadata extracts metadata directly from the context and enriches the passed policyContext.
func PolicyContextFromMetadata(policyContext map[string]string, ctx context.Context) {
if ctxMeta, has := metadata.FromContext(ctx); has {
for _, key := range []string{
servicecontext.HttpMetaRemoteAddress,
servicecontext.HttpMetaUserAgent,
servicecontext.HttpMetaContentType,
servicecontext.HttpMetaProtocol,
servicecontext.HttpMetaHostname,
servicecontext.HttpMetaHost,
servicecontext.HttpMetaPort,
servicecontext.ClientTime,
servicecontext.ServerTime,
} {
if val, hasKey := ctxMeta[key]; hasKey {
policyContext[key] = val
// log.Logger(ctx).Error("Set key: "+key, zap.Any("value", val))
}
}
}
}
// PolicyContextFromNode extracts metadata from the Node and enriches the passed policyContext.
func PolicyContextFromNode(policyContext map[string]string, node *tree.Node) {
policyContext[PolicyNodeMetaName] = node.GetStringMeta("name")
policyContext[PolicyNodeMetaPath] = node.Path
policyContext[PolicyNodeMetaType] = node.GetType().String()
policyContext[PolicyNodeMetaMTime] = fmt.Sprintf("%v", node.MTime)
policyContext[PolicyNodeMetaSize] = fmt.Sprintf("%v", node.Size)
policyContext[PolicyNodeMetaExtension] = strings.TrimLeft(path.Ext(node.Path), ".")
ms := node.GetMetaStore()
if ms == nil {
return
}
for k, _ := range ms {
policyContext[PolicyNodeMeta_+k] = node.GetStringMeta(k)
}
}
var checkersCache = cache.New(1*time.Minute, 10*time.Minute)
func loadPoliciesByResourcesType(ctx context.Context, resType string) ([]*idm.Policy, error) {
cli := idm.NewPolicyEngineServiceClient(common.ServiceGrpcNamespace_+common.ServicePolicy, defaults.NewClient())
r, e := cli.ListPolicyGroups(ctx, &idm.ListPolicyGroupsRequest{})
if e != nil {
return nil, e
}
var policies []*idm.Policy
for _, g := range r.PolicyGroups {
for _, p := range g.Policies {
isType := false
for _, res := range p.Resources {
if res == resType {
isType = true
break
}
}
if isType {
policies = append(policies, p)
}
}
}
return policies, nil
}
func CachedPoliciesChecker(ctx context.Context, resType string) (ladon.Warden, error) {
if ww, ok := checkersCache.Get(resType); ok {
return ww.(ladon.Warden), nil
}
w := &ladon.Ladon{
Manager: memory.NewMemoryManager(),
}
if policies, err := loadPoliciesByResourcesType(ctx, resType); err != nil {
return nil, nil
} else {
for _, pol := range policies {
w.Manager.Create(converter.ProtoToLadonPolicy(pol))
}
}
checkersCache.Set(resType, w, cache.DefaultExpiration)
return w, nil
}
func LocalACLPoliciesResolver(ctx context.Context, request *idm.PolicyEngineRequest) (*idm.PolicyEngineResponse, error) {
checker, e := CachedPoliciesChecker(ctx, "acl")
if e != nil {
return nil, e
}
cx := ladon.Context{}
for k, v := range request.Context {
cx[k] = v
}
allow := false
for _, subject := range request.Subjects {
request := &ladon.Request{
Resource: request.Resource,
Subject: subject,
Action: request.Action,
Context: cx,
}
if err := checker.IsAllowed(request); err != nil && err == ladon.ErrRequestForcefullyDenied {
break
} else if err == nil {
allow = true
} // Else "default deny" => continue checking
}
return &idm.PolicyEngineResponse{Allowed: allow}, nil
}