
Role, Attribute and conditions based Access Control for Node.js
npm i role-acl --save
Many RBAC (Role-Based Access Control) implementations differ, but the basics is widely adopted since it simulates real life role (job) assignments. But while data is getting more and more complex; you need to define policies on resources, subjects or even environments. This is called ABAC (Attribute-Based Access Control).
With the idea of merging the best features of the two (see this NIST paper); this library implements RBAC basics and also focuses on resource, action attributes and conditions.
This library is an extension of AccessControl. But I removed support for possession and deny statements from orginal implementation.
Core Features
- Chainable, friendly API.
e.g. ac.can(role).execute('create').on(resource)
- Role hierarchical inheritance.
- Define grants at once (e.g. from database result) or one by one.
- Grant permissions by resources and actions define by glob notation.
- Grant permissions by attributes defined by glob notation (with nested object support).
- Ability to filter data (model) instance by allowed attributes.
- Ability to control access using conditions.
- Supports AND, OR, NOT, EQUALS, NOT_EQUALS, STARTS_WITH, LIST_CONTAINS core conditions.
- You can specify dynamic context values in the core conditions using JSON Paths.
- Supports your own custom conditions e.g.
custom:isArticleOwner.
- You can define your own function conditions too but please note if you use custom functions instead of standard conditions, you won’t be able to save them as json in the DB.
- Policies are JSON compatible so can be stored and retrieved from database.
- Fast. (Grants are stored in memory, no database queries.)
- TypeScript support.
- Note:
- For versions < 4.0: follow this ReadMe.
Guide
const AccessControl = require('role-acl');
Examples
Basic Examples
Define roles and grants one by one.
const ac = new AccessControl();
ac.grant('user')
.execute('create').on('video')
.execute('delete').on('video')
.execute('read').on('video')
.grant('admin')
.extend('user')
.execute('update').on('video', ['title'])
.execute('delete').on('video');
const permission = ac.can('user').execute('create').sync().on('video');
const permission = await ac.can('user').execute('create').on('video');
console.log(permission.granted);
console.log(permission.attributes);
permission = ac.can('admin').execute('update').sync().on('video');
permission = await ac.can('admin').execute('update').on('video');
console.log(permission.granted);
console.log(permission.attributes);
Conditions Examples
const ac = new AccessControl();
ac.grant('user').condition(
{
Fn: 'EQUALS',
args: {
'category': 'sports'
}
}).execute('create').on('article');
let permission = ac.can('user').context({ category: 'sports' }).execute('create').sync().on('article');
let permission = await ac.can('user').context({ category: 'sports' }).execute('create').on('article');
console.log(permission.granted);
console.log(permission.attributes);
permission = ac.can('user').context({ category: 'tech' }).execute('create').sync().on('article');
permission = await ac.can('user').context({ category: 'tech' }).execute('create').on('article');
console.log(permission.granted);
console.log(permission.attributes);
ac.grant('user').condition(
{
Fn: 'EQUALS',
args: {
'requester': '$.owner'
}
}).execute('edit').on('article');
permission = ac.can('user').context({ requester: 'dilip', owner: 'dilip' }).execute('edit').sync().on('article');
permission = await ac.can('user').context({ requester: 'dilip', owner: 'dilip' }).execute('edit').on('article');
console.log(permission.granted);
ac.grant('user').condition(
{
Fn: 'NOT_EQUALS',
args: {
'requester': '$.owner'
}
}).execute('approve').on('article');
permission = ac.can('user').context({ requester: 'dilip', owner: 'dilip' }).execute('approve').sync().on('article');
permission = await ac.can('user').context({ requester: 'dilip', owner: 'dilip' }).execute('approve').on('article');
console.log(permission.granted);
ac.grant('user').condition(
(context) => {
return context.category !== 'politics'
}
).execute('create').on('article');
permission = ac.can('user').context({ category: 'sports' }).execute('create').sync().on('article');
permission = await ac.can('user').context({ category: 'sports' }).execute('create').on('article');
console.log(permission.granted);
Custom Conditions
You can declare your own conditions (requires version >= 4.5.2). Those declarations should be registerd with the library BEFORE your grants and permission checks. The custom condition declarations are allowing you to extend the library core conditions with your own business logic without sacrificing the abillity to serialize your grants.
Basic example:
const greaterOrEqual = (context, args) => {
if (!args || typeof args.level !== 'number') {
throw new Error('custom:gte requires "level" argument');
}
return +context.level >= args.level;
}
const ac = new AccessControl();
ac.registerConditionFunction('gte', greaterOrEqual);
ac.grant('user')
.condition({
Fn: 'custom:gte',
args: { level: 2 }
})
.execute('comment').on('article');
const permission1 = ac
.can('user')
.context({ level: 2 })
.execute('comment')
.sync()
.on('article');
console.log('LEVEL 2', permission1.granted);
const permission2 = ac
.can('user')
.context({ level: 1 })
.execute('comment')
.sync()
.on('article');
console.log('LEVEL 1', permission2.granted);
Argument is optional:
Custom condition argument is optional - same as core conditions.
const myConditions = {
isArticleOwner: (context) => {
return context.loginUserId && context.loginUserId === context.articleOwnerId
}
}
const ac = new AccessControl();
ac.registerConditionFunction('isArticleOwner', myConditions.isArticleOwner);
ac.grant("user").condition('custom:isArticleOwner')
.execute(['delete', 'update']).on('article');
ac.can('user').context({ loginUserId: 1, articleOwnerId: 1 })
.execute('update').sync().on('article');
Custom condition can be async:
import { asyncCheckResourceForUser } from './somewhere';
const myConditions = {
isResourceOwner: (context, args) => {
const { resource } = args || {};
const { loginUserId } = context;
return asyncCheckResourceForUser(resource, loginUserId, context[resource]);
}
}
const ac = new AccessControl();
ac.registerConditionFunction('isResourceOwner', myConditions.isResourceOwner);
ac.grant("user")
.condition({ Fn: 'custom:isResourceOwner', args: { resource: 'article' } })
.execute(['delete', 'update'])
.on('article');
await ac.can('user').context({ loginUserId: 1, article: { id: 10 } })
.execute('update').on('article');
Custom conditions allow security policy serializing and can be registered while initializing (in batch):
NOTE: function conditions are not serializeable, so custom conditions are the recommended way to implement your permission policy. You can easiely convert your current function conditions to custom conditions.
const myPolicy = {
grants: [
{
role: 'user',
resource: 'profile',
action: ['delete', 'update'],
attributes: ['*'],
condition: {
Fn: 'custom:isResourceOwner',
args: { resource: 'profile' }
}
},
{
role: 'user',
resource: 'article',
action: ['delete', 'update'],
attributes: ['*'],
condition: {
Fn: 'custom:isResourceOwner',
args: { resource: 'article' }
}
},
],
myConditions: {
isResourceOwner: async ({ user, record }, { resource } = {}) => {
if (resource === 'profile' && user.id === 1 && record.id === 1) {
return true;
}
if (resource === 'article' && user.id === 1 && record.id === 2) {
return true;
}
return false;
}
}
};
const ac = new AccessControl(myPolicy.grants, myPolicy.myConditions);
await ac.can('user').context({ user: { id: 1 }, record: { id: 1 } })
.execute('update').on('profile');
await ac.can('user').context({ user: { id: 1 }, record: { id: 1 } })
.execute('delete').on('article');
await ac.can('user').context({ user: { id: 1 }, record: { id: 2 } })
.execute('delete').on('article');
Mix with core conditions, use JSON path helper:
NOTE: getValueByPath is available in versions >= 4.5.5
const myPolicy = {
grants: [
{
role: 'editor/news',
resource: 'article',
action: 'approve',
attributes: ['*'],
condition: {
Fn: 'AND',
args: [
{
Fn: 'custom:categoryMatcher',
args: { type: 'news' }
},
{
Fn: 'custom:isResourceOwner',
args: { resource: 'article' }
}
]
}
},
],
myConditions: {
categoryMatcher: (context, { type } = {}) => {
return type && getValueByPath(context, '$.category.type') === type;
},
isResourceOwner: (context, { resource } = {}) => {
if (!resource) {
return false;
}
return getValueByPath(context, `$.${resource}.owner`) === getValueByPath(context, '$.user.id');
},
}
};
const ac = new AccessControl(myPolicy.grants, myPolicy.myConditions);
await ac.can('editor/news').context({ user: { id: 1 }, article: { owner: 1 }, category: { type: 'news' } })
.execute('approve').on('article');
await ac.can('editor/news').context({ user: { id: 1 }, article: { owner: 2 }, category: { type: 'news' } })
.execute('approve').on('article');
await ac.can('editor/news').context({ user: { id: 1 }, article: { owner: 1 }, category: { type: 'tutorials' } })
.execute('approve').on('article');
Wildcard (glob notation) Resource and Actions Examples
ac.grant({
role: 'politics/editor',
action: '*',
resource: 'article',
condition: {Fn: 'EQUALS', args: {category: 'politics'}},
attributes: ['*']
});
ac.grant({
role: 'politics/writer',
action: ['*', '!publish'],
resource: 'article',
condition: {Fn: 'EQUALS', args: {category: 'politics'}},
attributes: ['*']
});
ac.grant({
role: 'admin',
action: '*',
resource: '*',
condition: {Fn: 'EQUALS', args: {category: 'politics'}},
attributes: ['*']
});
permission = ac.can('politics/editor').execute('publish').with({category: 'politics'}).sync().on('article');
permission = await ac.can('politics/editor').execute('publish').with({category: 'politics'}).on('article');
console(permission.attributes);
console(permission.granted);
permission = ac.can('admin').execute('publish').with({category: 'politics'}).sync().on('article');
permission = await ac.can('admin').execute('publish').with({category: 'politics'}).on('article');
console(permission.attributes);
console(permission.granted);
permission = ac.can('admin').execute('publish').with({category: 'politics'}).sync().on('blog');
permission = await ac.can('admin').execute('publish').with({category: 'politics'}).on('blog');
console(permission.attributes);
console(permission.granted);
permission = ac.can('politics/writer').execute('publish').with({category: 'politics'}).sync().on('arti`cle');
permission = await ac.can('politics/writer').execute('publish').with({category: 'politics'}).on('arti`cle');
console(permission.granted);
Express.js Example
Check role permissions for the requested resource and action, if granted; respond with filtered attributes.
const ac = new AccessControl(grants);
router.get('/videos/:title', function (req, res, next) {
const permission = ac.can(req.user.role).execute('read').on('video');
if (permission.granted) {
Video.find(req.params.title, function (err, data) {
if (err || !data) return res.status(404).end();
res.json(permission.filter(data));
});
} else {
res.status(403).end();
}
});
Roles
You can create/define roles simply by calling .grant(<role>) method on an AccessControl instance.
Roles can extend other roles.
ac.grant('user').extend('viewer');
ac.grant('admin').extend(['user', 'editor']);
ac.grant(['admin', 'superadmin']).extend('moderator');
Actions and Action-Attributes
ac.grant('editor').execute('publish').on('article');
let permission = ac.can('editor').execute('publish').sync().on('article');
let permission = await ac.can('editor').execute('publish').on('article');
console(permission.attributes);
console(permission.granted);
ac.grant('sports/editor').execute('publish').when({Fn: 'EQUALS', args: {category: 'sports'}}).on('article');
permission = ac.can('sports/editor').execute('publish').with({category: 'sports'}).sync().on('article');
permission = await ac.can('sports/editor').execute('publish').with({category: 'sports'}).on('article');
console(permission.attributes);
console(permission.granted);
permission = ac.can('sports/editor').execute('publish').with({category: 'politics'})).sync().on('article');
permission = await ac.can('sports/editor').execute('publish').with({category: 'politics'})).on('article');
console(permission.attributes);
console(permission.granted);
Resources and Resource-Attributes
Multiple roles can have access to a specific resource. But depending on the context, you may need to limit the contents of the resource for specific roles.
This is possible by resource attributes. You can use Glob notation to define allowed or denied attributes.
For example, we have a video resource that has the following attributes: id, title and runtime.
All attributes of any video resource can be read by an admin role:
ac.grant('admin').execute('read').on('video', ['*']);
But the id attribute should not be read by a user role.
ac.grant('user').execute('read').on('video', ['*', '!id']);
You can also use nested objects (attributes).
ac.grant('user').execute('read').on('account', ['*', '!record.id']);
Checking Permissions and Filtering Attributes
You can call .can(<role>).<action>(<resource>) on an AccessControl instance to check for granted permissions for a specific resource and action.
const permission = ac.can('user').execute('read').on('account');
permission.granted;
permission.attributes;
permission.filter(data);
See express.js example.
Defining All Grants at Once
You can pass the grants directly to the AccessControl constructor.
It accepts either an Object:
let grantsObject = {
admin: {
grants: [
{
resource: 'video', action: '*', attributes: ['*']
}
]
},
user: {
grants: [
{
resource: 'video', action: 'create', attributes: ['*']
},
{
resource: 'video', action: 'read', attributes: ['*']
},
{
resource: 'video', action: 'update', attributes: ['*']
},
{
resource: 'video', action: 'delete', attributes: ['*']
},
]
},
"sports/editor": {
grants: [
{
resource: 'article',
action: '*',
attributes: ["*"],
condition: {
Fn: 'EQUALS',
args: {
'category': 'sports'
}
}
}
]
},
"sports/writer": {
grants: [
{
resource: 'article',
action: ['create', 'update'],
attributes: ["*", "!status"],
condition: {
Fn: 'EQUALS',
args: {
'category': 'sports'
}
}
}
]
}
};
const ac = new AccessControl(grantsObject);
… or an Array (useful when fetched from a database):
let grantList = [
{ role: 'admin', resource: 'video', action: 'create', attributes: ['*'] },
{ role: 'admin', resource: 'video', action: 'read', attributes: ['*'] },
{ role: 'admin', resource: 'video', action: 'update', attributes: ['*'] },
{ role: 'admin', resource: 'video', action: 'delete', attributes: ['*'] },
{ role: 'user', resource: 'video', action: 'create', attributes: ['*'] },
{ role: 'user', resource: 'video', action: 'read', attributes: ['*'] },
{ role: 'user', resource: 'video', action: 'update', attributes: ['*'] },
{ role: 'user', resource: 'video', action: 'delete', attributes: ['*'] },
{ role: 'user', resource: 'photo', action: '*', attributes: ['*'] },
{ role: 'user', resource: 'article', action: ['*', '!delete'], attributes: ['*'] },
{ role: 'sports/editor', resource: 'article', action: 'create', attributes: ['*'],
condition: { "Fn": "EQUALS", "args": { "category": "sports" } }
},
{
role: 'sports/editor', resource: 'article', action: 'update', attributes: ['*'],
condition: { "Fn": "EQUALS", "args": { "category": "sports" } }
}
];
const ac = new AccessControl(grantList);
You can set/get grants any time:
const ac = new AccessControl();
ac.setGrants(grantsObject);
console.log(ac.getGrants());
await User.save({permissions: acl.toJSON()});
const perms = await User.getBydId(userId);
ac = AccessControl.fromJSON(user.permissions);
await User.save({permissions: acl.getGrants()});
const perms = await User.getBydId(userId);
ac.setGrants(user.permissions);
Extending Roles
const ac = new AccessControl();
const editorGrant = {
role: 'editor',
resource: 'post',
action: 'create',
attributes: ['*']
};
ac.grant(editorGrant);
ac.extendRole('sports/editor', 'editor', {Fn: 'EQUALS', args: {category: 'sports'}});
ac.extendRole('politics/editor', 'editor', {Fn: 'EQUALS', args: {category: 'politics'}});
let permission = ac.can('sports/editor').context({category: 'sports'}).execute('create').sync().on('post');
let permission = await ac.can('sports/editor').context({category: 'sports'}).execute('create').on('post');
console.log(permission.granted);
console.log(permission.attributes);
permission = ac.can('sports/editor').context({category: 'politics'}).execute('create').sync().on('post');
permission = await ac.can('sports/editor').context({category: 'politics'}).execute('create').on('post');
console.log(permission.granted);
console.log(permission.attributes);
ac.extendRole('sports-and-politics/editor', ['sports/editor', 'politics/editor']);
permission = ac.can('sports-and-politics/editor').context({category: 'politics'}).execute('create').sync().on('post');
permission = await ac.can('sports-and-politics/editor').context({category: 'politics'}).execute('create').on('post');
console.log(permission.granted);
console.log(permission.attributes);
ac.extendRole('conditional/sports-and-politics/editor', 'sports-and-politics/editor', {
Fn: 'EQUALS',
args: { status: 'draft' }
});
permission = ac.can('conditional/sports-and-politics/editor').context({category: 'politics', status: 'draft'}).execute('create').sync().on('post');
permission = await ac.can('conditional/sports-and-politics/editor').context({category: 'politics', status: 'draft'}).execute('create').on('post');
console.log(permission.granted);
console.log(permission.attributes);
permission = ac.can('conditional/sports-and-politics/editor').context({category: 'politics', status: 'published'}).execute('create').sync().on('post');
permission = await ac.can('conditional/sports-and-politics/editor').context({category: 'politics', status: 'published'}).execute('create').on('post');
console.log(permission.granted);
console.log(permission.attributes);
Allowed Resources and actions
const ac = new AccessControl();
ac.grant('user').condition({Fn: 'EQUALS', args: {category: 'sports'}}).execute('create').on('article');
ac.grant('user').execute('*').on('image');
ac.extendRole('admin', 'user');
ac.grant('admin').execute('delete').on('article');
ac.grant('admin').execute('*').on('category');
ac.extendRole('owner', 'admin');
ac.grant('owner').execute('*').on('video');
console.log(ac.allowedResourcesSync({role: 'user'}).sort());
console.log(await ac.allowedResources({role: 'user'}).sort());
console.log(ac.allowedResourcesSync({role: 'user', context: {category: 'politics'}}).sort());
console.log(await ac.allowedResources({role: 'user', context: {category: 'politics'}}).sort());
console.log(ac.allowedResourcesSync({role: 'admin'}).sort());
console.log(await ac.allowedResources({role: 'admin'}).sort());
console.log(ac.allowedResourcesSync({role: 'owner'}).sort());
console.log(await ac.allowedResources({role: 'owner'}).sort());
console.log(ac.allowedResourcesSync({role: ['admin', 'owner']}).sort());
console.log(await ac.allowedResources({role: ['admin', 'owner']}).sort());
console.log(ac.allowedActionsSync({role: 'user', resource: 'article'}).sort());
console.log(await ac.allowedActions({role: 'user', resource: 'article'}).sort());
console.log(ac.allowedActionsSync({role: 'user', resource: 'article', context: {category: 'politics'}}));
console.log(await ac.allowedActions({role: 'user', resource: 'article', context: {category: 'politics'}}));
console.log(ac.allowedActionsSync({role: ['admin', 'user'], resource: 'article'}).sort());
console.log(await ac.allowedActions({role: ['admin', 'user'], resource: 'article'}).sort());
console.log(ac.allowedActionsSync({role: 'admin', resource: 'category'}).sort());
console.log(await ac.allowedActions({role: 'admin', resource: 'category'}).sort());
console.log(ac.allowedActionsSync({role: 'owner', resource: 'video'}).sort());
console.log(await ac.allowedActions({role: 'owner', resource: 'video'}).sort());
NOTE: allowedResources and allowedActions skip the conditions when context is not passed
Example for versions >= 4.0.0
Take a look at the test cases
Upgrading to >= 4.0.0
- There are many breaking changes so please update the code accordingly.
- All future updates and bug fixes will happen only to versions >= 4.
- New features only available in >= 4
- Storing and retrieving of custom condition functions.
- Promise based conditional functions.
- For Sync use cases use function with Sync suffix.
Licenses
This product is supported and actively developed by Tensult. You can contact us at [email protected].
评论