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 conditions.
- You can specify dynamic context values in the conditions using JSON Paths.
- You can define your own condition functions 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 = ;// or:// import { AccessControl } from 'role-acl';
Examples
Basic Examples
Define roles and grants one by one.
const ac = ;ac // define new or modify existing role. also takes an array. // equivalent to .execute('create').on('video', ['*']) // switch to another role without breaking the chain // inherit role capabilities. also takes an array // explicitly defined attributes ; const permission = ac; // <-- Sync Exampleconst permission = await ac; // <-- Async Exampleconsole; // —> trueconsole; // —> ['*'] (all attributes) permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsole; // —> trueconsole; // —> ['title']
Conditions Examples
const ac = ;ac; let permission = ac; // <-- Sync Examplelet permission = await ac; // <-- Async Exampleconsole; // —> trueconsole; // —> ['*'] (all attributes) permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsole; // —> falseconsole; // —> [] // Condition with dynamic context values using JSONPath// We can use this to allow only owner of the article to edit itac; permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsole; // —> true // We can use this to prevent someone to approve their own article so that it goes to review // by someone else before publishingac; permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsole; // —> false // Using custom/own condition functionsac;permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsole; // —> true
Wildcard (glob notation) Resource and Actions Examples
ac;ac; ac;permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsolepermissionattributes; // -> ['*']consolepermissiongranted; // -> true permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsolepermissionattributes; // -> ['*']consolepermissiongranted; // -> true permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsolepermissionattributes; // -> ['*']consolepermissiongranted; // -> true permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsolepermissiongranted; // -> false
Express.js Example
Check role permissions for the requested resource and action, if granted; respond with filtered attributes.
const ac = grants;// ...router;
Roles
You can create/define roles simply by calling .grant(<role>)
method on an AccessControl
instance.
Roles can extend other roles.
// user role inherits viewer role permissionsac;// admin role inherits both user and editor role permissionsac;// both admin and superadmin roles inherit moderator permissionsac;
Actions and Action-Attributes
ac;let permission = ac; // <-- Sync Examplelet permission = await ac; // <-- Async Exampleconsolepermissionattributes; // —> ['*'] (all attributes)consolepermissiongranted; // -> true ac;permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsolepermissionattributes; // —> ['*'] (all attributes)consolepermissiongranted; // -> true permission = ac); // <-- Sync Examplepermission = await ac); // <-- Async Exampleconsolepermissionattributes; // -> []consolepermissiongranted; // -> false
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;// equivalent to:// ac.grant('admin').execute('read').on('video');
But the id
attribute should not be read by a user
role.
ac;// equivalent to:// ac.grant('user').execute('read').on('video', ['title', 'runtime']);
You can also use nested objects (attributes).
ac;
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;permissiongranted; // truepermissionattributes; // ['*', '!record.id']permission; // filtered data (without record.id)
See express.js example.
Defining All Grants at Once
You can pass the grants directly to the AccessControl
constructor.
It accepts either an Object
:
// This is actually how the grants are maintained internally.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 = grantsObject;
... or an Array
(useful when fetched from a database):
// grant list fetched from Database (to be converted to a valid grants object, internally)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 = grantList;
You can set/get grants any time:
const ac = ;ac;console;// You can save ac.getGrants() to Database// Please note: User should be part of your code and wraps calls to User to table/collection.await User; // Retrieve from DBconst perms = await User;ac = AccessControl; // if your DB supports storing JSON natively then you can use following code.await User; // Retrieve from DBconst perms = await User;ac;
Extending Roles
const ac = ;const editorGrant = role: 'editor' resource: 'post' action: 'create' // action attributes: '*' // grant only;ac;// first level of extension (extending with condition)ac;ac; let permission = ac; // <-- Sync Examplelet permission = await ac; // <-- Async Exampleconsole; // —> trueconsole; // —> ['*'] permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsole; // —> falseconsole; // —> [] // second level of extension (extending without condition)ac;permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsole; // —> trueconsole; // —> ['*'] // third level of extension (extending with condition)ac; // <-- Async Example permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsole; // —> trueconsole; // —> ['*'] permission = ac; // <-- Sync Examplepermission = await ac; // <-- Async Exampleconsole; // —> falseconsole; // —> []
Allowed Resources and actions
const ac = ;ac;ac;ac; ac; ac;ac; // <-- Sync Example ac; console; // -> ['article', 'image'] console; // -> ['article', 'image'] console; // -> ['image'] console; // -> ['image']console; // -> ['article', 'category', 'image']console; // -> ['article', 'category', 'image']console; // -> ['article', 'category', 'image', 'video']console; // -> ['article', 'category', 'image', 'video']console; // -> ['article', 'category', 'image', 'video']console; // -> ['article', 'category', 'image', 'video'] console; // -> ['create']console; // -> ['create']console; // -> [] console; // -> [] console; // -> ['create', 'delete']console; // -> ['create', 'delete']console; // -> ['*']console; // -> ['*']console; // -> ['*']console; // -> ['*']
NOTE: allowedResources and allowedActions skip the conditions when context is not passed
Example for versions >= 4.0.0
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
- role-acl: MIT.
- AccessControl: MIT.
Contact us
This product is supported and actively developed by Tensult. You can contact us at info@tensult.com.