Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

accesscontrol

onury148.8kMIT2.2.1TypeScript support: included

Role and Attribute based Access Control for Node.js

access, access-control, acl, role, attribute, grant, deny, allow, reject, permission, action, possession, rbac, abac, crud, create, read, update, delete, resource, express, admin, user, glob, wildcard, policy, scope, context

readme

build-status Coverage Status dependencies Known Vulnerabilities maintained
npm release license TypeScript documentation

© 2018, Onur Yıldırım (@onury). MIT License.

Role and Attribute based Access Control for Node.js

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 and action attributes.

Core Features

  • Chainable, friendly API.
    e.g. ac.can(role).create(resource)
  • Role hierarchical inheritance.
  • Define grants at once (e.g. from database result) or one by one.
  • Grant/deny 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 lock underlying grants model.
  • No silent errors.
  • Fast. (Grants are stored in memory, no database queries.)
  • Brutally tested.
  • TypeScript support.

In order to build on more solid foundations, this library (v1.5.0+) is completely re-written in TypeScript.

Installation

with npm: npm i accesscontrol --save

with yarn: yarn add accesscontrol

Guide

const AccessControl = require('accesscontrol');
// or:
// import { AccessControl } from 'accesscontrol';

Basic Example

Define roles and grants one by one.

const ac = new AccessControl();
ac.grant('user')                    // define new or modify existing role. also takes an array.
    .createOwn('video')             // equivalent to .createOwn('video', ['*'])
    .deleteOwn('video')
    .readAny('video')
  .grant('admin')                   // switch to another role without breaking the chain
    .extend('user')                 // inherit role capabilities. also takes an array
    .updateAny('video', ['title'])  // explicitly defined attributes
    .deleteAny('video');

const permission = ac.can('user').createOwn('video');
console.log(permission.granted);    // —> true
console.log(permission.attributes); // —> ['*'] (all attributes)

permission = ac.can('admin').updateAny('video');
console.log(permission.granted);    // —> true
console.log(permission.attributes); // —> ['title']

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).readAny('video');
    if (permission.granted) {
        Video.find(req.params.title, function (err, data) {
            if (err || !data) return res.status(404).end();
            // filter data by permission attributes and send.
            res.json(permission.filter(data));
        });
    } else {
        // resource is forbidden for this user/role
        res.status(403).end();
    }
});

Roles

You can create/define roles simply by calling .grant(<role>) or .deny(<role>) methods on an AccessControl instance.

  • Roles can extend other roles.
// user role inherits viewer role permissions
ac.grant('user').extend('viewer');
// admin role inherits both user and editor role permissions
ac.grant('admin').extend(['user', 'editor']);
// both admin and superadmin roles inherit moderator permissions
ac.grant(['admin', 'superadmin']).extend('moderator');
  • Inheritance is done by reference, so you can grant resource permissions before or after extending a role.
// case #1
ac.grant('admin').extend('user') // assuming user role already exists
  .grant('user').createOwn('video');

// case #2
ac.grant('user').createOwn('video')
  .grant('admin').extend('user');

// below results the same for both cases
const permission = ac.can('admin').createOwn('video');
console.log(permission.granted); // true

Notes on inheritance:

  • A role cannot extend itself.
  • Cross-inheritance is not allowed.
    e.g. ac.grant('user').extend('admin').grant('admin').extend('user') will throw.
  • A role cannot (pre)extend a non-existing role. In other words, you should first create the base role. e.g. ac.grant('baseRole').grant('role').extend('baseRole')

Actions and Action-Attributes

CRUD operations are the actions you can perform on a resource. There are two action-attributes which define the possession of the resource: own and any.

For example, an admin role can create, read, update or delete (CRUD) any account resource. But a user role might only read or update its own account resource.

Action Possession
Create
Read
Update
Delete
Own The C|R|U|D action is (or not) to be performed on own resource(s) of the current subject.
Any The C|R|U|D action is (or not) to be performed on any resource(s); including own.
ac.grant('role').readOwn('resource');
ac.deny('role').deleteAny('resource');

Note that own requires you to also check for the actual possession. See this for more.

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').readAny('video', ['*']);
// equivalent to:
// ac.grant('admin').readAny('video');

But the id attribute should not be read by a user role.

ac.grant('user').readOwn('video', ['*', '!id']);
// equivalent to:
// ac.grant('user').readOwn('video', ['title', 'runtime']);

You can also use nested objects (attributes).

ac.grant('user').readOwn('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').readOwn('account');
permission.granted;       // true
permission.attributes;    // ['*', '!record.id']
permission.filter(data);  // 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: {
        video: {
            'create:any': ['*', '!views'],
            'read:any': ['*'],
            'update:any': ['*', '!views'],
            'delete:any': ['*']
        }
    },
    user: {
        video: {
            'create:own': ['*', '!rating', '!views'],
            'read:own': ['*'],
            'update:own': ['*', '!rating', '!views'],
            'delete:own': ['*']
        }
    }
};
const ac = new AccessControl(grantsObject);

... or an Array (useful when fetched from a database):

// grant list fetched from DB (to be converted to a valid grants object, internally)
let grantList = [
    { role: 'admin', resource: 'video', action: 'create:any', attributes: '*, !views' },
    { role: 'admin', resource: 'video', action: 'read:any', attributes: '*' },
    { role: 'admin', resource: 'video', action: 'update:any', attributes: '*, !views' },
    { role: 'admin', resource: 'video', action: 'delete:any', attributes: '*' },

    { role: 'user', resource: 'video', action: 'create:own', attributes: '*, !rating, !views' },
    { role: 'user', resource: 'video', action: 'read:any', attributes: '*' },
    { role: 'user', resource: 'video', action: 'update:own', attributes: '*, !rating, !views' },
    { role: 'user', resource: 'video', action: 'delete:own', attributes: '*' }
];
const ac = new AccessControl(grantList);

You can set grants any time...

const ac = new AccessControl();
ac.setGrants(grantsObject);
console.log(ac.getGrants());

...unless you lock it:

ac.lock().setGrants({}); // throws after locked

Documentation

You can read the full API reference with lots of details, features and examples.
And more at the F.A.Q. section.

Change-Log

See CHANGELOG.

Contributing

Clone original project:

git clone https://github.com/onury/accesscontrol.git

Install dependencies:

npm install

Add tests to relevant file under /test directory and run:

npm run build && npm run cover

Use included tslint.json and editorconfig for style and linting.
Travis build should pass, coverage should not degrade.

License

MIT.

changelog

AccessControl - Change Log

v2.2.1 (2018-02-24)

  • Fixed an issue with attribute filtering caused by the core dependency Notation. Now fixed and updated.
  • (Dev) Updated dev-dependencies to latest versions. Removed yarn.

v2.2.0 (2017-11-25)

This release greatly improves stability!

  • Fixed an issue where action and possession of a permission query is not pre-normalized. Only #permission() method was affected.
  • Fixed an issue where it would throw even if $extend was used properly in the initial grants model, passed to the constructor or #setGrants(). Fixes issue #22.
  • Fixed a memory leak (leading to "maximum call stack" error) occurs while processing role hierarchy.
  • Fixed an issue where role validation would incorrectly return true in a specific case.
  • Revised #lock() to throw a meaningful error if not successful.
  • Revised #hasRole() and #hasResource() methods to also accept a string array (to check for multiple at once), in addition to string (single).
  • Revised various chain methods to throw when explicit invalid values are passed. e.g. ac.grant()... will not throw (omitted parameter allowed) but ac.grant(undefined)... will throw. This mitigates the chance of passing an unset variable by mistake.
  • Various revisions, optimizations and clean-up.
  • (Dev) Migrated tests to Jest. Refactored tests to TypeScript. Removed Jasmine and dependencies.
  • (Dev) Adapted yarn. Enabled test coverage via jest. Added coveralls support.
  • (Dev) Added moooore tests. Revised code style. Improved coverage.

v2.0.0 (2017-10-05)

  • Breaking-Change: Cross role inheritance is no more allowed. Fixes issue #18.
  • Breaking-Change: Grants model cannot be emptied any more by omitting the parameter (e.g. #setGrants()) or passing null, undefined. This will throw. You need to either, explicitly call #reset() or set grants to an empty object ({}) in order to reset/empty grants safely.
  • Breaking-Change: Renamed #access() to #query(). This is an alias for #can() method.
  • Fixed an issue where deeper inherited roles (more than 1 level) would not be taken into account while querying for permissions. Fixes issue #17.
  • Added AccessControl#lock() method that freezes the underlying grants model and disables all functionality for modifying it. This is useful when you want to restrict any changes. Any attempts to modify (such as #setGrants(), #grant(), #deny(), etc) will throw after grants are locked. There is no unlock() method. It's like you lock the door and swallow the key. :yum:
  • Added AccessControl#isLocked boolean property.
  • Added AccessControl#getInheritedRolesOf() convenience method.
  • Fixed a mutation issue occurred when resource attributes are unioned. (Notation issue #2).
  • Fixed an issue with unioned attributes (when a role extends another and attributes (globs) are unioned for querying permissions). Fixes issue #19 (Notation issue #3).
  • Added the ability to detect invalid grants object passed to AccessControl instance. In order to prevent silent, future errors and mistakes; AccessControl now thoroughly inspects the grants object passed to constructor or #setGrants() method; and throws immediately if it has an invalid structure or configuration.
  • Revised AccessControl to throw if any reserved keywords are used (i.e. for role, resource names) such as "$", "$extend".
  • Added the ability to parse comma-separated attributes. You can now use this, in addition to string arrays; for defining resource attributes.

v1.5.4 (2017-09-22)

  • Fixed an issue where the static method AccessControl.filter() does not return the filtered data properly. Fixes issue #16.

v1.5.3 (2017-08-25)

v1.5.2 (2017-07-02)

  • Fixed an issue where the grants were not processed into the inner grants model structure; if an array is passed to AccessControl constructor; instead of using .setGrants(). Fixes issue #10.

v1.5.1 (2017-05-24)

  • Fixed TS import issue. Use import { AccessControl } from 'accesscontrol' in TypeScript projects.

v1.5.0 (2017-03-08)

  • Improvement: Migrated whole code base to TypeScript.
  • Added more strict validation checks. It will now throw on invalid information passed for both grants and permission checks. This helps prevent typos, unintended permission checks, etc...
  • Fixed a bug where checking permission with multiple roles would mutate the permission attributes. Fixes issue #2.
  • Fixed a mutation issue when an access definition object (IAccessInfo instead of role(s)) passed to .grant() or .deny() methods.
  • Improvement: You could grant permissions for multiple roles at once. Now, you can also grant permissions for multiple resources at the same time. This is very handy when you permit all attributes of the resources; e.g. ac.grant(['admin', 'superadmin']).readAny(['account', 'video'], ['*']). The caveat is that the resources (most probably) have different attributes; so you can either permit all, or only common attributes (e.g. ['id', 'name']).
  • Improvement: Extending a role with a non-existent role will now throw.

v1.0.1 (2016-11-09)

  • Fixed a syntax issue that throws when permission filter is called. Fixes issue #1.
  • (Dev) added filter test.

v1.0.0 (2016-09-10)

  • initial release.