/
model.go
384 lines (338 loc) · 9.09 KB
/
model.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
// Copyright 2017 The casbin Authors. All Rights Reserved.
//
// 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 model
import (
"container/list"
"errors"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"github.com/casbin/casbin/v2/config"
"github.com/casbin/casbin/v2/log"
"github.com/casbin/casbin/v2/util"
)
// Model represents the whole access control model.
type Model map[string]AssertionMap
// AssertionMap is the collection of assertions, can be "r", "p", "g", "e", "m".
type AssertionMap map[string]*Assertion
const defaultDomain string = ""
const defaultSeparator = "::"
var sectionNameMap = map[string]string{
"r": "request_definition",
"p": "policy_definition",
"g": "role_definition",
"e": "policy_effect",
"m": "matchers",
}
// Minimal required sections for a model to be valid
var requiredSections = []string{"r", "p", "e", "m"}
func loadAssertion(model Model, cfg config.ConfigInterface, sec string, key string) bool {
value := cfg.String(sectionNameMap[sec] + "::" + key)
return model.AddDef(sec, key, value)
}
// AddDef adds an assertion to the model.
func (model Model) AddDef(sec string, key string, value string) bool {
if value == "" {
return false
}
ast := Assertion{}
ast.Key = key
ast.Value = value
ast.PolicyMap = make(map[string]int)
ast.setLogger(model.GetLogger())
ast.initPriorityIndex()
if sec == "r" || sec == "p" {
ast.Tokens = strings.Split(ast.Value, ",")
for i := range ast.Tokens {
ast.Tokens[i] = key + "_" + strings.TrimSpace(ast.Tokens[i])
}
} else {
ast.Value = util.RemoveComments(util.EscapeAssertion(ast.Value))
}
_, ok := model[sec]
if !ok {
model[sec] = make(AssertionMap)
}
model[sec][key] = &ast
return true
}
func getKeySuffix(i int) string {
if i == 1 {
return ""
}
return strconv.Itoa(i)
}
func loadSection(model Model, cfg config.ConfigInterface, sec string) {
i := 1
for {
if !loadAssertion(model, cfg, sec, sec+getKeySuffix(i)) {
break
} else {
i++
}
}
}
// SetLogger sets the model's logger.
func (model Model) SetLogger(logger log.Logger) {
for _, astMap := range model {
for _, ast := range astMap {
ast.logger = logger
}
}
model["logger"] = AssertionMap{"logger": &Assertion{logger: logger}}
}
// GetLogger returns the model's logger.
func (model Model) GetLogger() log.Logger {
return model["logger"]["logger"].logger
}
// NewModel creates an empty model.
func NewModel() Model {
m := make(Model)
m.SetLogger(&log.DefaultLogger{})
return m
}
// NewModelFromFile creates a model from a .CONF file.
func NewModelFromFile(path string) (Model, error) {
m := NewModel()
err := m.LoadModel(path)
if err != nil {
return nil, err
}
return m, nil
}
// NewModelFromString creates a model from a string which contains model text.
func NewModelFromString(text string) (Model, error) {
m := NewModel()
err := m.LoadModelFromText(text)
if err != nil {
return nil, err
}
return m, nil
}
// LoadModel loads the model from model CONF file.
func (model Model) LoadModel(path string) error {
cfg, err := config.NewConfig(path)
if err != nil {
return err
}
return model.loadModelFromConfig(cfg)
}
// LoadModelFromText loads the model from the text.
func (model Model) LoadModelFromText(text string) error {
cfg, err := config.NewConfigFromText(text)
if err != nil {
return err
}
return model.loadModelFromConfig(cfg)
}
func (model Model) loadModelFromConfig(cfg config.ConfigInterface) error {
for s := range sectionNameMap {
loadSection(model, cfg, s)
}
ms := make([]string, 0)
for _, rs := range requiredSections {
if !model.hasSection(rs) {
ms = append(ms, sectionNameMap[rs])
}
}
if len(ms) > 0 {
return fmt.Errorf("missing required sections: %s", strings.Join(ms, ","))
}
return nil
}
func (model Model) hasSection(sec string) bool {
section := model[sec]
return section != nil
}
// PrintModel prints the model to the log.
func (model Model) PrintModel() {
if !model.GetLogger().IsEnabled() {
return
}
var modelInfo [][]string
for k, v := range model {
if k == "logger" {
continue
}
for i, j := range v {
modelInfo = append(modelInfo, []string{k, i, j.Value})
}
}
model.GetLogger().LogModel(modelInfo)
}
func (model Model) SortPoliciesBySubjectHierarchy() error {
if model["e"]["e"].Value != "subjectPriority(p_eft) || deny" {
return nil
}
subIndex := 0
domainIndex := -1
for ptype, assertion := range model["p"] {
for index, token := range assertion.Tokens {
if token == fmt.Sprintf("%s_dom", ptype) {
domainIndex = index
break
}
}
policies := assertion.Policy
subjectHierarchyMap, err := getSubjectHierarchyMap(model["g"]["g"].Policy)
if err != nil {
return err
}
sort.SliceStable(policies, func(i, j int) bool {
domain1, domain2 := defaultDomain, defaultDomain
if domainIndex != -1 {
domain1 = policies[i][domainIndex]
domain2 = policies[j][domainIndex]
}
name1, name2 := getNameWithDomain(domain1, policies[i][subIndex]), getNameWithDomain(domain2, policies[j][subIndex])
p1 := subjectHierarchyMap[name1]
p2 := subjectHierarchyMap[name2]
return p1 > p2
})
for i, policy := range assertion.Policy {
assertion.PolicyMap[strings.Join(policy, ",")] = i
}
}
return nil
}
func getSubjectHierarchyMap(policies [][]string) (map[string]int, error) {
subjectHierarchyMap := make(map[string]int)
// Tree structure of role
policyMap := make(map[string][]string)
for _, policy := range policies {
if len(policy) < 2 {
return nil, errors.New("policy g expect 2 more params")
}
domain := defaultDomain
if len(policy) != 2 {
domain = policy[2]
}
child := getNameWithDomain(domain, policy[0])
parent := getNameWithDomain(domain, policy[1])
policyMap[parent] = append(policyMap[parent], child)
if _, ok := subjectHierarchyMap[child]; !ok {
subjectHierarchyMap[child] = 0
}
if _, ok := subjectHierarchyMap[parent]; !ok {
subjectHierarchyMap[parent] = 0
}
subjectHierarchyMap[child] = 1
}
// Use queues for levelOrder
queue := list.New()
for k, v := range subjectHierarchyMap {
root := k
if v != 0 {
continue
}
lv := 0
queue.PushBack(root)
for queue.Len() != 0 {
sz := queue.Len()
for i := 0; i < sz; i++ {
node := queue.Front()
queue.Remove(node)
nodeValue := node.Value.(string)
subjectHierarchyMap[nodeValue] = lv
if _, ok := policyMap[nodeValue]; ok {
for _, child := range policyMap[nodeValue] {
queue.PushBack(child)
}
}
}
lv++
}
}
return subjectHierarchyMap, nil
}
func getNameWithDomain(domain string, name string) string {
return domain + defaultSeparator + name
}
func (model Model) SortPoliciesByPriority() error {
for ptype, assertion := range model["p"] {
for index, token := range assertion.Tokens {
if token == fmt.Sprintf("%s_priority", ptype) {
assertion.priorityIndex = index
break
}
}
if assertion.priorityIndex == -1 {
continue
}
policies := assertion.Policy
sort.SliceStable(policies, func(i, j int) bool {
p1, err := strconv.Atoi(policies[i][assertion.priorityIndex])
if err != nil {
return true
}
p2, err := strconv.Atoi(policies[j][assertion.priorityIndex])
if err != nil {
return true
}
return p1 < p2
})
for i, policy := range assertion.Policy {
assertion.PolicyMap[strings.Join(policy, ",")] = i
}
}
return nil
}
func (model Model) ToText() string {
tokenPatterns := make(map[string]string)
pPattern, rPattern := regexp.MustCompile("^p_"), regexp.MustCompile("^r_")
for _, ptype := range []string{"r", "p"} {
for _, token := range model[ptype][ptype].Tokens {
tokenPatterns[token] = rPattern.ReplaceAllString(pPattern.ReplaceAllString(token, "p."), "r.")
}
}
s := strings.Builder{}
writeString := func(sec string) {
for ptype := range model[sec] {
value := model[sec][ptype].Value
for tokenPattern, newToken := range tokenPatterns {
value = strings.Replace(value, tokenPattern, newToken, -1)
}
s.WriteString(fmt.Sprintf("%s = %s\n", sec, value))
}
}
s.WriteString("[request_definition]\n")
writeString("r")
s.WriteString("[policy_definition]\n")
writeString("p")
if _, ok := model["g"]; ok {
s.WriteString("[role_definition]\n")
for ptype := range model["g"] {
s.WriteString(fmt.Sprintf("%s = %s\n", ptype, model["g"][ptype].Value))
}
}
s.WriteString("[policy_effect]\n")
writeString("e")
s.WriteString("[matchers]\n")
writeString("m")
return s.String()
}
func (model Model) Copy() Model {
newModel := NewModel()
for sec, m := range model {
newAstMap := make(AssertionMap)
for ptype, ast := range m {
newAstMap[ptype] = ast.copy()
}
newModel[sec] = newAstMap
}
newModel.SetLogger(model.GetLogger())
return newModel
}