-
Notifications
You must be signed in to change notification settings - Fork 569
Expand file tree
/
Copy pathAdapter.go
More file actions
343 lines (315 loc) · 8.92 KB
/
Adapter.go
File metadata and controls
343 lines (315 loc) · 8.92 KB
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
/*
* Copyright (c) 2020-2024. Devtron Inc.
*
* 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 casbin
import (
"fmt"
"log"
"os"
"strings"
xormadapter "github.com/casbin/xorm-adapter"
xormadapter2 "github.com/casbin/xorm-adapter/v2"
"github.com/casbin/casbin"
casbinv2 "github.com/casbin/casbin/v2"
"github.com/devtron-labs/devtron/pkg/sql"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const CasbinDefaultDatabase = "casbin"
type Version string
const (
CasbinV1 Version = "V1"
CasbinV2 Version = "V2"
)
var e *casbin.SyncedEnforcer
var e2 *casbinv2.SyncedEnforcer
var enforcerImplRef *EnforcerImpl
var casbinVersion Version
type Subject string
type Resource string
type Action string
type Object string
type PolicyType string
type Policy struct {
Type PolicyType `json:"type"`
Sub Subject `json:"sub"`
Res Resource `json:"res"`
Act Action `json:"act"`
Obj Object `json:"obj"`
}
func isV2() bool {
return casbinVersion == CasbinV2
}
func setCasbinVersion() {
version := os.Getenv("USE_CASBIN_V2")
if version == "true" {
casbinVersion = CasbinV2
return
}
casbinVersion = CasbinV1
}
func Create() (*casbin.SyncedEnforcer, error) {
setCasbinVersion()
if isV2() {
return nil, nil
}
metav1.Now()
config, err := sql.GetConfig() //FIXME: use this from wire
if err != nil {
log.Println(err)
return nil, err
}
dbSpecified := true
if config.CasbinDatabase == CasbinDefaultDatabase {
dbSpecified = false
}
dataSource := fmt.Sprintf("dbname=%s user=%s password=%s host=%s port=%s sslmode=disable", config.CasbinDatabase, config.User, config.Password, config.Addr, config.Port)
a, err := xormadapter.NewAdapter("postgres", dataSource, dbSpecified) // Your driver and data source.
if err != nil {
log.Println(err)
return nil, err
}
auth, err1 := casbin.NewSyncedEnforcerSafe("./auth_model.conf", a)
if err1 != nil {
log.Println(err1)
return nil, err1
}
e = auth
err = e.LoadPolicy()
if err != nil {
log.Println(err)
return nil, err
}
log.Println("casbin Policies Loaded Successfully")
//adding our key matching func - MatchKeyFunc, to enforcer
e.AddFunction("matchKeyByPart", MatchKeyByPartFunc)
return e, nil
}
func CreateV2() (*casbinv2.SyncedEnforcer, error) {
setCasbinVersion()
if !isV2() {
return nil, nil
}
metav1.Now()
config, err := sql.GetConfig()
if err != nil {
log.Println(err)
return nil, err
}
dbSpecified := true
if config.CasbinDatabase == CasbinDefaultDatabase {
dbSpecified = false
}
dataSource := fmt.Sprintf("dbname=%s user=%s password=%s host=%s port=%s sslmode=disable", config.CasbinDatabase, config.User, config.Password, config.Addr, config.Port)
a, err := xormadapter2.NewAdapter("postgres", dataSource, dbSpecified) // Your driver and data source.
if err != nil {
log.Println(err)
return nil, err
}
//Adapter
auth, err1 := casbinv2.NewSyncedEnforcer("./auth_model.conf", a)
if err1 != nil {
log.Println(err)
return nil, err
}
e2 = auth
err = e2.LoadPolicy()
if err != nil {
log.Println(err)
return nil, err
}
log.Println("v2 casbin Policies Loaded Successfully")
//adding our key matching func - MatchKeyFunc, to enforcer
e2.AddFunction("matchKeyByPart", MatchKeyByPartFunc)
return e2, nil
}
func setEnforcerImpl(ref *EnforcerImpl) {
enforcerImplRef = ref
}
func AddPolicy(policies []Policy) []Policy {
defer handlePanic()
var failed = []Policy{}
emailIdList := map[string]struct{}{}
var err error
for _, p := range policies {
success := false
if strings.ToLower(string(p.Type)) == "p" && p.Sub != "" && p.Res != "" && p.Act != "" && p.Obj != "" {
sub := strings.ToLower(string(p.Sub))
res := strings.ToLower(string(p.Res))
act := strings.ToLower(string(p.Act))
obj := strings.ToLower(string(p.Obj))
if isV2() {
success, err = e2.AddPolicy([]string{sub, res, act, obj, "allow"})
if err != nil {
log.Println(err)
}
} else {
success = e.AddPolicy([]string{sub, res, act, obj, "allow"})
}
} else if strings.ToLower(string(p.Type)) == "g" && p.Sub != "" && p.Obj != "" {
sub := strings.ToLower(string(p.Sub))
obj := strings.ToLower(string(p.Obj))
if isV2() {
success, err = e2.AddGroupingPolicy([]string{sub, obj})
if err != nil {
log.Println(err)
}
} else {
success = e.AddGroupingPolicy([]string{sub, obj})
}
}
if !success {
failed = append(failed, p)
}
if p.Sub != "" {
emailIdList[strings.ToLower(string(p.Sub))] = struct{}{}
}
}
if len(policies) != len(failed) {
for emailId := range emailIdList {
enforcerImplRef.InvalidateCache(emailId)
}
}
return failed
}
func LoadPolicy() {
defer handlePanic()
err := enforcerImplRef.ReloadPolicy()
if err != nil {
fmt.Println("error in reloading policies", err)
}
}
func RemovePolicy(policies []Policy) []Policy {
defer handlePanic()
var failed = []Policy{}
emailIdList := map[string]struct{}{}
var err error
for _, p := range policies {
success := false
if strings.ToLower(string(p.Type)) == "p" && p.Sub != "" && p.Res != "" && p.Act != "" && p.Obj != "" {
if isV2() {
success, err = e2.RemovePolicy([]string{strings.ToLower(string(p.Sub)), strings.ToLower(string(p.Res)), strings.ToLower(string(p.Act)), strings.ToLower(string(p.Obj))})
if err != nil {
log.Println(err)
}
} else {
success = e.RemovePolicy([]string{strings.ToLower(string(p.Sub)), strings.ToLower(string(p.Res)), strings.ToLower(string(p.Act)), strings.ToLower(string(p.Obj))})
}
} else if strings.ToLower(string(p.Type)) == "g" && p.Sub != "" && p.Obj != "" {
if isV2() {
success, err = e2.RemoveGroupingPolicy([]string{strings.ToLower(string(p.Sub)), strings.ToLower(string(p.Obj))})
if err != nil {
log.Println(err)
}
} else {
success = e.RemoveGroupingPolicy([]string{strings.ToLower(string(p.Sub)), strings.ToLower(string(p.Obj))})
}
}
if !success {
failed = append(failed, p)
}
if p.Sub != "" {
emailIdList[strings.ToLower(string(p.Sub))] = struct{}{}
}
}
if len(policies) != len(failed) {
for emailId := range emailIdList {
enforcerImplRef.InvalidateCache(emailId)
}
}
return failed
}
func GetAllSubjects() []string {
if isV2() {
subjects, err := e2.GetAllSubjects()
if err != nil {
log.Println(err)
}
return subjects
}
return e.GetAllSubjects()
}
func DeleteRoleForUser(user string, role string) bool {
user = strings.ToLower(user)
role = strings.ToLower(role)
var response bool
var err error
if isV2() {
response, err = e2.DeleteRoleForUser(user, role)
if err != nil {
log.Println(err)
}
} else {
response = e.DeleteRoleForUser(user, role)
}
enforcerImplRef.InvalidateCache(user)
return response
}
func GetRolesForUser(user string) ([]string, error) {
user = strings.ToLower(user)
if isV2() {
return e2.GetRolesForUser(user)
}
return e.GetRolesForUser(user)
}
func GetUserByRole(role string) ([]string, error) {
role = strings.ToLower(role)
if isV2() {
return e2.GetUsersForRole(role)
}
return e.GetUsersForRole(role)
}
func RemovePoliciesByRoles(roles string) bool {
roles = strings.ToLower(roles)
var policyResponse bool
var err error
if isV2() {
policyResponse, err = e2.RemovePolicy([]string{roles})
if err != nil {
log.Println(err)
}
} else {
policyResponse = e.RemovePolicy([]string{roles})
}
enforcerImplRef.InvalidateCompleteCache()
return policyResponse
}
// TODO
// RemovePoliciesByAllRoles this method is currently not working as in casbin v1 internally it matches whole string arrays but we are only using role to delete,this has to be fixed or casbin has to be upgraded to v2.
// In v2 casbin, we first delete from adapter(database) and delete from model(cache) so it deletes from db but when deleting from cache it maintains a Policy Map whose key is combination of all v0,v1,v2 etc and we only have role, so it returns no error but false as output, but this is not blocking can be handled through Loading.
func RemovePoliciesByAllRoles(roles []string) bool {
rolesLower := make([]string, 0, len(roles))
for _, role := range roles {
rolesLower = append(rolesLower, strings.ToLower(role))
}
var policyResponse bool
var err error
for _, role := range rolesLower {
if isV2() {
policyResponse, err = e2.RemovePolicy([]string{role})
if err != nil {
log.Println(err)
}
} else {
policyResponse = e.RemovePolicy([]string{role})
}
}
enforcerImplRef.InvalidateCompleteCache()
return policyResponse
}
func handlePanic() {
if err := recover(); err != nil {
log.Println("panic occurred:", err)
}
}