forked from apache/casbin-jcasbin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel.java
More file actions
527 lines (459 loc) · 16.8 KB
/
Copy pathModel.java
File metadata and controls
527 lines (459 loc) · 16.8 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
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
// 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 org.casbin.jcasbin.model;
import org.casbin.jcasbin.config.Config;
import org.casbin.jcasbin.log.*;
import org.casbin.jcasbin.util.Util;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.casbin.jcasbin.util.Util.splitCommaDelimited;
/**
* Model represents the whole access control model.
*/
public class Model extends Policy {
public static final Map<String, String> sectionNameMap;
static {
sectionNameMap = new HashMap<>();
sectionNameMap.put("r", "request_definition");
sectionNameMap.put("p", "policy_definition");
sectionNameMap.put("g", "role_definition");
sectionNameMap.put("e", "policy_effect");
sectionNameMap.put("m", "matchers");
}
public static final String[] requiredSections = {"r", "p", "e", "m"};
// used by CoreEnforcer to detect changes to Model
protected int modCount;
private int domainIndex = -1;
private String defaultDomain = "";
private String defaultSeparator = "::";
public Model() {
model = new HashMap<>();
}
public int getModCount() {
return modCount;
}
private boolean loadAssertion(Model model, Config cfg, String sec, String key) {
String value = cfg.getString(sectionNameMap.get(sec) + "::" + key);
return model.addDef(sec, key, value);
}
private static final Pattern paramsPattern = Pattern.compile("\\((.*?)\\)");
/**
* getParamsToken Get ParamsToken from Assertion.Value
*/
private static List<String> getParamsToken(String value) {
Matcher matcher = paramsPattern.matcher(value);
if (!matcher.find()) {
return null;
}
String paramsString = matcher.group(1);
if (paramsString == null || paramsString.isEmpty()) {
return null;
}
String[] paramsArray = paramsString.split(",");
List<String> paramsList = new ArrayList<>();
for (String param : paramsArray) {
paramsList.add(param.trim());
}
return paramsList;
}
/**
* addDef adds an assertion to the model.
*
* @param sec the section, "p" or "g".
* @param key the policy type, "p", "p2", .. or "g", "g2", ..
* @param value the policy rule, separated by ", ".
* @return succeeds or not.
*/
public boolean addDef(String sec, String key, String value) {
Assertion ast = new Assertion();
ast.key = key;
ast.value = value;
ast.initPriorityIndex();
if ("".equals(ast.value)) {
return false;
}
if ("r".equals(sec) || "p".equals(sec)) {
ast.tokens = splitCommaDelimited(ast.value);
for (int i = 0; i < ast.tokens.length; i++) {
ast.tokens[i] = key + "_" + ast.tokens[i];
if ("p_priority".equals(ast.tokens[i])) {
ast.priorityIndex = i;
}
}
} else if ("g".equals(sec)) {
if (getParamsToken(ast.value) != null){
ast.paramsTokens = getParamsToken(ast.value).toArray(new String[0]);
}
int paramsTokens_length = ast.paramsTokens==null?0:ast.paramsTokens.length;
String[] tokens_array = value.split(",");
List<String> tokens_list = Arrays.asList(tokens_array).subList(0, tokens_array.length - paramsTokens_length);
ast.tokens = tokens_list.toArray(new String[0]);
} else {
ast.value = Util.removeComments(Util.escapeAssertion(ast.value));
}
if (!model.containsKey(sec)) {
model.put(sec, new HashMap<>());
}
model.get(sec).put(key, ast);
modCount++;
return true;
}
private String getKeySuffix(int i) {
if (i == 1) {
return "";
}
return Integer.toString(i);
}
private void loadSection(Model model, Config cfg, String sec) {
int i = 1;
while (true) {
if (!loadAssertion(model, cfg, sec, sec + getKeySuffix(i))) {
break;
} else {
i++;
}
}
}
/**
* Helper function for loadModel and loadModelFromText
*
* @param cfg the configuration parser
*/
private void loadSections(Config cfg) {
loadSection(this, cfg, "r");
loadSection(this, cfg, "p");
loadSection(this, cfg, "e");
loadSection(this, cfg, "m");
loadSection(this, cfg, "g");
}
/**
* SetLogger sets the model's logger.
*
* @param logger the logger to be set for the model.
*/
public void setLogger(Logger logger) {
for (Map<String, Assertion> astMap : model.values()) {
for (Assertion ast : astMap.values()) {
ast.setLogger(logger);
}
}
model.put("logger", Collections.singletonMap("logger", new Assertion(logger)));
}
/**
* NewModel creates an empty model.
*
* @return a new instance of the Model.
*/
public static Model newModel() {
Model model = new Model();
model.setLogger(new DefaultLogger());
return model;
}
/**
* NewModelFromString creates a model from a string which contains model text.
*
* @param path the path of the model file.
* @return the model loaded from file.
*/
public static Model newModelFromFile(String path) {
Model model = new Model();
model.loadModel(path);
return model;
}
/**
* NewModelFromString creates a model from a string which contains model text.
*
* @param text the path of the file.
* @return the model loaded from text.
*/
public static Model newModelFromString(String text) {
Model model = new Model();
model.loadModelFromText(text);
return model;
}
/**
* loadModel loads the model from model CONF file.
*
* @param path the path of the model file.
*/
public void loadModel(String path) {
Config cfg = Config.newConfig(path);
loadSections(cfg);
}
/**
* loadModelFromText loads the model from the text.
*
* @param text the model text.
*/
public void loadModelFromText(String text) {
Config cfg = Config.newConfigFromText(text);
loadSections(cfg);
}
/**
* loadModelFromConfig loads the model from the configuration.
*
* @param cfg the model text.
*/
public void loadModelFromConfig(Config cfg) {
for (String s : sectionNameMap.keySet()) {
loadSection(this, cfg, s);
}
List<String> ms = new ArrayList<>();
for (String rs : requiredSections) {
if (!hasSection(rs)) {
ms.add(sectionNameMap.get(rs));
}
}
if (!ms.isEmpty()) {
throw new RuntimeException("missing required sections: " + String.join(",", ms));
}
}
/**
* hasSection checks if the section exists in the model.
*
* @param sec the section name to check, such as "p" or "g".
* @return whether the section exists in the model.
*/
public boolean hasSection(String sec) {
Map<String, Assertion> section = model.get(sec);
return section != null;
}
/**
* saveSectionToText saves the section to the text.
*
* @return the section text.
*/
private String saveSectionToText(String sec) {
StringBuilder res = new StringBuilder("[" + sectionNameMap.get(sec) + "]\n");
Map<String, Assertion> section = model.get(sec);
if (section == null) {
return "";
}
for (Map.Entry<String, Assertion> entry : section.entrySet()) {
res.append(String.format("%s = %s\n", entry.getKey(), entry.getValue().value.replace("_", ".")));
}
return res.toString();
}
/**
* saveModelToText saves the model to the text.
*
* @return the model text.
*/
public String saveModelToText() {
StringBuilder res = new StringBuilder();
res.append(saveSectionToText("r"));
res.append("\n");
res.append(saveSectionToText("p"));
res.append("\n");
String g = saveSectionToText("g");
g = g.replace(".", "_");
res.append(g);
if (!"".equals(g)) {
res.append("\n");
}
res.append(saveSectionToText("e"));
res.append("\n");
res.append(saveSectionToText("m"));
return res.toString();
}
/**
* printModel prints the model to the log.
*/
public void printModel() {
if (!Util.isLogPrintEnabled()) {
return;
}
Util.logPrint("Model:");
for (Map.Entry<String, Map<String, Assertion>> entry : model.entrySet()) {
for (Map.Entry<String, Assertion> entry2 : entry.getValue().entrySet()) {
Util.logPrintfInfo("{}.{}: {}", entry.getKey(), entry2.getKey(), entry2.getValue().value);
}
}
}
/**
* sort policies by priority value
*/
public void sortPoliciesByPriority() {
if (!model.containsKey("p")) {
return;
}
for (Map.Entry<String, Assertion> entry : model.get("p").entrySet()) {
Assertion assertion = entry.getValue();
int priorityIndex = assertion.priorityIndex;
if (priorityIndex < 0) {
continue;
}
assertion.policy.sort(Comparator.comparingInt(p -> Integer.parseInt(p.get(priorityIndex))));
for (int i = 0; i < assertion.policy.size(); ++i) {
assertion.policyIndex.put(assertion.policy.get(i).toString(), i);
}
}
}
/**
* sort policies by hieraichy map
*/
public void sortPoliciesBySubjectHieraichy() {
if (model.get("e") == null || (!"subjectPriority(p_eft) || deny".equals(model.get("e").get("e").value))) {
return;
}
for (Map.Entry<String, Assertion> entry : model.get("p").entrySet()) {
Map<String, Integer> subjectHierarchyMap = getSubjectHierarchyMap(model.get("g").get("g").policy);
Assertion assertion = entry.getValue();
domainIndex = -1;
for(int i=0; i<assertion.tokens.length; i++){
if(assertion.tokens[i].equals(assertion.key+"_dom")){
domainIndex = i;
break;
}
}
Collections.sort(assertion.policy, (o1, o2)->{
String domain1 = domainIndex!=-1 ? o1.get(domainIndex) : defaultDomain;
String domain2 = domainIndex!=-1 ? o2.get(domainIndex) : defaultDomain;
int priority1 = subjectHierarchyMap.get(getNameWithDomain(domain1, o1.get(0)));
int priority2 = subjectHierarchyMap.get(getNameWithDomain(domain2, o2.get(0)));
return priority2-priority1;
});
}
}
public Map<String, Integer> getSubjectHierarchyMap(List<List<String>> policies) {
Map<String, Integer> subjectHierarchyMap = new HashMap<>();
Map<String, String> policyMap = new HashMap<>();
String domain = defaultDomain;
for(List<String> policy:policies) {
if(policy.size()!=2) {
domain = policy.get(2);
}
String child = getNameWithDomain(domain, policy.get(0));
String parent = getNameWithDomain(domain, policy.get(1));
policyMap.put(child, parent);
if(!subjectHierarchyMap.containsKey(child)) {
subjectHierarchyMap.put(child, 0);
}
if(!subjectHierarchyMap.containsKey(parent)) {
subjectHierarchyMap.put(parent, 0);
}
subjectHierarchyMap.replace(child, 1);
}
List<String> set = new ArrayList<>();
for (String key : subjectHierarchyMap.keySet()) {
if (subjectHierarchyMap.get(key) != 0) set.add(key);
}
while (!set.isEmpty()){
String child = set.get(0);
findHierarchy(policyMap, subjectHierarchyMap, set, child);
}
return subjectHierarchyMap;
}
private void findHierarchy(Map<String, String> policyMap, Map<String, Integer> subjectHierarchyMap, List<String> set, String child) {
set.remove(child);
String parent = policyMap.get(child);
if (set.contains(parent)) {
findHierarchy(policyMap, subjectHierarchyMap, set, parent);
}
subjectHierarchyMap.replace(child, subjectHierarchyMap.get(parent)+10);
}
public String getNameWithDomain(String domain, String name) {
return domain + defaultSeparator + name;
}
public enum PolicyOperations {
POLICY_ADD,
POLICY_REMOVE
}
public String toText() {
Map<String, String> tokenPatterns = new HashMap<>();
Pattern pPattern = Pattern.compile("^p_");
Pattern rPattern = Pattern.compile("^r_");
for (String ptype : new String[]{"r", "p"}) {
for (String token : model.get(ptype).get(ptype).tokens) {
String newToken = rPattern.matcher(pPattern.matcher(token).replaceAll("p.")).replaceAll("r.");
tokenPatterns.put(token, newToken);
}
}
if (model.get("e").get("e").value.contains("p_eft")) {
tokenPatterns.put("p_eft", "p.eft");
}
StringBuilder s = new StringBuilder();
writeString(s, "r", tokenPatterns);
writeString(s, "p", tokenPatterns);
if (model.containsKey("g")) {
s.append("[role_definition]\n");
for (String ptype : model.get("g").keySet()) {
s.append(String.format("%s = %s\n", ptype, model.get("g").get(ptype).value));
}
}
writeString(s, "e", tokenPatterns);
writeString(s, "m", tokenPatterns);
return s.toString();
}
private void writeString(StringBuilder s, String sec, Map<String, String> tokenPatterns) {
s.append(String.format("[%s]\n", sectionNameMap.get(sec)));
for (String ptype : model.get(sec).keySet()) {
String value = model.get(sec).get(ptype).value;
for (Map.Entry<String, String> entry : tokenPatterns.entrySet()) {
value = value.replace(entry.getKey(), entry.getValue());
}
s.append(String.format("%s = %s\n", sec, value));
}
}
/**
* getValuesForFieldInPolicyAllTypes gets all values for a field for all rules
* across all policy types in a section. Duplicated values are removed.
*
* @param sec the section, "p" or "g".
* @param fieldIndex the policy rule's index.
* @return all field values across all ptypes.
*/
public List<String> getValuesForFieldInPolicyAllTypes(String sec, int fieldIndex) {
List<String> values = new ArrayList<>();
Map<String, Assertion> section = model.get(sec);
if (section == null) {
return values;
}
for (Assertion assertion : section.values()) {
for (List<String> rule : assertion.policy) {
if (fieldIndex < rule.size()) {
values.add(rule.get(fieldIndex));
}
}
}
return Util.arrayRemoveDuplicates(values);
}
/**
* getFieldIndex returns the index of a field in a policy type.
* For example, given ptype="p" and field="sub", returns the index
* where "p_sub" appears in the tokens array.
*
* @param ptype the policy type, e.g., "p", "p2"
* @param field the field name, e.g., "sub", "obj", "act"
* @return the index of the field in the policy rule, or -1 if not found
*/
public int getFieldIndex(String ptype, String field) {
String pattern = ptype + "_" + field;
Map<String, Assertion> pSection = model.get("p");
if (pSection == null) {
return -1;
}
Assertion ast = pSection.get(ptype);
if (ast == null || ast.tokens == null) {
return -1;
}
for (int i = 0; i < ast.tokens.length; i++) {
if (pattern.equals(ast.tokens[i])) {
return i;
}
}
return -1;
}
}