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 attributes defined by glob notation (with nested object support).
- Ability to filter data (model) instance by allowed attributes.
- Ability to control access on "own" or "any" resources.
- Ability to control access using conditions.
- Supports AND, OR, NOT, EQUALS, NOT_EQUALS, STARTS_WITH, LIST_CONTAINS conditions
- Policies are JSON compatible so can be stored and retrieved from database.
- Fast. (Grants are stored in memory, no database queries.)
- TypeScript support.
Guide
const AccessControl = require('role-acl');
Basic Example
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').on('video');
console.log(permission.granted);
console.log(permission.attributes);
permission = ac.can('admin').execute('update').on('video');
console.log(permission.granted);
console.log(permission.attributes);
Conditions Examples
Define roles and grants one by one.
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').on('article');
console.log(permission.granted);
console.log(permission.attributes);
permission = ac.can('user').context({ category: 'tech' }).execute('create').on('article');
console.log(permission.granted);
console.log(permission.attributes);
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').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'}).on('article');
console(permission.attributes);
console(permission.granted);
permission = ac.can('sports/editor').execute('publish').with({category: 'politics'})).on('article');
console(permission.attributes).toEqual([]);
console(permission.granted).toEqual(false);
ac.grant({
role: 'politics/editor',
action: 'publish',
resource: 'article',
condition: {Fn: 'EQUALS', args: {category: 'politics'}},
attributes: attrs
});
permission = ac.can('politics/editor').execute('publish').with({category: 'politics'}).on('article');
console(permission.attributes).toEqual(attrs);
console(permission.granted).toEqual(true);
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: {
video: {
'create': ['*'],
'read': ['*'],
'update': ['*'],
'delete': ['*']
}
},
user: {
video: {
'create:own': ['*'],
'read:own': ['*'],
'update:own': ['*'],
'delete:own': ['*']
}
},
"sports/editor": {
article: {
"create:any": [
{
attributes: ["*"],
condition: {
Fn: 'EQUALS',
args: {
'category': 'sports'
}
}
}
],
"update:any": [
{
attributes: ["*"],
condition: {
Fn: 'EQUALS',
args: {
'category': 'sports'
}
}
}
]
}
},
"sports/writer": {
article: {
"create:any": [
{
attributes: ["*", "!status"],
condition: {
Fn: 'EQUALS',
args: {
'category': 'sports'
}
}
}
],
"update:any": [
{
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:own', attributes: ['*'] },
{ role: 'user', resource: 'video', action: 'read', attributes: ['*'] },
{ role: 'user', resource: 'video', action: 'update:own', attributes: ['*'] },
{ role: 'user', resource: 'video', action: 'delete:own', 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());
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').on('post');
console.log(permission.granted);
console.log(permission.attributes);
permission = 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').on('post');
console.log(permission.granted);
console.log(permission.attributes);
ac.extendRole('conditonal/sports-and-politics/editor', 'sports-and-politics/editor', {
Fn: 'EQUALS',
args: { status: 'draft' }
});
permission = ac.can('conditonal/sports-and-politics/editor').context({category: 'politics', status: 'draft'}).execute('create').on('post');
console.log(permission.granted);
console.log(permission.attributes);
permission = ac.can('conditonal/sports-and-politics/editor').context({category: 'politics', status: 'published'}).execute('create').on('post');
console.log(permission.granted);
console.log(permission.attributes);
Read more
More Examples
License
MIT.