-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathmodel.ts
480 lines (404 loc) · 12.6 KB
/
model.ts
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
// Copyright 2018 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.
import * as rbac from '../rbac';
import * as util from '../util';
import { Config, ConfigInterface } from '../config';
import { Assertion } from './assertion';
import { getLogger, logPrint } from '../log';
import { RoleManager } from '../rbac';
export const sectionNameMap: { [index: string]: string } = {
r: 'request_definition',
p: 'policy_definition',
g: 'role_definition',
e: 'policy_effect',
m: 'matchers',
};
export enum PolicyOp {
PolicyAdd,
PolicyRemove,
}
export const requiredSections = ['r', 'p', 'e', 'm'];
export class Model {
// Model represents the whole access control model.
// Mest-map is the collection of assertions, can be "r", "p", "g", "e", "m".
public model: Map<string, Map<string, Assertion>>;
public synced = false;
/**
* constructor is the constructor for Model.
*/
constructor() {
this.model = new Map<string, Map<string, Assertion>>();
}
private loadAssertion(cfg: ConfigInterface, sec: string, key: string): boolean {
const secName = sectionNameMap[sec];
const value = cfg.getString(`${secName}::${key}`);
return this.addDef(sec, key, value);
}
private static getKeySuffix(i: number): string {
if (i === 1) {
return '';
}
return i.toString();
}
private loadSection(cfg: ConfigInterface, sec: string): void {
let i = 1;
for (;;) {
if (!this.loadAssertion(cfg, sec, sec + Model.getKeySuffix(i))) {
break;
} else {
i++;
}
}
}
// addDef adds an assertion to the model.
public addDef(sec: string, key: string, value: string): boolean {
if (value === '') {
return false;
}
const ast = new Assertion(this.synced);
ast.key = key;
ast.value = value;
if (sec === 'r' || sec === 'p') {
const tokens = value.split(',').map((n) => n.trim());
for (let i = 0; i < tokens.length; i++) {
tokens[i] = key + '_' + tokens[i];
}
ast.tokens = tokens;
} else if (sec === 'm') {
const stringArguments = value.match(/\"(.*?)\"/g) || [];
stringArguments.forEach((n, index) => {
value = value.replace(n, `$<${index}>`);
});
value = util.escapeAssertion(value);
stringArguments.forEach((n, index) => {
value = value.replace(`$<${index}>`, n);
});
ast.value = value;
} else {
ast.value = util.escapeAssertion(value);
}
const nodeMap = this.model.get(sec);
if (nodeMap) {
nodeMap.set(key, ast);
} else {
const assertionMap = new Map<string, Assertion>();
assertionMap.set(key, ast);
this.model.set(sec, assertionMap);
}
return true;
}
// loadModel loads the model from model CONF string.
public loadModel(string: string): void {
const cfg = Config.newConfig(string);
this.loadModelFromConfig(cfg);
}
// loadModelFromText loads the model from the text.
public loadModelFromText(text: string): void {
const cfg = Config.newConfigFromText(text);
this.loadModelFromConfig(cfg);
}
public loadModelFromConfig(cfg: ConfigInterface): void {
for (const s in sectionNameMap) {
this.loadSection(cfg, s);
}
const ms: string[] = [];
requiredSections.forEach((n) => {
if (!this.hasSection(n)) {
ms.push(sectionNameMap[n]);
}
});
if (ms.length > 0) {
throw new Error(`missing required sections: ${ms.join(',')}`);
}
}
private hasSection(sec: string): boolean {
return this.model.get(sec) !== undefined;
}
// printModel prints the model to the log.
public printModel(): void {
logPrint('Model:');
this.model.forEach((value, key) => {
value.forEach((ast, astKey) => {
logPrint(`${key}.${astKey}: ${ast.value}`);
});
});
}
// buildIncrementalRoleLinks provides incremental build the role inheritance relations.
public async buildIncrementalRoleLinks(rm: rbac.RoleManager, op: PolicyOp, sec: string, ptype: string, rules: string[][]): Promise<void> {
if (sec === 'g') {
await this.model.get(sec)?.get(ptype)?.buildIncrementalRoleLinks(rm, op, rules);
}
}
// buildRoleLinks initializes the roles in RBAC.
public async buildRoleLinks(rmMap: Map<string, RoleManager>): Promise<void> {
const astMap = this.model.get('g');
if (!astMap) {
return;
}
for (const key of astMap.keys()) {
const ast = astMap.get(key);
const rm = rmMap.get(key);
if (!rm) {
throw new Error("Role manager didn't exist.");
}
await ast?.buildRoleLinks(rm);
}
}
// clearPolicy clears all current policy.
public clearPolicy(): void {
this.model.forEach((value, key) => {
if (key === 'p' || key === 'g') {
value.forEach((ast) => {
ast.policy = [];
});
}
});
}
// getPolicy gets all rules in a policy.
public getPolicy(sec: string, key: string): string[][] {
const policy: string[][] = [];
const ast = this.model.get(sec)?.get(key);
if (ast) {
policy.push(...ast.policy);
}
return policy;
}
// hasPolicy determines whether a model has the specified policy rule.
public hasPolicy(sec: string, key: string, rule: string[]): boolean {
const ast = this.model.get(sec)?.get(key);
if (!ast) {
return false;
}
return ast.policy.some((n: string[]) => util.arrayEquals(n, rule));
}
// addPolicy adds a policy rule to the model.
public addPolicy(sec: string, key: string, rule: string[]): boolean {
if (!this.hasPolicy(sec, key, rule)) {
const ast = this.model.get(sec)?.get(key);
if (!ast) {
return false;
}
const policy = ast.policy;
const tokens = ast.tokens;
const priorityIndex = tokens.indexOf('p_priority');
if (priorityIndex !== -1) {
const priorityRule = rule[priorityIndex];
const insertIndex = policy.findIndex((oneRule) => oneRule[priorityIndex] >= priorityRule);
if (priorityIndex === -1) {
policy.push(rule);
} else {
policy.splice(insertIndex, 0, rule);
}
} else {
policy.push(rule);
}
return true;
}
return false;
}
// addPolicies adds policy rules to the model.
public addPolicies(sec: string, ptype: string, rules: string[][]): [boolean, string[][]] {
const ast = this.model.get(sec)?.get(ptype);
if (!ast) {
return [false, []];
}
for (const rule of rules) {
if (this.hasPolicy(sec, ptype, rule)) {
return [false, []];
}
}
const priorityFlag = ast.tokens.indexOf('p_priority') !== -1;
if (priorityFlag) {
rules.forEach((rule) => {
this.addPolicy(sec, ptype, rule);
});
} else {
ast.policy = ast.policy.concat(rules);
}
return [true, rules];
}
// updatePolicy updates a policy from the model
public updatePolicy(sec: string, ptype: string, oldRule: string[], newRule: string[]): boolean {
const ast = this.model.get(sec)?.get(ptype);
if (!ast) {
return false;
}
const index = ast.policy.findIndex((r) => util.arrayEquals(r, oldRule));
if (index === -1) {
return false;
}
const priorityIndex = ast.tokens.indexOf('p_priority');
if (priorityIndex !== -1) {
if (oldRule[priorityIndex] === newRule[priorityIndex]) {
ast.policy[index] = newRule;
} else {
// this.removePolicy(sec, ptype, oldRule);
// this.addPolicy(sec, ptype, newRule);
throw new Error('new rule should have the same priority with old rule.');
}
} else {
ast.policy[index] = newRule;
}
return true;
}
// removePolicy removes a policy rule from the model.
public removePolicy(sec: string, key: string, rule: string[]): boolean {
if (this.hasPolicy(sec, key, rule)) {
const ast = this.model.get(sec)?.get(key);
if (!ast) {
return false;
}
ast.policy = ast.policy.filter((r) => !util.arrayEquals(rule, r));
return true;
}
return false;
}
// removePolicies removes policy rules from the model.
public removePolicies(sec: string, ptype: string, rules: string[][]): [boolean, string[][]] {
const effects: string[][] = [];
const ast = this.model.get(sec)?.get(ptype);
if (!ast) {
return [false, []];
}
for (const rule of rules) {
if (!this.hasPolicy(sec, ptype, rule)) {
return [false, []];
}
}
for (const rule of rules) {
ast.policy = ast.policy.filter((r: string[]) => {
const equals = util.arrayEquals(rule, r);
if (equals) {
effects.push(r);
}
return !equals;
});
}
return [true, effects];
}
// getFilteredPolicy gets rules based on field filters from a policy.
public getFilteredPolicy(sec: string, key: string, fieldIndex: number, ...fieldValues: string[]): string[][] {
const res: string[][] = [];
const ast = this.model.get(sec)?.get(key);
if (!ast) {
return res;
}
for (const rule of ast.policy) {
let matched = true;
for (let i = 0; i < fieldValues.length; i++) {
const fieldValue = fieldValues[i];
if (fieldValue !== '' && rule[fieldIndex + i] !== fieldValue) {
matched = false;
break;
}
}
if (matched) {
res.push(rule);
}
}
return res;
}
// removeFilteredPolicy removes policy rules based on field filters from the model.
public removeFilteredPolicy(sec: string, key: string, fieldIndex: number, ...fieldValues: string[]): [boolean, string[][]] {
const res = [];
const effects: string[][] = [];
let bool = false;
if (fieldValues.length === 0) {
return [false, effects];
}
const ast = this.model.get(sec)?.get(key);
if (!ast) {
return [false, []];
}
for (const rule of ast.policy) {
let matched = true;
for (let i = 0; i < fieldValues.length; i++) {
const fieldValue = fieldValues[i];
if (fieldValue !== '' && rule[fieldIndex + i] !== fieldValue) {
matched = false;
break;
}
}
if (matched) {
bool = true;
effects.push(rule);
} else {
res.push(rule);
}
}
if (effects.length !== 0) {
ast.policy = res;
}
return [bool, effects];
}
// getValuesForFieldInPolicy gets all values for a field for all rules in a policy, duplicated values are removed.
public getValuesForFieldInPolicy(sec: string, key: string, fieldIndex: number): string[] {
const values: string[] = [];
const ast = this.model.get(sec)?.get(key);
if (!ast) {
return values;
}
return util.arrayRemoveDuplicates(ast.policy.map((n: string[]) => n[fieldIndex]));
}
// getValuesForFieldInPolicyAllTypes gets all values for a field for all rules in a policy of all ptypes, duplicated values are removed.
public getValuesForFieldInPolicyAllTypes(sec: string, fieldIndex: number): string[] {
const values: string[] = [];
const ast = this.model.get(sec);
if (!ast) {
return values;
}
for (const ptype of ast.keys()) {
values.push(...this.getValuesForFieldInPolicy(sec, ptype, fieldIndex));
}
return util.arrayRemoveDuplicates(values);
}
// printPolicy prints the policy to log.
public printPolicy(): void {
if (!getLogger().isEnable()) {
return;
}
logPrint('Policy:');
this.model.forEach((map, key) => {
if (key === 'p' || key === 'g') {
map.forEach((ast) => {
logPrint(`key, : ${ast.value}, : , ${ast.policy}`);
});
}
});
}
}
/**
* newModel creates a model.
*/
export function newModel(...text: string[]): Model {
const m = new Model();
if (text.length === 2) {
if (text[0] !== '') {
m.loadModel(text[0]);
}
} else if (text.length === 1) {
m.loadModelFromText(text[0]);
} else if (text.length !== 0) {
throw new Error('Invalid parameters for model.');
}
return m;
}
/**
* newModelFromString creates a model from a string which contains model text.
*/
export function newModelFromString(text: string): Model {
const m = new Model();
m.loadModelFromText(text);
return m;
}