-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathcoreEnforcer.ts
639 lines (554 loc) · 18.6 KB
/
coreEnforcer.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
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// 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 { compile, compileAsync, addBinaryOp } from 'expression-eval';
import { DefaultEffector, Effect, Effector } from './effect';
import { FunctionMap, Model, newModel, PolicyOp } from './model';
import { Adapter, FilteredAdapter, Watcher } from './persist';
import { DefaultRoleManager, RoleManager } from './rbac';
import { EnforceContext } from './enforceContext';
import {
escapeAssertion,
generateGFunction,
getEvalValue,
hasEval,
replaceEval,
generatorRunSync,
generatorRunAsync,
generateSyncGFunction,
isRoleManagerSync,
customIn,
bracketCompatible,
} from './util';
import { getLogger, logPrint } from './log';
import { MatchingFunc } from './rbac';
type Matcher = ((context: any) => Promise<any>) | ((context: any) => any);
type EnforceResult = Generator<(boolean | [boolean, string[]]) | Promise<boolean | [boolean, string[]]>>;
/**
* CoreEnforcer defines the core functionality of an enforcer.
*/
export class CoreEnforcer {
protected modelPath: string;
protected model: Model;
protected fm: FunctionMap = FunctionMap.loadFunctionMap();
protected eft: Effector = new DefaultEffector();
private matcherMap: Map<string, Matcher> = new Map();
private defaultEnforceContext: EnforceContext = new EnforceContext('r', 'p', 'e', 'm');
protected adapter: Adapter;
protected watcher: Watcher | null = null;
protected rmMap: Map<string, RoleManager>;
protected enabled = true;
protected autoSave = true;
protected autoBuildRoleLinks = true;
protected autoNotifyWatcher = true;
private getExpression(asyncCompile: boolean, exp: string): Matcher {
const matcherKey = `${asyncCompile ? 'ASYNC[' : 'SYNC['}${exp}]`;
addBinaryOp('in', 1, customIn);
let expression = this.matcherMap.get(matcherKey);
if (!expression) {
exp = bracketCompatible(exp);
expression = asyncCompile ? compileAsync(exp) : compile(exp);
this.matcherMap.set(matcherKey, expression);
}
return expression;
}
/**
* loadModel reloads the model from the model CONF string.
* Because the policy is attached to a model,
* so the policy is invalidated and needs to be reloaded by calling LoadPolicy().
*/
public loadModel(): void {
this.model = newModel();
this.model.synced = false;
this.model.loadModel(this.modelPath);
this.model.printModel();
}
/**
* get a new RoleManager based on the type of current Enforcer
*/
public newRoleManager(): RoleManager {
return new DefaultRoleManager(10);
}
/**
* getModel gets the current model.
*
* @return the model of the enforcer.
*/
public getModel(): Model {
return this.model;
}
/**
* setModel sets the current model.
*
* @param m the model.
*/
public setModel(m: Model): void {
this.model = m;
}
/**
* getAdapter gets the current adapter.
*
* @return the adapter of the enforcer.
*/
public getAdapter(): Adapter {
return this.adapter;
}
/**
* setAdapter sets the current adapter.
*
* @param adapter the adapter.
*/
public setAdapter(adapter: Adapter): void {
this.adapter = adapter;
}
/**
* setWatcher sets the current watcher.
*
* @param watcher the watcher.
*/
public setWatcher(watcher: Watcher): void {
this.watcher = watcher;
watcher.setUpdateCallback(async () => await this.loadPolicy());
}
/**
* setRoleManager sets the current role manager.
*
* @param rm the role manager.
*/
public setRoleManager(rm: RoleManager): void {
this.rmMap.set('g', rm);
}
/**
* setRoleManager sets the current role manager.
*
* @param name
* @param rm the role manager.
*/
public setNamedRoleManager(name: string, rm: RoleManager): void {
this.rmMap.set(name, rm);
}
/**
* getRoleManager gets the current role manager.
*/
public getRoleManager(): RoleManager | undefined {
return this.rmMap.get('g');
}
/**
* getNamedRoleManager gets role manager by name.
*/
public getNamedRoleManager(name: string): RoleManager | undefined {
return this.rmMap.get(name);
}
/**
* setEffector sets the current effector.
*
* @param eft the effector.
*/
public setEffector(eft: Effector): void {
this.eft = eft;
}
/**
* clearPolicy clears all policy.
*/
public clearPolicy(): void {
this.model.clearPolicy();
}
public initRmMap(): void {
this.rmMap = new Map<string, RoleManager>();
const rm = this.model.model.get('g');
if (rm) {
for (const ptype of rm.keys()) {
this.rmMap.set(ptype, this.newRoleManager());
}
}
}
public sortPolicies(): void {
const policy = this.model.model.get('p')?.get('p')?.policy;
const tokens = this.model.model.get('p')?.get('p')?.tokens;
if (policy && tokens) {
const priorityIndex = tokens.indexOf('p_priority');
if (priorityIndex !== -1) {
policy.sort((a, b) => {
return parseInt(a[priorityIndex], 10) - parseInt(b[priorityIndex], 10);
});
}
}
}
/**
* loadPolicy reloads the policy from adapter.
*/
public async loadPolicy(): Promise<void> {
this.model.clearPolicy();
await this.adapter.loadPolicy(this.model);
this.sortPolicies();
this.initRmMap();
if (this.autoBuildRoleLinks) {
await this.buildRoleLinksInternal();
}
}
/**
* loadFilteredPolicy reloads a filtered policy from adapter.
*
* @param filter the filter used to specify which type of policy should be loaded.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
public async loadFilteredPolicy(filter: any): Promise<boolean> {
this.model.clearPolicy();
return this.loadIncrementalFilteredPolicy(filter);
}
/**
* LoadIncrementalFilteredPolicy append a filtered policy from adapter.
*
* @param filter the filter used to specify which type of policy should be appended.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
public async loadIncrementalFilteredPolicy(filter: any): Promise<boolean> {
if ('isFiltered' in this.adapter) {
await (this.adapter as FilteredAdapter).loadFilteredPolicy(this.model, filter);
} else {
throw new Error('filtered policies are not supported by this adapter');
}
this.sortPolicies();
this.initRmMap();
if (this.autoBuildRoleLinks) {
await this.buildRoleLinksInternal();
}
return true;
}
/**
* isFiltered returns true if the loaded policy has been filtered.
*
* @return if the loaded policy has been filtered.
*/
public isFiltered(): boolean {
if ('isFiltered' in this.adapter) {
return (this.adapter as FilteredAdapter).isFiltered();
}
return false;
}
/**
* savePolicy saves the current policy (usually after changed with
* Casbin API) back to adapter.
*/
public async savePolicy(): Promise<boolean> {
if (this.isFiltered()) {
throw new Error('Cannot save a filtered policy');
}
const flag = await this.adapter.savePolicy(this.model);
if (!flag) {
return false;
}
if (this.watcher) {
return await this.watcher.update();
}
return true;
}
/**
* enableEnforce changes the enforcing state of Casbin, when Casbin is
* disabled, all access will be allowed by the enforce() function.
*
* @param enable whether to enable the enforcer.
*/
public enableEnforce(enable: boolean): void {
this.enabled = enable;
}
/**
* enableLog changes whether to print Casbin log to the standard output.
*
* @param enable whether to enable Casbin's log.
*/
public enableLog(enable: boolean): void {
getLogger().enableLog(enable);
}
/**
* enableAutoSave controls whether to save a policy rule automatically to
* the adapter when it is added or removed.
*
* @param autoSave whether to enable the AutoSave feature.
*/
public enableAutoSave(autoSave: boolean): void {
this.autoSave = autoSave;
}
/**
* enableAutoNotifyWatcher controls whether to save a policy rule automatically notify the Watcher when it is added or removed.
* @param enable whether to enable the AutoNotifyWatcher feature.
*/
public enableAutoNotifyWatcher(enable: boolean): void {
this.autoNotifyWatcher = enable;
}
/**
* enableAutoBuildRoleLinks controls whether to save a policy rule
* automatically to the adapter when it is added or removed.
*
* @param autoBuildRoleLinks whether to automatically build the role links.
*/
public enableAutoBuildRoleLinks(autoBuildRoleLinks: boolean): void {
this.autoBuildRoleLinks = autoBuildRoleLinks;
}
/**
* add matching function to RoleManager by ptype
* @param ptype g
* @param fn the function will be added
*/
public async addNamedMatchingFunc(ptype: string, fn: MatchingFunc): Promise<void> {
const rm = this.rmMap.get(ptype);
if (rm) {
return await (<DefaultRoleManager>rm).addMatchingFunc(fn);
}
throw Error('Target ptype not found.');
}
/**
* add domain matching function to RoleManager by ptype
* @param ptype g
* @param fn the function will be added
*/
public async addNamedDomainMatchingFunc(ptype: string, fn: MatchingFunc): Promise<void> {
const rm = this.rmMap.get(ptype);
if (rm) {
return await (<DefaultRoleManager>rm).addDomainMatchingFunc(fn);
}
}
/**
* buildRoleLinks manually rebuild the role inheritance relations.
*/
public async buildRoleLinks(): Promise<void> {
return this.buildRoleLinksInternal();
}
/**
* buildIncrementalRoleLinks provides incremental build the role inheritance relations.
* @param op policy operation
* @param ptype g
* @param rules policies
*/
public async buildIncrementalRoleLinks(op: PolicyOp, ptype: string, rules: string[][]): Promise<void> {
let rm = this.rmMap.get(ptype);
if (!rm) {
rm = this.newRoleManager();
this.rmMap.set(ptype, rm);
}
await this.model.buildIncrementalRoleLinks(rm, op, 'g', ptype, rules);
}
protected async buildRoleLinksInternal(): Promise<void> {
for (const rm of this.rmMap.values()) {
await rm.clear();
await this.model.buildRoleLinks(this.rmMap);
}
}
private *privateEnforce(
asyncCompile = true,
explain = false,
enforceContext: EnforceContext = new EnforceContext('r', 'p', 'e', 'm'),
...rvals: any[]
): EnforceResult {
if (!this.enabled) {
return true;
}
let explainIndex = -1;
const functions: { [key: string]: any } = {};
this.fm.getFunctions().forEach((value: any, key: string) => {
functions[key] = value;
});
const astMap = this.model.model.get('g');
astMap?.forEach((value, key) => {
const rm = value.rm;
functions[key] = isRoleManagerSync(rm) ? generateSyncGFunction(rm) : generateGFunction(rm);
});
const expString = this.model.model.get('m')?.get(enforceContext.mType)?.value;
if (!expString) {
throw new Error('Unable to find matchers in model');
}
const effectExpr = this.model.model.get('e')?.get(enforceContext.eType)?.value;
if (!effectExpr) {
throw new Error('Unable to find policy_effect in model');
}
const HasEval: boolean = hasEval(expString);
let expression: Matcher | undefined = undefined;
const p = this.model.model.get('p')?.get(enforceContext.pType);
const policyLen = p?.policy?.length;
const rTokens = this.model.model.get('r')?.get(enforceContext.rType)?.tokens;
const rTokensLen = rTokens?.length;
const effectStream = this.eft.newStream(effectExpr);
if (policyLen && policyLen !== 0) {
for (let i = 0; i < policyLen; i++) {
const parameters: { [key: string]: any } = {};
if (rTokens?.length !== rvals.length) {
throw new Error(`invalid request size: expected ${rTokensLen}, got ${rvals.length}, rvals: ${rvals}"`);
}
rTokens.forEach((token, j) => {
parameters[token] = rvals[j];
});
p?.tokens.forEach((token, j) => {
parameters[token] = p?.policy[i][j];
});
if (HasEval) {
const ruleNames: string[] = getEvalValue(expString);
let expWithRule = expString;
for (const ruleName of ruleNames) {
if (ruleName in parameters) {
const rule = escapeAssertion(parameters[ruleName]);
expWithRule = replaceEval(expWithRule, ruleName, rule);
} else {
throw new Error(`${ruleName} not in ${parameters}`);
}
}
expression = this.getExpression(asyncCompile, expWithRule);
} else {
if (expression === undefined) {
expression = this.getExpression(asyncCompile, expString);
}
}
const context = { ...parameters, ...functions };
const result = asyncCompile ? yield expression(context) : expression(context);
let eftRes: Effect;
switch (typeof result) {
case 'boolean':
eftRes = result ? Effect.Allow : Effect.Indeterminate;
break;
case 'number':
if (result === 0) {
eftRes = Effect.Indeterminate;
} else {
eftRes = result;
}
break;
default:
throw new Error('matcher result should be boolean or number');
}
const eft = parameters['p_eft'];
if (eft && eftRes === Effect.Allow) {
if (eft === 'allow') {
eftRes = Effect.Allow;
} else if (eft === 'deny') {
eftRes = Effect.Deny;
} else {
eftRes = Effect.Indeterminate;
}
}
const [res, done] = effectStream.pushEffect(eftRes);
if (done) {
explainIndex = i;
break;
}
}
} else {
explainIndex = 0;
const parameters: { [key: string]: any } = {};
rTokens?.forEach((token, j): void => {
parameters[token] = rvals[j];
});
p?.tokens?.forEach((token) => {
parameters[token] = '';
});
expression = this.getExpression(asyncCompile, expString);
const context = { ...parameters, ...functions };
const result = asyncCompile ? yield expression(context) : expression(context);
if (result) {
effectStream.pushEffect(Effect.Allow);
} else {
effectStream.pushEffect(Effect.Indeterminate);
}
}
const res = effectStream.current();
// only generate the request --> result string if the message
// is going to be logged.
if (getLogger().isEnable()) {
let reqStr = 'Request: ';
for (let i = 0; i < rvals.length; i++) {
if (i !== rvals.length - 1) {
reqStr += `${rvals[i]}, `;
} else {
reqStr += rvals[i];
}
}
reqStr += ` ---> ${res}`;
logPrint(reqStr);
}
if (explain) {
if (explainIndex === -1) {
return [res, []];
}
return [res, p?.policy[explainIndex]];
}
return res;
}
/**
* If the matchers does not contain an asynchronous method, call it faster.
*
* enforceSync decides whether a "subject" can access a "object" with
* the operation "action", input parameters are usually: (sub, obj, act).
*
* @param rvals the request needs to be mediated, usually an array
* of strings, can be class instances if ABAC is used.
* @return whether to allow the request.
*/
public enforceSync(...rvals: any[]): boolean {
if (rvals[0] instanceof EnforceContext) {
const enforceContext: EnforceContext = rvals.shift();
return generatorRunSync(this.privateEnforce(false, false, enforceContext, ...rvals));
}
return generatorRunSync(this.privateEnforce(false, false, this.defaultEnforceContext, ...rvals));
}
/**
* If the matchers does not contain an asynchronous method, call it faster.
*
* enforceSync decides whether a "subject" can access a "object" with
* the operation "action", input parameters are usually: (sub, obj, act).
*
* @param rvals the request needs to be mediated, usually an array
* of strings, can be class instances if ABAC is used.
* @return whether to allow the request and the reason rule.
*/
public enforceExSync(...rvals: any[]): [boolean, string[]] {
if (rvals[0] instanceof EnforceContext) {
const enforceContext: EnforceContext = rvals.shift();
return generatorRunSync(this.privateEnforce(false, true, enforceContext, ...rvals));
}
return generatorRunSync(this.privateEnforce(false, true, this.defaultEnforceContext, ...rvals));
}
/**
* Same as enforceSync. To be removed.
*/
public enforceWithSyncCompile(...rvals: any[]): boolean {
return this.enforceSync(...rvals);
}
/**
* enforce decides whether a "subject" can access a "object" with
* the operation "action", input parameters are usually: (sub, obj, act).
*
* @param rvals the request needs to be mediated, usually an array
* of strings, can be class instances if ABAC is used.
* @return whether to allow the request.
*/
public async enforce(...rvals: any[]): Promise<boolean> {
if (rvals[0] instanceof EnforceContext) {
const enforceContext: EnforceContext = rvals.shift();
return generatorRunAsync(this.privateEnforce(true, false, enforceContext, ...rvals));
}
return generatorRunAsync(this.privateEnforce(true, false, this.defaultEnforceContext, ...rvals));
}
/**
* enforce decides whether a "subject" can access a "object" with
* the operation "action", input parameters are usually: (sub, obj, act).
*
* @param rvals the request needs to be mediated, usually an array
* of strings, can be class instances if ABAC is used.
* @return whether to allow the request and the reason rule.
*/
public async enforceEx(...rvals: any[]): Promise<[boolean, string[]]> {
if (rvals[0] instanceof EnforceContext) {
const enforceContext: EnforceContext = rvals.shift();
return generatorRunAsync(this.privateEnforce(true, true, enforceContext, ...rvals));
}
return generatorRunAsync(this.privateEnforce(true, true, this.defaultEnforceContext, ...rvals));
}
}